repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
stephanepechard/projy
projy/collectors/AuthorMailCollector.py
AuthorMailCollector.author_mail_from_system
python
def author_mail_from_system(self): self.author_mail = getpass.getuser() + '@' + socket.gethostname() return self.author_mail
Get the author mail from system information. It is probably often innacurate.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/collectors/AuthorMailCollector.py#L42-L47
null
class AuthorMailCollector(Collector): """ The AuthorMailCollector class. """ def __init__(self): self.author_mail = None def author_mail_from_git(self): """ Get the author mail from git information. """ try: # launch git command and get answer cmd = Popen(["git", "config", "--get", "user.email"], stdout=PIPE) stdoutdata = cmd.communicate() if (stdoutdata[0]): self.author_mail = stdoutdata[0].rstrip(os.linesep) except ImportError: pass except CalledProcessError: pass except OSError: pass return self.author_mail
stephanepechard/projy
projy/templates/LaTeXBookTemplate.py
LaTeXBookTemplate.files
python
def files(self): files_description = [ [ self.project_name, self.project_name + '.tex', 'LaTeXBookFileTemplate' ], [ self.project_name, 'references.bib', 'BibTeXFileTemplate' ], [ self.project_name, 'Makefile', 'LaTeXMakefileFileTemplate' ], ] return files_description
Return the names of files to be created.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/LaTeXBookTemplate.py#L27-L43
null
class LaTeXBookTemplate(ProjyTemplate): """ Projy template for a LaTeX project. """ def __init__(self): ProjyTemplate.__init__(self) def directories(self): """ Return the names of directories to be created. """ directories_description = [ self.project_name, ] return directories_description def substitutes(self): """ Return the substitutions for the templating replacements. """ author_collector = AuthorCollector() substitute_dict = dict( project = self.project_name, date = date.today().isoformat(), author = author_collector.collect() ) return substitute_dict
stephanepechard/projy
projy/templates/LaTeXBookTemplate.py
LaTeXBookTemplate.substitutes
python
def substitutes(self): author_collector = AuthorCollector() substitute_dict = dict( project = self.project_name, date = date.today().isoformat(), author = author_collector.collect() ) return substitute_dict
Return the substitutions for the templating replacements.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/LaTeXBookTemplate.py#L46-L54
[ "def collect(self):\n \"\"\" Select the best suited data of all available in the subclasses.\n In each subclass, the functions alphabetical order should\n correspond to their importance.\n Here, the first non null value is returned.\n \"\"\"\n class_functions = []\n for key in self....
class LaTeXBookTemplate(ProjyTemplate): """ Projy template for a LaTeX project. """ def __init__(self): ProjyTemplate.__init__(self) def directories(self): """ Return the names of directories to be created. """ directories_description = [ self.project_name, ] return directories_description def files(self): """ Return the names of files to be created. """ files_description = [ [ self.project_name, self.project_name + '.tex', 'LaTeXBookFileTemplate' ], [ self.project_name, 'references.bib', 'BibTeXFileTemplate' ], [ self.project_name, 'Makefile', 'LaTeXMakefileFileTemplate' ], ] return files_description
stephanepechard/projy
projy/templates/DjangoProjectTemplate.py
DjangoProjectTemplate.directories
python
def directories(self): directories_description = [ self.project_name, self.project_name + '/conf', self.project_name + '/static', ] return directories_description
Return the names of directories to be created.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/DjangoProjectTemplate.py#L23-L30
null
class DjangoProjectTemplate(ProjyTemplate): """ Projy template class for PythonPackage. """ def __init__(self): ProjyTemplate.__init__(self) def files(self): """ Return the names of files to be created. """ files_description = [ # configuration [ self.project_name, 'Makefile', 'DjangoMakefileTemplate' ], [ self.project_name + '/conf', 'requirements_base.txt', 'DjangoRequirementsBaseTemplate' ], [ self.project_name + '/conf', 'requirements_dev.txt', 'DjangoRequirementsDevTemplate' ], [ self.project_name + '/conf', 'requirements_production.txt', 'DjangoRequirementsProdTemplate' ], [ self.project_name + '/conf', 'nginx.conf', 'DjangoNginxConfTemplate' ], [ self.project_name + '/conf', 'supervisord.conf', 'DjangoSupervisorConfTemplate' ], [ self.project_name, 'fabfile.py', 'DjangoFabfileTemplate' ], [ self.project_name, 'CHANGES.txt', 'PythonPackageCHANGESFileTemplate' ], [ self.project_name, 'LICENSE.txt', 'GPL3FileTemplate' ], [ self.project_name, 'README.txt', 'READMEReSTFileTemplate' ], [ self.project_name, '.gitignore', 'DjangoGitignoreTemplate' ], # django files [ self.project_name, 'dev.py', 'DjangoSettingsDevTemplate' ], [ self.project_name, 'prod.py', 'DjangoSettingsProdTemplate' ], ] return files_description def substitutes(self): """ Return the substitutions for the templating replacements. """ author_collector = AuthorCollector() mail_collector = AuthorMailCollector() substitute_dict = { 'project': self.project_name, 'project_lower': self.project_name.lower(), 'date': date.today().isoformat(), 'author': author_collector.collect(), 'author_email': mail_collector.collect(), } return substitute_dict def posthook(self): # build the virtualenv call(['make']) # create the Django project call(['./venv/bin/django-admin.py', 'startproject', self.project_name]) # transform original settings files into 3 files for different env mkdir('{p}/settings'.format(p=self.project_name)) self.touch('{p}/settings/__init__.py'.format(p=self.project_name)) move('dev.py', '{p}/settings'.format(p=self.project_name)) move('prod.py', '{p}/settings'.format(p=self.project_name)) move('{p}/{p}/settings.py'.format(p=self.project_name), '{p}/settings/base.py'.format(p=self.project_name)) # organize files nicely mkdir('{p}/templates'.format(p=self.project_name)) move('{p}/manage.py'.format(p=self.project_name), 'manage.py') move('{p}/{p}/__init__.py'.format(p=self.project_name), '{p}/'.format(p=self.project_name)) move('{p}/{p}/urls.py'.format(p=self.project_name), '{p}/'.format(p=self.project_name)) move('{p}/{p}/wsgi.py'.format(p=self.project_name), '{p}/'.format(p=self.project_name)) rmdir('{p}/{p}'.format(p=self.project_name)) # create empty git repo call(['git', 'init']) # replace some lines self.replace_in_file('{p}/wsgi.py'.format(p=self.project_name), '"{p}.settings"'.format(p=self.project_name), '"{p}.settings.production"'.format(p=self.project_name)) self.replace_in_file('{p}/settings/base.py'.format(p=self.project_name), u" # ('Your Name', 'your_email@example.com'),", u" ('{}', '{}'),".format(self.substitutes()['author'], self.substitutes()['author_email']))
stephanepechard/projy
projy/templates/DjangoProjectTemplate.py
DjangoProjectTemplate.substitutes
python
def substitutes(self): author_collector = AuthorCollector() mail_collector = AuthorMailCollector() substitute_dict = { 'project': self.project_name, 'project_lower': self.project_name.lower(), 'date': date.today().isoformat(), 'author': author_collector.collect(), 'author_email': mail_collector.collect(), } return substitute_dict
Return the substitutions for the templating replacements.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/DjangoProjectTemplate.py#L81-L92
[ "def collect(self):\n \"\"\" Select the best suited data of all available in the subclasses.\n In each subclass, the functions alphabetical order should\n correspond to their importance.\n Here, the first non null value is returned.\n \"\"\"\n class_functions = []\n for key in self....
class DjangoProjectTemplate(ProjyTemplate): """ Projy template class for PythonPackage. """ def __init__(self): ProjyTemplate.__init__(self) def directories(self): """ Return the names of directories to be created. """ directories_description = [ self.project_name, self.project_name + '/conf', self.project_name + '/static', ] return directories_description def files(self): """ Return the names of files to be created. """ files_description = [ # configuration [ self.project_name, 'Makefile', 'DjangoMakefileTemplate' ], [ self.project_name + '/conf', 'requirements_base.txt', 'DjangoRequirementsBaseTemplate' ], [ self.project_name + '/conf', 'requirements_dev.txt', 'DjangoRequirementsDevTemplate' ], [ self.project_name + '/conf', 'requirements_production.txt', 'DjangoRequirementsProdTemplate' ], [ self.project_name + '/conf', 'nginx.conf', 'DjangoNginxConfTemplate' ], [ self.project_name + '/conf', 'supervisord.conf', 'DjangoSupervisorConfTemplate' ], [ self.project_name, 'fabfile.py', 'DjangoFabfileTemplate' ], [ self.project_name, 'CHANGES.txt', 'PythonPackageCHANGESFileTemplate' ], [ self.project_name, 'LICENSE.txt', 'GPL3FileTemplate' ], [ self.project_name, 'README.txt', 'READMEReSTFileTemplate' ], [ self.project_name, '.gitignore', 'DjangoGitignoreTemplate' ], # django files [ self.project_name, 'dev.py', 'DjangoSettingsDevTemplate' ], [ self.project_name, 'prod.py', 'DjangoSettingsProdTemplate' ], ] return files_description def posthook(self): # build the virtualenv call(['make']) # create the Django project call(['./venv/bin/django-admin.py', 'startproject', self.project_name]) # transform original settings files into 3 files for different env mkdir('{p}/settings'.format(p=self.project_name)) self.touch('{p}/settings/__init__.py'.format(p=self.project_name)) move('dev.py', '{p}/settings'.format(p=self.project_name)) move('prod.py', '{p}/settings'.format(p=self.project_name)) move('{p}/{p}/settings.py'.format(p=self.project_name), '{p}/settings/base.py'.format(p=self.project_name)) # organize files nicely mkdir('{p}/templates'.format(p=self.project_name)) move('{p}/manage.py'.format(p=self.project_name), 'manage.py') move('{p}/{p}/__init__.py'.format(p=self.project_name), '{p}/'.format(p=self.project_name)) move('{p}/{p}/urls.py'.format(p=self.project_name), '{p}/'.format(p=self.project_name)) move('{p}/{p}/wsgi.py'.format(p=self.project_name), '{p}/'.format(p=self.project_name)) rmdir('{p}/{p}'.format(p=self.project_name)) # create empty git repo call(['git', 'init']) # replace some lines self.replace_in_file('{p}/wsgi.py'.format(p=self.project_name), '"{p}.settings"'.format(p=self.project_name), '"{p}.settings.production"'.format(p=self.project_name)) self.replace_in_file('{p}/settings/base.py'.format(p=self.project_name), u" # ('Your Name', 'your_email@example.com'),", u" ('{}', '{}'),".format(self.substitutes()['author'], self.substitutes()['author_email']))
stephanepechard/projy
projy/templates/ProjyTemplate.py
ProjyTemplate.create
python
def create(self, project_name, template_name, substitutions): self.project_name = project_name self.template_name = template_name # create substitutions dictionary from user arguments # TODO: check what is given for subs in substitutions: current_sub = subs.split(',') current_key = current_sub[0].strip() current_val = current_sub[1].strip() self.substitutes_dict[current_key] = current_val self.term.print_info(u"Creating project '{0}' with template {1}" .format(self.term.text_in_color(project_name, TERM_PINK), template_name)) self.make_directories() self.make_files() self.make_posthook()
Launch the project creation.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/ProjyTemplate.py#L27-L45
[ "def make_directories(self):\n \"\"\" Create the directories of the template. \"\"\"\n\n # get the directories from the template\n directories = []\n try:\n directories = self.directories()\n except AttributeError:\n self.term.print_info(u\"No directory in the template.\")\n\n workin...
class ProjyTemplate: """ Base template class for a Projy project creation. """ def __init__(self): self.project_name = None self.template_name = None self.substitutes_dict = {} self.term = TerminalView() def make_directories(self): """ Create the directories of the template. """ # get the directories from the template directories = [] try: directories = self.directories() except AttributeError: self.term.print_info(u"No directory in the template.") working_dir = os.getcwd() # iteratively create the directories for directory in directories: dir_name = working_dir + '/' + directory if not os.path.isdir(dir_name): try: os.makedirs(dir_name) except OSError as error: if error.errno != errno.EEXIST: raise else: self.term.print_error_and_exit(u"The directory {0} already exists." .format(directory)) self.term.print_info(u"Creating directory '{0}'" .format(self.term.text_in_color(directory, TERM_GREEN))) def make_files(self): """ Create the files of the template. """ # get the files from the template files = [] try: files = self.files() except AttributeError: self.term.print_info(u"No file in the template. Weird, but why not?") # get the substitutes intersecting the template and the cli try: for key in self.substitutes().keys(): if key not in self.substitutes_dict: self.substitutes_dict[key] = self.substitutes()[key] except AttributeError: self.term.print_info(u"No substitute in the template.") working_dir = os.getcwd() # iteratively create the files for directory, name, template_file in files: if directory: filepath = working_dir + '/' + directory + '/' + name filename = directory + '/' + name else: filepath = working_dir + '/' + name filename = name # open the file to write into try: output = open(filepath, 'w') except IOError: self.term.print_error_and_exit(u"Can't create destination"\ " file: {0}".format(filepath)) # open the template to read from if template_file: input_file = join(dirname(__file__), template_file + '.txt') # write each line of input file into output file, # templatized with substitutes try: with open(input_file, 'r') as line: template_line = Template(line.read()) try: output.write(template_line. safe_substitute(self.substitutes_dict).encode('utf-8')) except TypeError: output.write(template_line. safe_substitute(self.substitutes_dict)) output.close() except IOError: self.term.print_error_and_exit(u"Can't create template file"\ ": {0}".format(input_file)) else: output.close() # the file is empty, but still created self.term.print_info(u"Creating file '{0}'" .format(self.term.text_in_color(filename, TERM_YELLOW))) def make_posthook(self): """ Run the post hook into the project directory. """ print(id(self.posthook), self.posthook) print(id(super(self.__class__, self).posthook), super(self.__class__, self).posthook) import ipdb;ipdb.set_trace() if self.posthook: os.chdir(self.project_name) # enter the project main directory self.posthook() def replace_in_file(self, file_path, old_exp, new_exp): """ In the given file, replace all 'old_exp' by 'new_exp'. """ self.term.print_info(u"Making replacement into {}" .format(self.term.text_in_color(file_path, TERM_GREEN))) # write the new version into a temporary file tmp_file = tempfile.NamedTemporaryFile(mode='w+t', delete=False) for filelineno, line in enumerate(io.open(file_path, encoding="utf-8")): if old_exp in line: line = line.replace(old_exp, new_exp) try: tmp_file.write(line.encode('utf-8')) except TypeError: tmp_file.write(line) name = tmp_file.name # keep the name tmp_file.close() shutil.copy(name, file_path) # replace the original one os.remove(name) def touch(self, filename): """ A simple equivalent of the well known shell 'touch' command. """ with file(filename, 'a'): os.utime(filename, None) def posthook(self): """ Empty post-hook, to be inherited. """ pass
stephanepechard/projy
projy/templates/ProjyTemplate.py
ProjyTemplate.make_directories
python
def make_directories(self): # get the directories from the template directories = [] try: directories = self.directories() except AttributeError: self.term.print_info(u"No directory in the template.") working_dir = os.getcwd() # iteratively create the directories for directory in directories: dir_name = working_dir + '/' + directory if not os.path.isdir(dir_name): try: os.makedirs(dir_name) except OSError as error: if error.errno != errno.EEXIST: raise else: self.term.print_error_and_exit(u"The directory {0} already exists." .format(directory)) self.term.print_info(u"Creating directory '{0}'" .format(self.term.text_in_color(directory, TERM_GREEN)))
Create the directories of the template.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/ProjyTemplate.py#L48-L73
[ "def print_error_and_exit(self, message):\n \"\"\" Print an error in red and exits the program. \"\"\"\n sys.exit(self.term.bold_red('[ERROR] ' + message))\n", "def print_info(self, message):\n \"\"\" Print an informational text. \"\"\"\n print(message)\n", "def text_in_color(self, message, color_co...
class ProjyTemplate: """ Base template class for a Projy project creation. """ def __init__(self): self.project_name = None self.template_name = None self.substitutes_dict = {} self.term = TerminalView() def create(self, project_name, template_name, substitutions): """ Launch the project creation. """ self.project_name = project_name self.template_name = template_name # create substitutions dictionary from user arguments # TODO: check what is given for subs in substitutions: current_sub = subs.split(',') current_key = current_sub[0].strip() current_val = current_sub[1].strip() self.substitutes_dict[current_key] = current_val self.term.print_info(u"Creating project '{0}' with template {1}" .format(self.term.text_in_color(project_name, TERM_PINK), template_name)) self.make_directories() self.make_files() self.make_posthook() def make_files(self): """ Create the files of the template. """ # get the files from the template files = [] try: files = self.files() except AttributeError: self.term.print_info(u"No file in the template. Weird, but why not?") # get the substitutes intersecting the template and the cli try: for key in self.substitutes().keys(): if key not in self.substitutes_dict: self.substitutes_dict[key] = self.substitutes()[key] except AttributeError: self.term.print_info(u"No substitute in the template.") working_dir = os.getcwd() # iteratively create the files for directory, name, template_file in files: if directory: filepath = working_dir + '/' + directory + '/' + name filename = directory + '/' + name else: filepath = working_dir + '/' + name filename = name # open the file to write into try: output = open(filepath, 'w') except IOError: self.term.print_error_and_exit(u"Can't create destination"\ " file: {0}".format(filepath)) # open the template to read from if template_file: input_file = join(dirname(__file__), template_file + '.txt') # write each line of input file into output file, # templatized with substitutes try: with open(input_file, 'r') as line: template_line = Template(line.read()) try: output.write(template_line. safe_substitute(self.substitutes_dict).encode('utf-8')) except TypeError: output.write(template_line. safe_substitute(self.substitutes_dict)) output.close() except IOError: self.term.print_error_and_exit(u"Can't create template file"\ ": {0}".format(input_file)) else: output.close() # the file is empty, but still created self.term.print_info(u"Creating file '{0}'" .format(self.term.text_in_color(filename, TERM_YELLOW))) def make_posthook(self): """ Run the post hook into the project directory. """ print(id(self.posthook), self.posthook) print(id(super(self.__class__, self).posthook), super(self.__class__, self).posthook) import ipdb;ipdb.set_trace() if self.posthook: os.chdir(self.project_name) # enter the project main directory self.posthook() def replace_in_file(self, file_path, old_exp, new_exp): """ In the given file, replace all 'old_exp' by 'new_exp'. """ self.term.print_info(u"Making replacement into {}" .format(self.term.text_in_color(file_path, TERM_GREEN))) # write the new version into a temporary file tmp_file = tempfile.NamedTemporaryFile(mode='w+t', delete=False) for filelineno, line in enumerate(io.open(file_path, encoding="utf-8")): if old_exp in line: line = line.replace(old_exp, new_exp) try: tmp_file.write(line.encode('utf-8')) except TypeError: tmp_file.write(line) name = tmp_file.name # keep the name tmp_file.close() shutil.copy(name, file_path) # replace the original one os.remove(name) def touch(self, filename): """ A simple equivalent of the well known shell 'touch' command. """ with file(filename, 'a'): os.utime(filename, None) def posthook(self): """ Empty post-hook, to be inherited. """ pass
stephanepechard/projy
projy/templates/ProjyTemplate.py
ProjyTemplate.make_files
python
def make_files(self): # get the files from the template files = [] try: files = self.files() except AttributeError: self.term.print_info(u"No file in the template. Weird, but why not?") # get the substitutes intersecting the template and the cli try: for key in self.substitutes().keys(): if key not in self.substitutes_dict: self.substitutes_dict[key] = self.substitutes()[key] except AttributeError: self.term.print_info(u"No substitute in the template.") working_dir = os.getcwd() # iteratively create the files for directory, name, template_file in files: if directory: filepath = working_dir + '/' + directory + '/' + name filename = directory + '/' + name else: filepath = working_dir + '/' + name filename = name # open the file to write into try: output = open(filepath, 'w') except IOError: self.term.print_error_and_exit(u"Can't create destination"\ " file: {0}".format(filepath)) # open the template to read from if template_file: input_file = join(dirname(__file__), template_file + '.txt') # write each line of input file into output file, # templatized with substitutes try: with open(input_file, 'r') as line: template_line = Template(line.read()) try: output.write(template_line. safe_substitute(self.substitutes_dict).encode('utf-8')) except TypeError: output.write(template_line. safe_substitute(self.substitutes_dict)) output.close() except IOError: self.term.print_error_and_exit(u"Can't create template file"\ ": {0}".format(input_file)) else: output.close() # the file is empty, but still created self.term.print_info(u"Creating file '{0}'" .format(self.term.text_in_color(filename, TERM_YELLOW)))
Create the files of the template.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/ProjyTemplate.py#L76-L135
[ "def print_error_and_exit(self, message):\n \"\"\" Print an error in red and exits the program. \"\"\"\n sys.exit(self.term.bold_red('[ERROR] ' + message))\n", "def print_info(self, message):\n \"\"\" Print an informational text. \"\"\"\n print(message)\n", "def text_in_color(self, message, color_co...
class ProjyTemplate: """ Base template class for a Projy project creation. """ def __init__(self): self.project_name = None self.template_name = None self.substitutes_dict = {} self.term = TerminalView() def create(self, project_name, template_name, substitutions): """ Launch the project creation. """ self.project_name = project_name self.template_name = template_name # create substitutions dictionary from user arguments # TODO: check what is given for subs in substitutions: current_sub = subs.split(',') current_key = current_sub[0].strip() current_val = current_sub[1].strip() self.substitutes_dict[current_key] = current_val self.term.print_info(u"Creating project '{0}' with template {1}" .format(self.term.text_in_color(project_name, TERM_PINK), template_name)) self.make_directories() self.make_files() self.make_posthook() def make_directories(self): """ Create the directories of the template. """ # get the directories from the template directories = [] try: directories = self.directories() except AttributeError: self.term.print_info(u"No directory in the template.") working_dir = os.getcwd() # iteratively create the directories for directory in directories: dir_name = working_dir + '/' + directory if not os.path.isdir(dir_name): try: os.makedirs(dir_name) except OSError as error: if error.errno != errno.EEXIST: raise else: self.term.print_error_and_exit(u"The directory {0} already exists." .format(directory)) self.term.print_info(u"Creating directory '{0}'" .format(self.term.text_in_color(directory, TERM_GREEN))) def make_posthook(self): """ Run the post hook into the project directory. """ print(id(self.posthook), self.posthook) print(id(super(self.__class__, self).posthook), super(self.__class__, self).posthook) import ipdb;ipdb.set_trace() if self.posthook: os.chdir(self.project_name) # enter the project main directory self.posthook() def replace_in_file(self, file_path, old_exp, new_exp): """ In the given file, replace all 'old_exp' by 'new_exp'. """ self.term.print_info(u"Making replacement into {}" .format(self.term.text_in_color(file_path, TERM_GREEN))) # write the new version into a temporary file tmp_file = tempfile.NamedTemporaryFile(mode='w+t', delete=False) for filelineno, line in enumerate(io.open(file_path, encoding="utf-8")): if old_exp in line: line = line.replace(old_exp, new_exp) try: tmp_file.write(line.encode('utf-8')) except TypeError: tmp_file.write(line) name = tmp_file.name # keep the name tmp_file.close() shutil.copy(name, file_path) # replace the original one os.remove(name) def touch(self, filename): """ A simple equivalent of the well known shell 'touch' command. """ with file(filename, 'a'): os.utime(filename, None) def posthook(self): """ Empty post-hook, to be inherited. """ pass
stephanepechard/projy
projy/templates/ProjyTemplate.py
ProjyTemplate.make_posthook
python
def make_posthook(self): print(id(self.posthook), self.posthook) print(id(super(self.__class__, self).posthook), super(self.__class__, self).posthook) import ipdb;ipdb.set_trace() if self.posthook: os.chdir(self.project_name) # enter the project main directory self.posthook()
Run the post hook into the project directory.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/ProjyTemplate.py#L138-L145
[ "def posthook(self):\n \"\"\" Empty post-hook, to be inherited. \"\"\"\n pass\n" ]
class ProjyTemplate: """ Base template class for a Projy project creation. """ def __init__(self): self.project_name = None self.template_name = None self.substitutes_dict = {} self.term = TerminalView() def create(self, project_name, template_name, substitutions): """ Launch the project creation. """ self.project_name = project_name self.template_name = template_name # create substitutions dictionary from user arguments # TODO: check what is given for subs in substitutions: current_sub = subs.split(',') current_key = current_sub[0].strip() current_val = current_sub[1].strip() self.substitutes_dict[current_key] = current_val self.term.print_info(u"Creating project '{0}' with template {1}" .format(self.term.text_in_color(project_name, TERM_PINK), template_name)) self.make_directories() self.make_files() self.make_posthook() def make_directories(self): """ Create the directories of the template. """ # get the directories from the template directories = [] try: directories = self.directories() except AttributeError: self.term.print_info(u"No directory in the template.") working_dir = os.getcwd() # iteratively create the directories for directory in directories: dir_name = working_dir + '/' + directory if not os.path.isdir(dir_name): try: os.makedirs(dir_name) except OSError as error: if error.errno != errno.EEXIST: raise else: self.term.print_error_and_exit(u"The directory {0} already exists." .format(directory)) self.term.print_info(u"Creating directory '{0}'" .format(self.term.text_in_color(directory, TERM_GREEN))) def make_files(self): """ Create the files of the template. """ # get the files from the template files = [] try: files = self.files() except AttributeError: self.term.print_info(u"No file in the template. Weird, but why not?") # get the substitutes intersecting the template and the cli try: for key in self.substitutes().keys(): if key not in self.substitutes_dict: self.substitutes_dict[key] = self.substitutes()[key] except AttributeError: self.term.print_info(u"No substitute in the template.") working_dir = os.getcwd() # iteratively create the files for directory, name, template_file in files: if directory: filepath = working_dir + '/' + directory + '/' + name filename = directory + '/' + name else: filepath = working_dir + '/' + name filename = name # open the file to write into try: output = open(filepath, 'w') except IOError: self.term.print_error_and_exit(u"Can't create destination"\ " file: {0}".format(filepath)) # open the template to read from if template_file: input_file = join(dirname(__file__), template_file + '.txt') # write each line of input file into output file, # templatized with substitutes try: with open(input_file, 'r') as line: template_line = Template(line.read()) try: output.write(template_line. safe_substitute(self.substitutes_dict).encode('utf-8')) except TypeError: output.write(template_line. safe_substitute(self.substitutes_dict)) output.close() except IOError: self.term.print_error_and_exit(u"Can't create template file"\ ": {0}".format(input_file)) else: output.close() # the file is empty, but still created self.term.print_info(u"Creating file '{0}'" .format(self.term.text_in_color(filename, TERM_YELLOW))) def replace_in_file(self, file_path, old_exp, new_exp): """ In the given file, replace all 'old_exp' by 'new_exp'. """ self.term.print_info(u"Making replacement into {}" .format(self.term.text_in_color(file_path, TERM_GREEN))) # write the new version into a temporary file tmp_file = tempfile.NamedTemporaryFile(mode='w+t', delete=False) for filelineno, line in enumerate(io.open(file_path, encoding="utf-8")): if old_exp in line: line = line.replace(old_exp, new_exp) try: tmp_file.write(line.encode('utf-8')) except TypeError: tmp_file.write(line) name = tmp_file.name # keep the name tmp_file.close() shutil.copy(name, file_path) # replace the original one os.remove(name) def touch(self, filename): """ A simple equivalent of the well known shell 'touch' command. """ with file(filename, 'a'): os.utime(filename, None) def posthook(self): """ Empty post-hook, to be inherited. """ pass
stephanepechard/projy
projy/templates/ProjyTemplate.py
ProjyTemplate.replace_in_file
python
def replace_in_file(self, file_path, old_exp, new_exp): self.term.print_info(u"Making replacement into {}" .format(self.term.text_in_color(file_path, TERM_GREEN))) # write the new version into a temporary file tmp_file = tempfile.NamedTemporaryFile(mode='w+t', delete=False) for filelineno, line in enumerate(io.open(file_path, encoding="utf-8")): if old_exp in line: line = line.replace(old_exp, new_exp) try: tmp_file.write(line.encode('utf-8')) except TypeError: tmp_file.write(line) name = tmp_file.name # keep the name tmp_file.close() shutil.copy(name, file_path) # replace the original one os.remove(name)
In the given file, replace all 'old_exp' by 'new_exp'.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/ProjyTemplate.py#L148-L166
[ "def print_info(self, message):\n \"\"\" Print an informational text. \"\"\"\n print(message)\n", "def text_in_color(self, message, color_code):\n \"\"\" Print with a beautiful color. See codes at the top of this file. \"\"\"\n return self.term.color(color_code) + message + self.term.normal\n" ]
class ProjyTemplate: """ Base template class for a Projy project creation. """ def __init__(self): self.project_name = None self.template_name = None self.substitutes_dict = {} self.term = TerminalView() def create(self, project_name, template_name, substitutions): """ Launch the project creation. """ self.project_name = project_name self.template_name = template_name # create substitutions dictionary from user arguments # TODO: check what is given for subs in substitutions: current_sub = subs.split(',') current_key = current_sub[0].strip() current_val = current_sub[1].strip() self.substitutes_dict[current_key] = current_val self.term.print_info(u"Creating project '{0}' with template {1}" .format(self.term.text_in_color(project_name, TERM_PINK), template_name)) self.make_directories() self.make_files() self.make_posthook() def make_directories(self): """ Create the directories of the template. """ # get the directories from the template directories = [] try: directories = self.directories() except AttributeError: self.term.print_info(u"No directory in the template.") working_dir = os.getcwd() # iteratively create the directories for directory in directories: dir_name = working_dir + '/' + directory if not os.path.isdir(dir_name): try: os.makedirs(dir_name) except OSError as error: if error.errno != errno.EEXIST: raise else: self.term.print_error_and_exit(u"The directory {0} already exists." .format(directory)) self.term.print_info(u"Creating directory '{0}'" .format(self.term.text_in_color(directory, TERM_GREEN))) def make_files(self): """ Create the files of the template. """ # get the files from the template files = [] try: files = self.files() except AttributeError: self.term.print_info(u"No file in the template. Weird, but why not?") # get the substitutes intersecting the template and the cli try: for key in self.substitutes().keys(): if key not in self.substitutes_dict: self.substitutes_dict[key] = self.substitutes()[key] except AttributeError: self.term.print_info(u"No substitute in the template.") working_dir = os.getcwd() # iteratively create the files for directory, name, template_file in files: if directory: filepath = working_dir + '/' + directory + '/' + name filename = directory + '/' + name else: filepath = working_dir + '/' + name filename = name # open the file to write into try: output = open(filepath, 'w') except IOError: self.term.print_error_and_exit(u"Can't create destination"\ " file: {0}".format(filepath)) # open the template to read from if template_file: input_file = join(dirname(__file__), template_file + '.txt') # write each line of input file into output file, # templatized with substitutes try: with open(input_file, 'r') as line: template_line = Template(line.read()) try: output.write(template_line. safe_substitute(self.substitutes_dict).encode('utf-8')) except TypeError: output.write(template_line. safe_substitute(self.substitutes_dict)) output.close() except IOError: self.term.print_error_and_exit(u"Can't create template file"\ ": {0}".format(input_file)) else: output.close() # the file is empty, but still created self.term.print_info(u"Creating file '{0}'" .format(self.term.text_in_color(filename, TERM_YELLOW))) def make_posthook(self): """ Run the post hook into the project directory. """ print(id(self.posthook), self.posthook) print(id(super(self.__class__, self).posthook), super(self.__class__, self).posthook) import ipdb;ipdb.set_trace() if self.posthook: os.chdir(self.project_name) # enter the project main directory self.posthook() def touch(self, filename): """ A simple equivalent of the well known shell 'touch' command. """ with file(filename, 'a'): os.utime(filename, None) def posthook(self): """ Empty post-hook, to be inherited. """ pass
stephanepechard/projy
projy/cmdline.py
docopt_arguments
python
def docopt_arguments(): doc = """Projy: Create templated project. Usage: projy <template> <project> [<substitution>...] projy -i | --info <template> projy -l | --list projy -h | --help projy -v | --version Options: -i, --info Print information on a specific template. -l, --list Print available template list. -h, --help Show this help message and exit. -v, --version Show program's version number and exit. """ from projy.docopt import docopt return docopt(doc, argv=sys.argv[1:], version='0.1')
Creates beautiful command-line interfaces. See https://github.com/docopt/docopt
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L11-L29
[ "def docopt(doc, argv=sys.argv[1:], help=True, version=None):\n DocoptExit.usage = docopt.usage = usage = printable_usage(doc)\n pot_options = parse_doc_options(doc)\n pattern = parse_pattern(formal_usage(usage), options=pot_options)\n argv = parse_argv(argv, options=pot_options)\n extras(help, versi...
# -*- coding: utf-8 -*- """ First thing to do: parse user-given arguments. """ # system import os import sys # local [--with=<key,value> ...] from projy.TerminalView import * def template_name_from_class_name(class_name): """ Remove the last 'Template' in the name. """ suffix = 'Template' output = class_name if (class_name.endswith(suffix)): output = class_name[:-len(suffix)] return output def run_list(): """ Print the list of all available templates. """ term = TerminalView() term.print_info("These are the available templates:") import pkgutil, projy.templates pkgpath = os.path.dirname(projy.templates.__file__) templates = [name for _, name, _ in pkgutil.iter_modules([pkgpath])] for name in templates: # the father of all templates, not a real usable one if (name != 'ProjyTemplate'): term.print_info(term.text_in_color(template_name_from_class_name(name), TERM_PINK)) def run_info(template): """ Print information about a specific template. """ template.project_name = 'TowelStuff' # fake project name, always the same name = template_name_from_class_name(template.__class__.__name__) term = TerminalView() term.print_info("Content of template {} with an example project " \ "named 'TowelStuff':".format(term.text_in_color(name, TERM_GREEN))) dir_name = None for file_info in sorted(template.files(), key=lambda dir: dir[0]): directory = file_name = template_name = '' if file_info[0]: directory = file_info[0] if file_info[1]: file_name = file_info[1] if file_info[2]: template_name = '\t\t - ' + file_info[2] if (directory != dir_name): term.print_info('\n\t' + term.text_in_color(directory + '/', TERM_PINK)) dir_name = directory term.print_info('\t\t' + term.text_in_color(file_name, TERM_YELLOW) + template_name) # print substitutions try: subs = template.substitutes().keys() if len(subs) > 0: subs.sort() term.print_info("\nSubstitutions of this template are: ") max_len = 0 for key in subs: if max_len < len(key): max_len = len(key) for key in subs: term.print_info(u"\t{0:{1}} -> {2}". format(key, max_len, template.substitutes()[key])) except AttributeError: pass def template_class_from_name(name): """ Return the template class object from agiven name. """ # import the right template module term = TerminalView() template_name = name + 'Template' try: __import__('projy.templates.' + template_name) template_mod = sys.modules['projy.templates.' + template_name] except ImportError: term.print_error_and_exit("Unable to find {}".format(name)) # import the class from the module try: template_class = getattr(template_mod, template_name) except AttributeError: term.print_error_and_exit("Unable to create a template {}".format(name)) return template_class() def execute(): """ Main function. """ args = docopt_arguments() term = TerminalView() # print list of installed templates if args['--list']: run_list() return # instanciate the class if args['<template>']: template = template_class_from_name(args['<template>']) # print info on a template if args['--info']: if args['<template>']: run_info(template) else: term.print_error_and_exit("Please specify a template") return # launch the template template.create(args['<project>'], args['<template>'], args['<substitution>']) term.print_info("Done!")
stephanepechard/projy
projy/cmdline.py
template_name_from_class_name
python
def template_name_from_class_name(class_name): suffix = 'Template' output = class_name if (class_name.endswith(suffix)): output = class_name[:-len(suffix)] return output
Remove the last 'Template' in the name.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L32-L38
null
# -*- coding: utf-8 -*- """ First thing to do: parse user-given arguments. """ # system import os import sys # local [--with=<key,value> ...] from projy.TerminalView import * def docopt_arguments(): """ Creates beautiful command-line interfaces. See https://github.com/docopt/docopt """ doc = """Projy: Create templated project. Usage: projy <template> <project> [<substitution>...] projy -i | --info <template> projy -l | --list projy -h | --help projy -v | --version Options: -i, --info Print information on a specific template. -l, --list Print available template list. -h, --help Show this help message and exit. -v, --version Show program's version number and exit. """ from projy.docopt import docopt return docopt(doc, argv=sys.argv[1:], version='0.1') def run_list(): """ Print the list of all available templates. """ term = TerminalView() term.print_info("These are the available templates:") import pkgutil, projy.templates pkgpath = os.path.dirname(projy.templates.__file__) templates = [name for _, name, _ in pkgutil.iter_modules([pkgpath])] for name in templates: # the father of all templates, not a real usable one if (name != 'ProjyTemplate'): term.print_info(term.text_in_color(template_name_from_class_name(name), TERM_PINK)) def run_info(template): """ Print information about a specific template. """ template.project_name = 'TowelStuff' # fake project name, always the same name = template_name_from_class_name(template.__class__.__name__) term = TerminalView() term.print_info("Content of template {} with an example project " \ "named 'TowelStuff':".format(term.text_in_color(name, TERM_GREEN))) dir_name = None for file_info in sorted(template.files(), key=lambda dir: dir[0]): directory = file_name = template_name = '' if file_info[0]: directory = file_info[0] if file_info[1]: file_name = file_info[1] if file_info[2]: template_name = '\t\t - ' + file_info[2] if (directory != dir_name): term.print_info('\n\t' + term.text_in_color(directory + '/', TERM_PINK)) dir_name = directory term.print_info('\t\t' + term.text_in_color(file_name, TERM_YELLOW) + template_name) # print substitutions try: subs = template.substitutes().keys() if len(subs) > 0: subs.sort() term.print_info("\nSubstitutions of this template are: ") max_len = 0 for key in subs: if max_len < len(key): max_len = len(key) for key in subs: term.print_info(u"\t{0:{1}} -> {2}". format(key, max_len, template.substitutes()[key])) except AttributeError: pass def template_class_from_name(name): """ Return the template class object from agiven name. """ # import the right template module term = TerminalView() template_name = name + 'Template' try: __import__('projy.templates.' + template_name) template_mod = sys.modules['projy.templates.' + template_name] except ImportError: term.print_error_and_exit("Unable to find {}".format(name)) # import the class from the module try: template_class = getattr(template_mod, template_name) except AttributeError: term.print_error_and_exit("Unable to create a template {}".format(name)) return template_class() def execute(): """ Main function. """ args = docopt_arguments() term = TerminalView() # print list of installed templates if args['--list']: run_list() return # instanciate the class if args['<template>']: template = template_class_from_name(args['<template>']) # print info on a template if args['--info']: if args['<template>']: run_info(template) else: term.print_error_and_exit("Please specify a template") return # launch the template template.create(args['<project>'], args['<template>'], args['<substitution>']) term.print_info("Done!")
stephanepechard/projy
projy/cmdline.py
run_list
python
def run_list(): term = TerminalView() term.print_info("These are the available templates:") import pkgutil, projy.templates pkgpath = os.path.dirname(projy.templates.__file__) templates = [name for _, name, _ in pkgutil.iter_modules([pkgpath])] for name in templates: # the father of all templates, not a real usable one if (name != 'ProjyTemplate'): term.print_info(term.text_in_color(template_name_from_class_name(name), TERM_PINK))
Print the list of all available templates.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L41-L51
[ "def template_name_from_class_name(class_name):\n \"\"\" Remove the last 'Template' in the name. \"\"\"\n suffix = 'Template'\n output = class_name\n if (class_name.endswith(suffix)):\n output = class_name[:-len(suffix)]\n return output\n", "def print_info(self, message):\n \"\"\" Print a...
# -*- coding: utf-8 -*- """ First thing to do: parse user-given arguments. """ # system import os import sys # local [--with=<key,value> ...] from projy.TerminalView import * def docopt_arguments(): """ Creates beautiful command-line interfaces. See https://github.com/docopt/docopt """ doc = """Projy: Create templated project. Usage: projy <template> <project> [<substitution>...] projy -i | --info <template> projy -l | --list projy -h | --help projy -v | --version Options: -i, --info Print information on a specific template. -l, --list Print available template list. -h, --help Show this help message and exit. -v, --version Show program's version number and exit. """ from projy.docopt import docopt return docopt(doc, argv=sys.argv[1:], version='0.1') def template_name_from_class_name(class_name): """ Remove the last 'Template' in the name. """ suffix = 'Template' output = class_name if (class_name.endswith(suffix)): output = class_name[:-len(suffix)] return output def run_info(template): """ Print information about a specific template. """ template.project_name = 'TowelStuff' # fake project name, always the same name = template_name_from_class_name(template.__class__.__name__) term = TerminalView() term.print_info("Content of template {} with an example project " \ "named 'TowelStuff':".format(term.text_in_color(name, TERM_GREEN))) dir_name = None for file_info in sorted(template.files(), key=lambda dir: dir[0]): directory = file_name = template_name = '' if file_info[0]: directory = file_info[0] if file_info[1]: file_name = file_info[1] if file_info[2]: template_name = '\t\t - ' + file_info[2] if (directory != dir_name): term.print_info('\n\t' + term.text_in_color(directory + '/', TERM_PINK)) dir_name = directory term.print_info('\t\t' + term.text_in_color(file_name, TERM_YELLOW) + template_name) # print substitutions try: subs = template.substitutes().keys() if len(subs) > 0: subs.sort() term.print_info("\nSubstitutions of this template are: ") max_len = 0 for key in subs: if max_len < len(key): max_len = len(key) for key in subs: term.print_info(u"\t{0:{1}} -> {2}". format(key, max_len, template.substitutes()[key])) except AttributeError: pass def template_class_from_name(name): """ Return the template class object from agiven name. """ # import the right template module term = TerminalView() template_name = name + 'Template' try: __import__('projy.templates.' + template_name) template_mod = sys.modules['projy.templates.' + template_name] except ImportError: term.print_error_and_exit("Unable to find {}".format(name)) # import the class from the module try: template_class = getattr(template_mod, template_name) except AttributeError: term.print_error_and_exit("Unable to create a template {}".format(name)) return template_class() def execute(): """ Main function. """ args = docopt_arguments() term = TerminalView() # print list of installed templates if args['--list']: run_list() return # instanciate the class if args['<template>']: template = template_class_from_name(args['<template>']) # print info on a template if args['--info']: if args['<template>']: run_info(template) else: term.print_error_and_exit("Please specify a template") return # launch the template template.create(args['<project>'], args['<template>'], args['<substitution>']) term.print_info("Done!")
stephanepechard/projy
projy/cmdline.py
run_info
python
def run_info(template): template.project_name = 'TowelStuff' # fake project name, always the same name = template_name_from_class_name(template.__class__.__name__) term = TerminalView() term.print_info("Content of template {} with an example project " \ "named 'TowelStuff':".format(term.text_in_color(name, TERM_GREEN))) dir_name = None for file_info in sorted(template.files(), key=lambda dir: dir[0]): directory = file_name = template_name = '' if file_info[0]: directory = file_info[0] if file_info[1]: file_name = file_info[1] if file_info[2]: template_name = '\t\t - ' + file_info[2] if (directory != dir_name): term.print_info('\n\t' + term.text_in_color(directory + '/', TERM_PINK)) dir_name = directory term.print_info('\t\t' + term.text_in_color(file_name, TERM_YELLOW) + template_name) # print substitutions try: subs = template.substitutes().keys() if len(subs) > 0: subs.sort() term.print_info("\nSubstitutions of this template are: ") max_len = 0 for key in subs: if max_len < len(key): max_len = len(key) for key in subs: term.print_info(u"\t{0:{1}} -> {2}". format(key, max_len, template.substitutes()[key])) except AttributeError: pass
Print information about a specific template.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L54-L91
[ "def template_name_from_class_name(class_name):\n \"\"\" Remove the last 'Template' in the name. \"\"\"\n suffix = 'Template'\n output = class_name\n if (class_name.endswith(suffix)):\n output = class_name[:-len(suffix)]\n return output\n", "def print_info(self, message):\n \"\"\" Print a...
# -*- coding: utf-8 -*- """ First thing to do: parse user-given arguments. """ # system import os import sys # local [--with=<key,value> ...] from projy.TerminalView import * def docopt_arguments(): """ Creates beautiful command-line interfaces. See https://github.com/docopt/docopt """ doc = """Projy: Create templated project. Usage: projy <template> <project> [<substitution>...] projy -i | --info <template> projy -l | --list projy -h | --help projy -v | --version Options: -i, --info Print information on a specific template. -l, --list Print available template list. -h, --help Show this help message and exit. -v, --version Show program's version number and exit. """ from projy.docopt import docopt return docopt(doc, argv=sys.argv[1:], version='0.1') def template_name_from_class_name(class_name): """ Remove the last 'Template' in the name. """ suffix = 'Template' output = class_name if (class_name.endswith(suffix)): output = class_name[:-len(suffix)] return output def run_list(): """ Print the list of all available templates. """ term = TerminalView() term.print_info("These are the available templates:") import pkgutil, projy.templates pkgpath = os.path.dirname(projy.templates.__file__) templates = [name for _, name, _ in pkgutil.iter_modules([pkgpath])] for name in templates: # the father of all templates, not a real usable one if (name != 'ProjyTemplate'): term.print_info(term.text_in_color(template_name_from_class_name(name), TERM_PINK)) def template_class_from_name(name): """ Return the template class object from agiven name. """ # import the right template module term = TerminalView() template_name = name + 'Template' try: __import__('projy.templates.' + template_name) template_mod = sys.modules['projy.templates.' + template_name] except ImportError: term.print_error_and_exit("Unable to find {}".format(name)) # import the class from the module try: template_class = getattr(template_mod, template_name) except AttributeError: term.print_error_and_exit("Unable to create a template {}".format(name)) return template_class() def execute(): """ Main function. """ args = docopt_arguments() term = TerminalView() # print list of installed templates if args['--list']: run_list() return # instanciate the class if args['<template>']: template = template_class_from_name(args['<template>']) # print info on a template if args['--info']: if args['<template>']: run_info(template) else: term.print_error_and_exit("Please specify a template") return # launch the template template.create(args['<project>'], args['<template>'], args['<substitution>']) term.print_info("Done!")
stephanepechard/projy
projy/cmdline.py
template_class_from_name
python
def template_class_from_name(name): # import the right template module term = TerminalView() template_name = name + 'Template' try: __import__('projy.templates.' + template_name) template_mod = sys.modules['projy.templates.' + template_name] except ImportError: term.print_error_and_exit("Unable to find {}".format(name)) # import the class from the module try: template_class = getattr(template_mod, template_name) except AttributeError: term.print_error_and_exit("Unable to create a template {}".format(name)) return template_class()
Return the template class object from agiven name.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L94-L110
[ "def print_error_and_exit(self, message):\n \"\"\" Print an error in red and exits the program. \"\"\"\n sys.exit(self.term.bold_red('[ERROR] ' + message))\n" ]
# -*- coding: utf-8 -*- """ First thing to do: parse user-given arguments. """ # system import os import sys # local [--with=<key,value> ...] from projy.TerminalView import * def docopt_arguments(): """ Creates beautiful command-line interfaces. See https://github.com/docopt/docopt """ doc = """Projy: Create templated project. Usage: projy <template> <project> [<substitution>...] projy -i | --info <template> projy -l | --list projy -h | --help projy -v | --version Options: -i, --info Print information on a specific template. -l, --list Print available template list. -h, --help Show this help message and exit. -v, --version Show program's version number and exit. """ from projy.docopt import docopt return docopt(doc, argv=sys.argv[1:], version='0.1') def template_name_from_class_name(class_name): """ Remove the last 'Template' in the name. """ suffix = 'Template' output = class_name if (class_name.endswith(suffix)): output = class_name[:-len(suffix)] return output def run_list(): """ Print the list of all available templates. """ term = TerminalView() term.print_info("These are the available templates:") import pkgutil, projy.templates pkgpath = os.path.dirname(projy.templates.__file__) templates = [name for _, name, _ in pkgutil.iter_modules([pkgpath])] for name in templates: # the father of all templates, not a real usable one if (name != 'ProjyTemplate'): term.print_info(term.text_in_color(template_name_from_class_name(name), TERM_PINK)) def run_info(template): """ Print information about a specific template. """ template.project_name = 'TowelStuff' # fake project name, always the same name = template_name_from_class_name(template.__class__.__name__) term = TerminalView() term.print_info("Content of template {} with an example project " \ "named 'TowelStuff':".format(term.text_in_color(name, TERM_GREEN))) dir_name = None for file_info in sorted(template.files(), key=lambda dir: dir[0]): directory = file_name = template_name = '' if file_info[0]: directory = file_info[0] if file_info[1]: file_name = file_info[1] if file_info[2]: template_name = '\t\t - ' + file_info[2] if (directory != dir_name): term.print_info('\n\t' + term.text_in_color(directory + '/', TERM_PINK)) dir_name = directory term.print_info('\t\t' + term.text_in_color(file_name, TERM_YELLOW) + template_name) # print substitutions try: subs = template.substitutes().keys() if len(subs) > 0: subs.sort() term.print_info("\nSubstitutions of this template are: ") max_len = 0 for key in subs: if max_len < len(key): max_len = len(key) for key in subs: term.print_info(u"\t{0:{1}} -> {2}". format(key, max_len, template.substitutes()[key])) except AttributeError: pass def execute(): """ Main function. """ args = docopt_arguments() term = TerminalView() # print list of installed templates if args['--list']: run_list() return # instanciate the class if args['<template>']: template = template_class_from_name(args['<template>']) # print info on a template if args['--info']: if args['<template>']: run_info(template) else: term.print_error_and_exit("Please specify a template") return # launch the template template.create(args['<project>'], args['<template>'], args['<substitution>']) term.print_info("Done!")
stephanepechard/projy
projy/cmdline.py
execute
python
def execute(): args = docopt_arguments() term = TerminalView() # print list of installed templates if args['--list']: run_list() return # instanciate the class if args['<template>']: template = template_class_from_name(args['<template>']) # print info on a template if args['--info']: if args['<template>']: run_info(template) else: term.print_error_and_exit("Please specify a template") return # launch the template template.create(args['<project>'], args['<template>'], args['<substitution>']) term.print_info("Done!")
Main function.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L113-L139
[ "def docopt_arguments():\n \"\"\" Creates beautiful command-line interfaces.\n See https://github.com/docopt/docopt \"\"\"\n doc = \"\"\"Projy: Create templated project.\n\n Usage: projy <template> <project> [<substitution>...]\n projy -i | --info <template>\n projy -l | --list\n...
# -*- coding: utf-8 -*- """ First thing to do: parse user-given arguments. """ # system import os import sys # local [--with=<key,value> ...] from projy.TerminalView import * def docopt_arguments(): """ Creates beautiful command-line interfaces. See https://github.com/docopt/docopt """ doc = """Projy: Create templated project. Usage: projy <template> <project> [<substitution>...] projy -i | --info <template> projy -l | --list projy -h | --help projy -v | --version Options: -i, --info Print information on a specific template. -l, --list Print available template list. -h, --help Show this help message and exit. -v, --version Show program's version number and exit. """ from projy.docopt import docopt return docopt(doc, argv=sys.argv[1:], version='0.1') def template_name_from_class_name(class_name): """ Remove the last 'Template' in the name. """ suffix = 'Template' output = class_name if (class_name.endswith(suffix)): output = class_name[:-len(suffix)] return output def run_list(): """ Print the list of all available templates. """ term = TerminalView() term.print_info("These are the available templates:") import pkgutil, projy.templates pkgpath = os.path.dirname(projy.templates.__file__) templates = [name for _, name, _ in pkgutil.iter_modules([pkgpath])] for name in templates: # the father of all templates, not a real usable one if (name != 'ProjyTemplate'): term.print_info(term.text_in_color(template_name_from_class_name(name), TERM_PINK)) def run_info(template): """ Print information about a specific template. """ template.project_name = 'TowelStuff' # fake project name, always the same name = template_name_from_class_name(template.__class__.__name__) term = TerminalView() term.print_info("Content of template {} with an example project " \ "named 'TowelStuff':".format(term.text_in_color(name, TERM_GREEN))) dir_name = None for file_info in sorted(template.files(), key=lambda dir: dir[0]): directory = file_name = template_name = '' if file_info[0]: directory = file_info[0] if file_info[1]: file_name = file_info[1] if file_info[2]: template_name = '\t\t - ' + file_info[2] if (directory != dir_name): term.print_info('\n\t' + term.text_in_color(directory + '/', TERM_PINK)) dir_name = directory term.print_info('\t\t' + term.text_in_color(file_name, TERM_YELLOW) + template_name) # print substitutions try: subs = template.substitutes().keys() if len(subs) > 0: subs.sort() term.print_info("\nSubstitutions of this template are: ") max_len = 0 for key in subs: if max_len < len(key): max_len = len(key) for key in subs: term.print_info(u"\t{0:{1}} -> {2}". format(key, max_len, template.substitutes()[key])) except AttributeError: pass def template_class_from_name(name): """ Return the template class object from agiven name. """ # import the right template module term = TerminalView() template_name = name + 'Template' try: __import__('projy.templates.' + template_name) template_mod = sys.modules['projy.templates.' + template_name] except ImportError: term.print_error_and_exit("Unable to find {}".format(name)) # import the class from the module try: template_class = getattr(template_mod, template_name) except AttributeError: term.print_error_and_exit("Unable to create a template {}".format(name)) return template_class()
stephanepechard/projy
projy/templates/ProjyTemplateTemplate.py
ProjyTemplateTemplate.substitutes
python
def substitutes(self): substitute_dict = dict( project = self.project_name, template = self.project_name + 'Template', file = self.project_name + 'FileTemplate', ) return substitute_dict
Return the substitutions for the templating replacements.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/ProjyTemplateTemplate.py#L28-L35
null
class ProjyTemplateTemplate(ProjyTemplate): """ Projy template class for ProjyTemplate. """ def __init__(self): ProjyTemplate.__init__(self) def files(self): """ Return the names of files to be created. """ files_description = [ [ None, self.project_name + 'Template.py', 'ProjyTemplateFileTemplate' ], [ None, self.project_name + 'FileTemplate.txt', None ], ] return files_description
stephanepechard/projy
projy/templates/PythonPackageTemplate.py
PythonPackageTemplate.files
python
def files(self): files_description = [ [ self.project_name, 'bootstrap', 'BootstrapScriptFileTemplate' ], [ self.project_name, 'CHANGES.txt', 'PythonPackageCHANGESFileTemplate' ], [ self.project_name, 'LICENSE.txt', 'GPL3FileTemplate' ], [ self.project_name, 'MANIFEST.in', 'PythonPackageMANIFESTFileTemplate' ], [ self.project_name, 'README.txt', 'READMEReSTFileTemplate' ], [ self.project_name, 'setup.py', 'PythonPackageSetupFileTemplate' ], [ self.project_name + '/' + self.project_name.lower(), '__init__.py', None ], [ self.project_name + '/docs', 'index.rst', None ], ] return files_description
Return the names of files to be created.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/PythonPackageTemplate.py#L30-L58
null
class PythonPackageTemplate(ProjyTemplate): """ Projy template class for PythonPackage. """ def __init__(self): ProjyTemplate.__init__(self) def directories(self): """ Return the names of directories to be created. """ directories_description = [ self.project_name, self.project_name + '/' + self.project_name.lower(), self.project_name + '/docs', ] return directories_description def substitutes(self): """ Return the substitutions for the templating replacements. """ author_collector = AuthorCollector() mail_collector = AuthorMailCollector() substitute_dict = dict( project = self.project_name, project_lower = self.project_name.lower(), date = date.today().isoformat(), author = author_collector.collect(), author_email = mail_collector.collect(), ) return substitute_dict
stephanepechard/projy
projy/templates/PythonPackageTemplate.py
PythonPackageTemplate.substitutes
python
def substitutes(self): author_collector = AuthorCollector() mail_collector = AuthorMailCollector() substitute_dict = dict( project = self.project_name, project_lower = self.project_name.lower(), date = date.today().isoformat(), author = author_collector.collect(), author_email = mail_collector.collect(), ) return substitute_dict
Return the substitutions for the templating replacements.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/PythonPackageTemplate.py#L61-L72
[ "def collect(self):\n \"\"\" Select the best suited data of all available in the subclasses.\n In each subclass, the functions alphabetical order should\n correspond to their importance.\n Here, the first non null value is returned.\n \"\"\"\n class_functions = []\n for key in self....
class PythonPackageTemplate(ProjyTemplate): """ Projy template class for PythonPackage. """ def __init__(self): ProjyTemplate.__init__(self) def directories(self): """ Return the names of directories to be created. """ directories_description = [ self.project_name, self.project_name + '/' + self.project_name.lower(), self.project_name + '/docs', ] return directories_description def files(self): """ Return the names of files to be created. """ files_description = [ [ self.project_name, 'bootstrap', 'BootstrapScriptFileTemplate' ], [ self.project_name, 'CHANGES.txt', 'PythonPackageCHANGESFileTemplate' ], [ self.project_name, 'LICENSE.txt', 'GPL3FileTemplate' ], [ self.project_name, 'MANIFEST.in', 'PythonPackageMANIFESTFileTemplate' ], [ self.project_name, 'README.txt', 'READMEReSTFileTemplate' ], [ self.project_name, 'setup.py', 'PythonPackageSetupFileTemplate' ], [ self.project_name + '/' + self.project_name.lower(), '__init__.py', None ], [ self.project_name + '/docs', 'index.rst', None ], ] return files_description
stephanepechard/projy
fabfile.py
commit
python
def commit(message=COMMON_COMMIT_MESSAGE, capture=True): env.warn_only = True local(u'git commit -am"{}"'.format(message))
git commit with common commit message when omit.
train
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/fabfile.py#L15-L18
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Deployment of Projy. """ # system import os, re # fabric from fabric.api import cd, env, execute, local, run, sudo, prefix # projy from projy import __version__ COMMON_COMMIT_MESSAGE = u"Fast commit through Fabric" def push(): """ Local git push. """ local("git push") def deploy(message=COMMON_COMMIT_MESSAGE): """ Commit and push to git servers. """ execute(commit, message) execute(push) def reinstall(): """ Reinstall the project to local virtualenv. """ local('if [ $(pip freeze | grep Projy | wc -w ) -eq 1 ]; then ' './venv/bin/pip uninstall -q -y Projy ; fi') local('./venv/bin/python setup.py sdist') local('./venv/bin/pip install -q dist/Projy-' + __version__ + '.tar.gz') local('rm -rf dist/ Projy.egg-info/') def install(): """ Install the project. """ local('./venv/bin/python setup.py install') local('rm -rf build') def md2rst(in_file, out_file, pipe): """ Generate reStructuredText from Makrdown. """ local("pandoc -f markdown -t rst %s %s > %s" % (in_file, pipe, out_file)) def readme(): md2rst('README.md', 'README.txt', '| head -n -8 | tail -n +3') def build_doc(): """ Build the html documentation. """ local('cd docs/ && make html') local('cd docs/_build/html && zip -9 -T -r ../Projy-' + __version__ + '.zip *') local('cat docs/changelog.rst | tail -n +3 > CHANGES.txt') def watch_doc(): local('venv/bin/watchmedo shell-command --patterns="docs/*.rst" --command="fab build_doc" ./docs/') def tests(): """ Launch tests. """ local("nosetests") # local("coverage html -d /tmp/coverage-projy --omit='projy/docopt.py'") # local("coverage erase") def clean(): """ Remove temporary files. """ local('rm -rf docs/_build/ dist/ Projy.egg-info/') local('find . -name "*.pyc" | xargs rm') def upload(): """ Upload Pypi. """ local("python setup.py sdist upload")
Nixiware/viper
nx/viper/service/mail.py
Service.send
python
def send(self, recipient, subject, message): if self.configured is False: return False # connecting to server try: self.smtp = smtplib.SMTP( self.application.config["viper.mail"]["host"], self.application.config["viper.mail"]["port"] ) self.smtp.connect( self.application.config["viper.mail"]["host"], self.application.config["viper.mail"]["port"] ) if self.application.config["viper.mail"]["tls"]: self.smtp.starttls() except Exception as e: if hasattr(self, "smtp") and self.smtp is not None: self.smtp.quit() self.log.warn( "[Viper.Mail] Cannot connect to server. Error: {error}", error=str(e) ) return False # performing authentication if len(self.application.config["viper.mail"]["username"]) > 0: try: self.smtp.login( self.application.config["viper.mail"]["username"], self.application.config["viper.mail"]["password"] ) except Exception as e: if hasattr(self, "smtp") and self.smtp is not None: self.smtp.quit() self.log.warn( "[Viper.Mail] Cannot authenticate with server. Error: {error}", error=str(e) ) return False # composing message headers messageHeaders = [] messageHeaders.append("From: {} <{}>".format( self.application.config["viper.mail"]["name"], self.application.config["viper.mail"]["from"] )) if len(recipient) == 2: messageHeaders.append("To: {} <{}>".format( recipient[1], recipient[0] )) else: messageHeaders.append("To: {}".format( recipient[0] )) messageHeaders.append("MIME-Version: 1.0") messageHeaders.append("Content-type: text/html") messageHeaders.append("Subject: {}".format(subject)) # creating email contents emailContents = "" for messageHeaderLine in messageHeaders: if len(emailContents) == 0: emailContents = messageHeaderLine else: emailContents = "{}\n{}".format( emailContents, messageHeaderLine ) emailContents = "{}\n\n{}".format( emailContents, message ) # sending email try: self.smtp.sendmail( self.application.config["viper.mail"]["from"], [recipient[0]], emailContents ) except smtplib.SMTPRecipientsRefused as e: if hasattr(self, "smtp") and self.smtp is not None: self.smtp.quit() self.log.warn( "[Viper.Mail] Server refused mail recipients: " \ "{recipients}. Error: {error}", recipients=recipient, error=str(e) ) return False except smtplib.SMTPSenderRefused as e: if hasattr(self, "smtp") and self.smtp is not None: self.smtp.quit() self.log.warn( "[Viper.Mail] Server refused mail sender: {sender}. " \ "Error: {error}", sender=self.application.config["viper.mail"]["from"], error=str(e) ) return False except Exception as e: if hasattr(self, "smtp") and self.smtp is not None: self.smtp.quit() self.log.warn( "[Viper.Mail] Server refused to deliver mail. Error: {error}", error=str(e) ) return False return True
Sends an email using the SMTP connection. :param recipient: <tuple> recipient's email address as the first element and their name as an optional second element :param subject: <str> mail subject :param message: <str> mail content (as HTML markup) :return: <bool> True if mail was sent successfully, False otherwise
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mail.py#L34-L163
null
class Service: """ SMTP mail service Email sender based on Pythons's smtplib. """ log = Logger() def __init__(self, application): self.application = application self.application.eventDispatcher.addObserver( Application.kEventApplicationStart, self._applicationStart ) def _applicationStart(self, data): self.configured = False if "viper.mail" in self.application.config: if "host" in self.application.config["viper.mail"] \ and "port" in self.application.config["viper.mail"]: if len(self.application.config["viper.mail"]["host"]) > 0 and \ self.application.config["viper.mail"]["port"] > 0: self.configured = True
Nixiware/viper
nx/viper/controller.py
Controller.sendPartialResponse
python
def sendPartialResponse(self): self.requestProtocol.requestResponse["code"] = ( self.responseCode ) self.requestProtocol.requestResponse["content"] = ( self.responseContent ) self.requestProtocol.requestResponse["errors"] = ( self.responseErrors ) self.requestProtocol.sendPartialRequestResponse()
Send a partial response without closing the connection. :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/controller.py#L34-L49
null
class Controller: """ Viper controller Base controller class for controllers instantiated by the Viper dispatcher. """ def __init__(self, application, requestProtocol, requestVersion, requestParameters): self.application = application self.requestProtocol = requestProtocol self.requestVersion = requestVersion self.requestParameters = requestParameters self.responseCode = 0 self.responseContent = {} self.responseErrors = [] def preDispatch(self): """ Method called before the request action is triggered. :return: <void> """ pass def postDispatch(self): """ Method called after the request action is triggered. :return: <void> """ pass def sendFinalResponse(self): """ Send the final response and close the connection. :return: <void> """ self.requestProtocol.requestResponse["code"] = ( self.responseCode ) self.requestProtocol.requestResponse["content"] = ( self.responseContent ) self.requestProtocol.requestResponse["errors"] = ( self.responseErrors ) self.requestProtocol.sendFinalRequestResponse()
Nixiware/viper
nx/viper/controller.py
Controller.sendFinalResponse
python
def sendFinalResponse(self): self.requestProtocol.requestResponse["code"] = ( self.responseCode ) self.requestProtocol.requestResponse["content"] = ( self.responseContent ) self.requestProtocol.requestResponse["errors"] = ( self.responseErrors ) self.requestProtocol.sendFinalRequestResponse()
Send the final response and close the connection. :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/controller.py#L51-L66
null
class Controller: """ Viper controller Base controller class for controllers instantiated by the Viper dispatcher. """ def __init__(self, application, requestProtocol, requestVersion, requestParameters): self.application = application self.requestProtocol = requestProtocol self.requestVersion = requestVersion self.requestParameters = requestParameters self.responseCode = 0 self.responseContent = {} self.responseErrors = [] def preDispatch(self): """ Method called before the request action is triggered. :return: <void> """ pass def postDispatch(self): """ Method called after the request action is triggered. :return: <void> """ pass def sendPartialResponse(self): """ Send a partial response without closing the connection. :return: <void> """ self.requestProtocol.requestResponse["code"] = ( self.responseCode ) self.requestProtocol.requestResponse["content"] = ( self.responseContent ) self.requestProtocol.requestResponse["errors"] = ( self.responseErrors ) self.requestProtocol.sendPartialRequestResponse()
Nixiware/viper
nx/viper/service/mysql.py
Service._applicationStart
python
def _applicationStart(self, data): checkup = False if "viper.mysql" in self.application.config \ and isinstance(self.application.config["viper.mysql"], dict): if "host" in self.application.config["viper.mysql"] and \ "port" in self.application.config["viper.mysql"] and \ "name" in self.application.config["viper.mysql"]: if len(self.application.config["viper.mysql"]["host"]) > 0 and \ self.application.config["viper.mysql"]["port"] > 0 and \ len(self.application.config["viper.mysql"]["name"]) > 0: checkup = True if checkup is not True: return try: self._connectionPool = adbapi.ConnectionPool( "MySQLdb", host=self.application.config["viper.mysql"]["host"], port=int(self.application.config["viper.mysql"]["port"]), user=self.application.config["viper.mysql"]["username"], passwd=self.application.config["viper.mysql"]["password"], db=self.application.config["viper.mysql"]["name"], charset=self.application.config["viper.mysql"]["charset"], cp_min=int( self.application.config["viper.mysql"]["connectionsMinimum"] ), cp_max=int( self.application.config["viper.mysql"]["connectionsMaximum"] ), cp_reconnect=True ) except Exception as e: self.log.error( "[Viper.MySQL] Cannot connect to server. Error: {error}", error=str(e) ) if "init" in self.application.config["viper.mysql"] \ and self.application.config["viper.mysql"]["init"]["runIfEmpty"]: self._checkIfDatabaseIsEmpty( lambda isEmpty: self._scheduleDatabaseInit(isEmpty) , lambda error: self.log.error("[Viper.MySQL] Cannot check if database is empty. Error {error}", error=error) )
Initializes the database connection pool. :param data: <object> event data object :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L27-L82
null
class Service: """ MySQL Database service Wrapper for Twisted's adbapi for interacting with a MySQL database. """ log = Logger() def __init__(self, application): self.application = application self.application.eventDispatcher.addObserver( ViperApplication.kEventApplicationStart, self._applicationStart ) def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None): """ Check if database contains any tables. :param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument is a boolean flag specifying if the database is empty or not :param failHandler: <function(<str>)> method called if interrogation failed where the first argument is the error message :return: <void> """ def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() if failHandler is not None: reactor.callInThread(failHandler, errorMessage) def selectCallback(transaction, successHandler): querySelect = \ "SELECT `TABLE_NAME` " \ "FROM INFORMATION_SCHEMA.TABLES " \ "WHERE " \ "`TABLE_SCHEMA` = %s" \ ";" try: transaction.execute( querySelect, (self.application.config["viper.mysql"]["name"],) ) tables = transaction.fetchall() except Exception as e: failCallback(e) return if successHandler is not None: reactor.callInThread(successHandler, len(tables) == 0) interaction = self.runInteraction(selectCallback, successHandler) interaction.addErrback(failCallback) def _initDatabase(self): """ Initializes the database structure based on application configuration. :return: <void> """ queries = [] if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0: for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]: sqlFile = open(scriptFilePath, "r") queriesInFile = self.extractFromSQLFile(sqlFile) sqlFile.close() queries.extend(queriesInFile) def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() self.log.error( "[Viper.MySQL] _initDatabase() database error: {errorMessage}", errorMessage=errorMessage ) def runCallback(transaction, queries): try: for query in queries: transaction.execute(query) except Exception as e: failCallback(e) return interaction = self.runInteraction(runCallback, queries) interaction.addErrback(failCallback) def _scheduleDatabaseInit(self, isEmpty): """ Schedule database initialization if database is empty. :param isEmpty: <bool> flag for database empty status :return: <void> """ if isEmpty: self._initDatabase() def extractFromSQLFile(self, filePointer, delimiter=";"): """ Process an SQL file and extract all the queries sorted. :param filePointer: <io.TextIOWrapper> file pointer to SQL file :return: <list> list of queries """ data = filePointer.read() # reading file and splitting it into lines dataLines = [] dataLinesIndex = 0 for c in data: if len(dataLines) - 1 < dataLinesIndex: dataLines.append("") if c == "\r\n" or c == "\r" or c == "\n": dataLinesIndex += 1 else: dataLines[dataLinesIndex] = "{}{}".format( dataLines[dataLinesIndex], c ) # forming SQL statements from all lines provided statements = [] statementsIndex = 0 for line in dataLines: # ignoring comments if line.startswith("--") or line.startswith("#"): continue # removing spaces line = line.strip() # ignoring blank lines if len(line) == 0: continue # appending each character to it's statement until delimiter is reached for c in line: if len(statements) - 1 < statementsIndex: statements.append("") statements[statementsIndex] = "{}{}".format( statements[statementsIndex], c ) if c == delimiter: statementsIndex += 1 return statements def runInteraction(self, interaction, *args, **kwargs): """ Interact with the database and return the result. :param interaction: <function> method with first argument is a <adbapi.Transaction> instance :param args: additional positional arguments to be passed to interaction :param kwargs: keyword arguments to be passed to interaction :return: <defer> """ try: return self._connectionPool.runInteraction( interaction, *args, **kwargs ) except: d = defer.Deferred() d.errback() return d def runQuery(self, *args, **kwargs): """ Execute an SQL query and return the result. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runQuery(*args, **kwargs) except: d = defer.Deferred() d.errback() return d def runOperation(self, *args, **kwargs): """ Execute an SQL query and return None. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runOperation(*args, **kwargs) except: d = defer.Deferred() d.errback() return d
Nixiware/viper
nx/viper/service/mysql.py
Service._checkIfDatabaseIsEmpty
python
def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None): def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() if failHandler is not None: reactor.callInThread(failHandler, errorMessage) def selectCallback(transaction, successHandler): querySelect = \ "SELECT `TABLE_NAME` " \ "FROM INFORMATION_SCHEMA.TABLES " \ "WHERE " \ "`TABLE_SCHEMA` = %s" \ ";" try: transaction.execute( querySelect, (self.application.config["viper.mysql"]["name"],) ) tables = transaction.fetchall() except Exception as e: failCallback(e) return if successHandler is not None: reactor.callInThread(successHandler, len(tables) == 0) interaction = self.runInteraction(selectCallback, successHandler) interaction.addErrback(failCallback)
Check if database contains any tables. :param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument is a boolean flag specifying if the database is empty or not :param failHandler: <function(<str>)> method called if interrogation failed where the first argument is the error message :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L84-L125
null
class Service: """ MySQL Database service Wrapper for Twisted's adbapi for interacting with a MySQL database. """ log = Logger() def __init__(self, application): self.application = application self.application.eventDispatcher.addObserver( ViperApplication.kEventApplicationStart, self._applicationStart ) def _applicationStart(self, data): """ Initializes the database connection pool. :param data: <object> event data object :return: <void> """ checkup = False if "viper.mysql" in self.application.config \ and isinstance(self.application.config["viper.mysql"], dict): if "host" in self.application.config["viper.mysql"] and \ "port" in self.application.config["viper.mysql"] and \ "name" in self.application.config["viper.mysql"]: if len(self.application.config["viper.mysql"]["host"]) > 0 and \ self.application.config["viper.mysql"]["port"] > 0 and \ len(self.application.config["viper.mysql"]["name"]) > 0: checkup = True if checkup is not True: return try: self._connectionPool = adbapi.ConnectionPool( "MySQLdb", host=self.application.config["viper.mysql"]["host"], port=int(self.application.config["viper.mysql"]["port"]), user=self.application.config["viper.mysql"]["username"], passwd=self.application.config["viper.mysql"]["password"], db=self.application.config["viper.mysql"]["name"], charset=self.application.config["viper.mysql"]["charset"], cp_min=int( self.application.config["viper.mysql"]["connectionsMinimum"] ), cp_max=int( self.application.config["viper.mysql"]["connectionsMaximum"] ), cp_reconnect=True ) except Exception as e: self.log.error( "[Viper.MySQL] Cannot connect to server. Error: {error}", error=str(e) ) if "init" in self.application.config["viper.mysql"] \ and self.application.config["viper.mysql"]["init"]["runIfEmpty"]: self._checkIfDatabaseIsEmpty( lambda isEmpty: self._scheduleDatabaseInit(isEmpty) , lambda error: self.log.error("[Viper.MySQL] Cannot check if database is empty. Error {error}", error=error) ) def _initDatabase(self): """ Initializes the database structure based on application configuration. :return: <void> """ queries = [] if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0: for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]: sqlFile = open(scriptFilePath, "r") queriesInFile = self.extractFromSQLFile(sqlFile) sqlFile.close() queries.extend(queriesInFile) def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() self.log.error( "[Viper.MySQL] _initDatabase() database error: {errorMessage}", errorMessage=errorMessage ) def runCallback(transaction, queries): try: for query in queries: transaction.execute(query) except Exception as e: failCallback(e) return interaction = self.runInteraction(runCallback, queries) interaction.addErrback(failCallback) def _scheduleDatabaseInit(self, isEmpty): """ Schedule database initialization if database is empty. :param isEmpty: <bool> flag for database empty status :return: <void> """ if isEmpty: self._initDatabase() def extractFromSQLFile(self, filePointer, delimiter=";"): """ Process an SQL file and extract all the queries sorted. :param filePointer: <io.TextIOWrapper> file pointer to SQL file :return: <list> list of queries """ data = filePointer.read() # reading file and splitting it into lines dataLines = [] dataLinesIndex = 0 for c in data: if len(dataLines) - 1 < dataLinesIndex: dataLines.append("") if c == "\r\n" or c == "\r" or c == "\n": dataLinesIndex += 1 else: dataLines[dataLinesIndex] = "{}{}".format( dataLines[dataLinesIndex], c ) # forming SQL statements from all lines provided statements = [] statementsIndex = 0 for line in dataLines: # ignoring comments if line.startswith("--") or line.startswith("#"): continue # removing spaces line = line.strip() # ignoring blank lines if len(line) == 0: continue # appending each character to it's statement until delimiter is reached for c in line: if len(statements) - 1 < statementsIndex: statements.append("") statements[statementsIndex] = "{}{}".format( statements[statementsIndex], c ) if c == delimiter: statementsIndex += 1 return statements def runInteraction(self, interaction, *args, **kwargs): """ Interact with the database and return the result. :param interaction: <function> method with first argument is a <adbapi.Transaction> instance :param args: additional positional arguments to be passed to interaction :param kwargs: keyword arguments to be passed to interaction :return: <defer> """ try: return self._connectionPool.runInteraction( interaction, *args, **kwargs ) except: d = defer.Deferred() d.errback() return d def runQuery(self, *args, **kwargs): """ Execute an SQL query and return the result. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runQuery(*args, **kwargs) except: d = defer.Deferred() d.errback() return d def runOperation(self, *args, **kwargs): """ Execute an SQL query and return None. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runOperation(*args, **kwargs) except: d = defer.Deferred() d.errback() return d
Nixiware/viper
nx/viper/service/mysql.py
Service._initDatabase
python
def _initDatabase(self): queries = [] if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0: for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]: sqlFile = open(scriptFilePath, "r") queriesInFile = self.extractFromSQLFile(sqlFile) sqlFile.close() queries.extend(queriesInFile) def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() self.log.error( "[Viper.MySQL] _initDatabase() database error: {errorMessage}", errorMessage=errorMessage ) def runCallback(transaction, queries): try: for query in queries: transaction.execute(query) except Exception as e: failCallback(e) return interaction = self.runInteraction(runCallback, queries) interaction.addErrback(failCallback)
Initializes the database structure based on application configuration. :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L127-L162
null
class Service: """ MySQL Database service Wrapper for Twisted's adbapi for interacting with a MySQL database. """ log = Logger() def __init__(self, application): self.application = application self.application.eventDispatcher.addObserver( ViperApplication.kEventApplicationStart, self._applicationStart ) def _applicationStart(self, data): """ Initializes the database connection pool. :param data: <object> event data object :return: <void> """ checkup = False if "viper.mysql" in self.application.config \ and isinstance(self.application.config["viper.mysql"], dict): if "host" in self.application.config["viper.mysql"] and \ "port" in self.application.config["viper.mysql"] and \ "name" in self.application.config["viper.mysql"]: if len(self.application.config["viper.mysql"]["host"]) > 0 and \ self.application.config["viper.mysql"]["port"] > 0 and \ len(self.application.config["viper.mysql"]["name"]) > 0: checkup = True if checkup is not True: return try: self._connectionPool = adbapi.ConnectionPool( "MySQLdb", host=self.application.config["viper.mysql"]["host"], port=int(self.application.config["viper.mysql"]["port"]), user=self.application.config["viper.mysql"]["username"], passwd=self.application.config["viper.mysql"]["password"], db=self.application.config["viper.mysql"]["name"], charset=self.application.config["viper.mysql"]["charset"], cp_min=int( self.application.config["viper.mysql"]["connectionsMinimum"] ), cp_max=int( self.application.config["viper.mysql"]["connectionsMaximum"] ), cp_reconnect=True ) except Exception as e: self.log.error( "[Viper.MySQL] Cannot connect to server. Error: {error}", error=str(e) ) if "init" in self.application.config["viper.mysql"] \ and self.application.config["viper.mysql"]["init"]["runIfEmpty"]: self._checkIfDatabaseIsEmpty( lambda isEmpty: self._scheduleDatabaseInit(isEmpty) , lambda error: self.log.error("[Viper.MySQL] Cannot check if database is empty. Error {error}", error=error) ) def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None): """ Check if database contains any tables. :param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument is a boolean flag specifying if the database is empty or not :param failHandler: <function(<str>)> method called if interrogation failed where the first argument is the error message :return: <void> """ def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() if failHandler is not None: reactor.callInThread(failHandler, errorMessage) def selectCallback(transaction, successHandler): querySelect = \ "SELECT `TABLE_NAME` " \ "FROM INFORMATION_SCHEMA.TABLES " \ "WHERE " \ "`TABLE_SCHEMA` = %s" \ ";" try: transaction.execute( querySelect, (self.application.config["viper.mysql"]["name"],) ) tables = transaction.fetchall() except Exception as e: failCallback(e) return if successHandler is not None: reactor.callInThread(successHandler, len(tables) == 0) interaction = self.runInteraction(selectCallback, successHandler) interaction.addErrback(failCallback) def _scheduleDatabaseInit(self, isEmpty): """ Schedule database initialization if database is empty. :param isEmpty: <bool> flag for database empty status :return: <void> """ if isEmpty: self._initDatabase() def extractFromSQLFile(self, filePointer, delimiter=";"): """ Process an SQL file and extract all the queries sorted. :param filePointer: <io.TextIOWrapper> file pointer to SQL file :return: <list> list of queries """ data = filePointer.read() # reading file and splitting it into lines dataLines = [] dataLinesIndex = 0 for c in data: if len(dataLines) - 1 < dataLinesIndex: dataLines.append("") if c == "\r\n" or c == "\r" or c == "\n": dataLinesIndex += 1 else: dataLines[dataLinesIndex] = "{}{}".format( dataLines[dataLinesIndex], c ) # forming SQL statements from all lines provided statements = [] statementsIndex = 0 for line in dataLines: # ignoring comments if line.startswith("--") or line.startswith("#"): continue # removing spaces line = line.strip() # ignoring blank lines if len(line) == 0: continue # appending each character to it's statement until delimiter is reached for c in line: if len(statements) - 1 < statementsIndex: statements.append("") statements[statementsIndex] = "{}{}".format( statements[statementsIndex], c ) if c == delimiter: statementsIndex += 1 return statements def runInteraction(self, interaction, *args, **kwargs): """ Interact with the database and return the result. :param interaction: <function> method with first argument is a <adbapi.Transaction> instance :param args: additional positional arguments to be passed to interaction :param kwargs: keyword arguments to be passed to interaction :return: <defer> """ try: return self._connectionPool.runInteraction( interaction, *args, **kwargs ) except: d = defer.Deferred() d.errback() return d def runQuery(self, *args, **kwargs): """ Execute an SQL query and return the result. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runQuery(*args, **kwargs) except: d = defer.Deferred() d.errback() return d def runOperation(self, *args, **kwargs): """ Execute an SQL query and return None. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runOperation(*args, **kwargs) except: d = defer.Deferred() d.errback() return d
Nixiware/viper
nx/viper/service/mysql.py
Service.extractFromSQLFile
python
def extractFromSQLFile(self, filePointer, delimiter=";"): data = filePointer.read() # reading file and splitting it into lines dataLines = [] dataLinesIndex = 0 for c in data: if len(dataLines) - 1 < dataLinesIndex: dataLines.append("") if c == "\r\n" or c == "\r" or c == "\n": dataLinesIndex += 1 else: dataLines[dataLinesIndex] = "{}{}".format( dataLines[dataLinesIndex], c ) # forming SQL statements from all lines provided statements = [] statementsIndex = 0 for line in dataLines: # ignoring comments if line.startswith("--") or line.startswith("#"): continue # removing spaces line = line.strip() # ignoring blank lines if len(line) == 0: continue # appending each character to it's statement until delimiter is reached for c in line: if len(statements) - 1 < statementsIndex: statements.append("") statements[statementsIndex] = "{}{}".format( statements[statementsIndex], c ) if c == delimiter: statementsIndex += 1 return statements
Process an SQL file and extract all the queries sorted. :param filePointer: <io.TextIOWrapper> file pointer to SQL file :return: <list> list of queries
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L174-L226
null
class Service: """ MySQL Database service Wrapper for Twisted's adbapi for interacting with a MySQL database. """ log = Logger() def __init__(self, application): self.application = application self.application.eventDispatcher.addObserver( ViperApplication.kEventApplicationStart, self._applicationStart ) def _applicationStart(self, data): """ Initializes the database connection pool. :param data: <object> event data object :return: <void> """ checkup = False if "viper.mysql" in self.application.config \ and isinstance(self.application.config["viper.mysql"], dict): if "host" in self.application.config["viper.mysql"] and \ "port" in self.application.config["viper.mysql"] and \ "name" in self.application.config["viper.mysql"]: if len(self.application.config["viper.mysql"]["host"]) > 0 and \ self.application.config["viper.mysql"]["port"] > 0 and \ len(self.application.config["viper.mysql"]["name"]) > 0: checkup = True if checkup is not True: return try: self._connectionPool = adbapi.ConnectionPool( "MySQLdb", host=self.application.config["viper.mysql"]["host"], port=int(self.application.config["viper.mysql"]["port"]), user=self.application.config["viper.mysql"]["username"], passwd=self.application.config["viper.mysql"]["password"], db=self.application.config["viper.mysql"]["name"], charset=self.application.config["viper.mysql"]["charset"], cp_min=int( self.application.config["viper.mysql"]["connectionsMinimum"] ), cp_max=int( self.application.config["viper.mysql"]["connectionsMaximum"] ), cp_reconnect=True ) except Exception as e: self.log.error( "[Viper.MySQL] Cannot connect to server. Error: {error}", error=str(e) ) if "init" in self.application.config["viper.mysql"] \ and self.application.config["viper.mysql"]["init"]["runIfEmpty"]: self._checkIfDatabaseIsEmpty( lambda isEmpty: self._scheduleDatabaseInit(isEmpty) , lambda error: self.log.error("[Viper.MySQL] Cannot check if database is empty. Error {error}", error=error) ) def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None): """ Check if database contains any tables. :param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument is a boolean flag specifying if the database is empty or not :param failHandler: <function(<str>)> method called if interrogation failed where the first argument is the error message :return: <void> """ def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() if failHandler is not None: reactor.callInThread(failHandler, errorMessage) def selectCallback(transaction, successHandler): querySelect = \ "SELECT `TABLE_NAME` " \ "FROM INFORMATION_SCHEMA.TABLES " \ "WHERE " \ "`TABLE_SCHEMA` = %s" \ ";" try: transaction.execute( querySelect, (self.application.config["viper.mysql"]["name"],) ) tables = transaction.fetchall() except Exception as e: failCallback(e) return if successHandler is not None: reactor.callInThread(successHandler, len(tables) == 0) interaction = self.runInteraction(selectCallback, successHandler) interaction.addErrback(failCallback) def _initDatabase(self): """ Initializes the database structure based on application configuration. :return: <void> """ queries = [] if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0: for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]: sqlFile = open(scriptFilePath, "r") queriesInFile = self.extractFromSQLFile(sqlFile) sqlFile.close() queries.extend(queriesInFile) def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() self.log.error( "[Viper.MySQL] _initDatabase() database error: {errorMessage}", errorMessage=errorMessage ) def runCallback(transaction, queries): try: for query in queries: transaction.execute(query) except Exception as e: failCallback(e) return interaction = self.runInteraction(runCallback, queries) interaction.addErrback(failCallback) def _scheduleDatabaseInit(self, isEmpty): """ Schedule database initialization if database is empty. :param isEmpty: <bool> flag for database empty status :return: <void> """ if isEmpty: self._initDatabase() def runInteraction(self, interaction, *args, **kwargs): """ Interact with the database and return the result. :param interaction: <function> method with first argument is a <adbapi.Transaction> instance :param args: additional positional arguments to be passed to interaction :param kwargs: keyword arguments to be passed to interaction :return: <defer> """ try: return self._connectionPool.runInteraction( interaction, *args, **kwargs ) except: d = defer.Deferred() d.errback() return d def runQuery(self, *args, **kwargs): """ Execute an SQL query and return the result. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runQuery(*args, **kwargs) except: d = defer.Deferred() d.errback() return d def runOperation(self, *args, **kwargs): """ Execute an SQL query and return None. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runOperation(*args, **kwargs) except: d = defer.Deferred() d.errback() return d
Nixiware/viper
nx/viper/service/mysql.py
Service.runInteraction
python
def runInteraction(self, interaction, *args, **kwargs): try: return self._connectionPool.runInteraction( interaction, *args, **kwargs ) except: d = defer.Deferred() d.errback() return d
Interact with the database and return the result. :param interaction: <function> method with first argument is a <adbapi.Transaction> instance :param args: additional positional arguments to be passed to interaction :param kwargs: keyword arguments to be passed to interaction :return: <defer>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L228-L246
null
class Service: """ MySQL Database service Wrapper for Twisted's adbapi for interacting with a MySQL database. """ log = Logger() def __init__(self, application): self.application = application self.application.eventDispatcher.addObserver( ViperApplication.kEventApplicationStart, self._applicationStart ) def _applicationStart(self, data): """ Initializes the database connection pool. :param data: <object> event data object :return: <void> """ checkup = False if "viper.mysql" in self.application.config \ and isinstance(self.application.config["viper.mysql"], dict): if "host" in self.application.config["viper.mysql"] and \ "port" in self.application.config["viper.mysql"] and \ "name" in self.application.config["viper.mysql"]: if len(self.application.config["viper.mysql"]["host"]) > 0 and \ self.application.config["viper.mysql"]["port"] > 0 and \ len(self.application.config["viper.mysql"]["name"]) > 0: checkup = True if checkup is not True: return try: self._connectionPool = adbapi.ConnectionPool( "MySQLdb", host=self.application.config["viper.mysql"]["host"], port=int(self.application.config["viper.mysql"]["port"]), user=self.application.config["viper.mysql"]["username"], passwd=self.application.config["viper.mysql"]["password"], db=self.application.config["viper.mysql"]["name"], charset=self.application.config["viper.mysql"]["charset"], cp_min=int( self.application.config["viper.mysql"]["connectionsMinimum"] ), cp_max=int( self.application.config["viper.mysql"]["connectionsMaximum"] ), cp_reconnect=True ) except Exception as e: self.log.error( "[Viper.MySQL] Cannot connect to server. Error: {error}", error=str(e) ) if "init" in self.application.config["viper.mysql"] \ and self.application.config["viper.mysql"]["init"]["runIfEmpty"]: self._checkIfDatabaseIsEmpty( lambda isEmpty: self._scheduleDatabaseInit(isEmpty) , lambda error: self.log.error("[Viper.MySQL] Cannot check if database is empty. Error {error}", error=error) ) def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None): """ Check if database contains any tables. :param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument is a boolean flag specifying if the database is empty or not :param failHandler: <function(<str>)> method called if interrogation failed where the first argument is the error message :return: <void> """ def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() if failHandler is not None: reactor.callInThread(failHandler, errorMessage) def selectCallback(transaction, successHandler): querySelect = \ "SELECT `TABLE_NAME` " \ "FROM INFORMATION_SCHEMA.TABLES " \ "WHERE " \ "`TABLE_SCHEMA` = %s" \ ";" try: transaction.execute( querySelect, (self.application.config["viper.mysql"]["name"],) ) tables = transaction.fetchall() except Exception as e: failCallback(e) return if successHandler is not None: reactor.callInThread(successHandler, len(tables) == 0) interaction = self.runInteraction(selectCallback, successHandler) interaction.addErrback(failCallback) def _initDatabase(self): """ Initializes the database structure based on application configuration. :return: <void> """ queries = [] if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0: for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]: sqlFile = open(scriptFilePath, "r") queriesInFile = self.extractFromSQLFile(sqlFile) sqlFile.close() queries.extend(queriesInFile) def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() self.log.error( "[Viper.MySQL] _initDatabase() database error: {errorMessage}", errorMessage=errorMessage ) def runCallback(transaction, queries): try: for query in queries: transaction.execute(query) except Exception as e: failCallback(e) return interaction = self.runInteraction(runCallback, queries) interaction.addErrback(failCallback) def _scheduleDatabaseInit(self, isEmpty): """ Schedule database initialization if database is empty. :param isEmpty: <bool> flag for database empty status :return: <void> """ if isEmpty: self._initDatabase() def extractFromSQLFile(self, filePointer, delimiter=";"): """ Process an SQL file and extract all the queries sorted. :param filePointer: <io.TextIOWrapper> file pointer to SQL file :return: <list> list of queries """ data = filePointer.read() # reading file and splitting it into lines dataLines = [] dataLinesIndex = 0 for c in data: if len(dataLines) - 1 < dataLinesIndex: dataLines.append("") if c == "\r\n" or c == "\r" or c == "\n": dataLinesIndex += 1 else: dataLines[dataLinesIndex] = "{}{}".format( dataLines[dataLinesIndex], c ) # forming SQL statements from all lines provided statements = [] statementsIndex = 0 for line in dataLines: # ignoring comments if line.startswith("--") or line.startswith("#"): continue # removing spaces line = line.strip() # ignoring blank lines if len(line) == 0: continue # appending each character to it's statement until delimiter is reached for c in line: if len(statements) - 1 < statementsIndex: statements.append("") statements[statementsIndex] = "{}{}".format( statements[statementsIndex], c ) if c == delimiter: statementsIndex += 1 return statements def runQuery(self, *args, **kwargs): """ Execute an SQL query and return the result. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runQuery(*args, **kwargs) except: d = defer.Deferred() d.errback() return d def runOperation(self, *args, **kwargs): """ Execute an SQL query and return None. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runOperation(*args, **kwargs) except: d = defer.Deferred() d.errback() return d
Nixiware/viper
nx/viper/service/mysql.py
Service.runQuery
python
def runQuery(self, *args, **kwargs): try: return self._connectionPool.runQuery(*args, **kwargs) except: d = defer.Deferred() d.errback() return d
Execute an SQL query and return the result. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L248-L261
null
class Service: """ MySQL Database service Wrapper for Twisted's adbapi for interacting with a MySQL database. """ log = Logger() def __init__(self, application): self.application = application self.application.eventDispatcher.addObserver( ViperApplication.kEventApplicationStart, self._applicationStart ) def _applicationStart(self, data): """ Initializes the database connection pool. :param data: <object> event data object :return: <void> """ checkup = False if "viper.mysql" in self.application.config \ and isinstance(self.application.config["viper.mysql"], dict): if "host" in self.application.config["viper.mysql"] and \ "port" in self.application.config["viper.mysql"] and \ "name" in self.application.config["viper.mysql"]: if len(self.application.config["viper.mysql"]["host"]) > 0 and \ self.application.config["viper.mysql"]["port"] > 0 and \ len(self.application.config["viper.mysql"]["name"]) > 0: checkup = True if checkup is not True: return try: self._connectionPool = adbapi.ConnectionPool( "MySQLdb", host=self.application.config["viper.mysql"]["host"], port=int(self.application.config["viper.mysql"]["port"]), user=self.application.config["viper.mysql"]["username"], passwd=self.application.config["viper.mysql"]["password"], db=self.application.config["viper.mysql"]["name"], charset=self.application.config["viper.mysql"]["charset"], cp_min=int( self.application.config["viper.mysql"]["connectionsMinimum"] ), cp_max=int( self.application.config["viper.mysql"]["connectionsMaximum"] ), cp_reconnect=True ) except Exception as e: self.log.error( "[Viper.MySQL] Cannot connect to server. Error: {error}", error=str(e) ) if "init" in self.application.config["viper.mysql"] \ and self.application.config["viper.mysql"]["init"]["runIfEmpty"]: self._checkIfDatabaseIsEmpty( lambda isEmpty: self._scheduleDatabaseInit(isEmpty) , lambda error: self.log.error("[Viper.MySQL] Cannot check if database is empty. Error {error}", error=error) ) def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None): """ Check if database contains any tables. :param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument is a boolean flag specifying if the database is empty or not :param failHandler: <function(<str>)> method called if interrogation failed where the first argument is the error message :return: <void> """ def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() if failHandler is not None: reactor.callInThread(failHandler, errorMessage) def selectCallback(transaction, successHandler): querySelect = \ "SELECT `TABLE_NAME` " \ "FROM INFORMATION_SCHEMA.TABLES " \ "WHERE " \ "`TABLE_SCHEMA` = %s" \ ";" try: transaction.execute( querySelect, (self.application.config["viper.mysql"]["name"],) ) tables = transaction.fetchall() except Exception as e: failCallback(e) return if successHandler is not None: reactor.callInThread(successHandler, len(tables) == 0) interaction = self.runInteraction(selectCallback, successHandler) interaction.addErrback(failCallback) def _initDatabase(self): """ Initializes the database structure based on application configuration. :return: <void> """ queries = [] if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0: for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]: sqlFile = open(scriptFilePath, "r") queriesInFile = self.extractFromSQLFile(sqlFile) sqlFile.close() queries.extend(queriesInFile) def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() self.log.error( "[Viper.MySQL] _initDatabase() database error: {errorMessage}", errorMessage=errorMessage ) def runCallback(transaction, queries): try: for query in queries: transaction.execute(query) except Exception as e: failCallback(e) return interaction = self.runInteraction(runCallback, queries) interaction.addErrback(failCallback) def _scheduleDatabaseInit(self, isEmpty): """ Schedule database initialization if database is empty. :param isEmpty: <bool> flag for database empty status :return: <void> """ if isEmpty: self._initDatabase() def extractFromSQLFile(self, filePointer, delimiter=";"): """ Process an SQL file and extract all the queries sorted. :param filePointer: <io.TextIOWrapper> file pointer to SQL file :return: <list> list of queries """ data = filePointer.read() # reading file and splitting it into lines dataLines = [] dataLinesIndex = 0 for c in data: if len(dataLines) - 1 < dataLinesIndex: dataLines.append("") if c == "\r\n" or c == "\r" or c == "\n": dataLinesIndex += 1 else: dataLines[dataLinesIndex] = "{}{}".format( dataLines[dataLinesIndex], c ) # forming SQL statements from all lines provided statements = [] statementsIndex = 0 for line in dataLines: # ignoring comments if line.startswith("--") or line.startswith("#"): continue # removing spaces line = line.strip() # ignoring blank lines if len(line) == 0: continue # appending each character to it's statement until delimiter is reached for c in line: if len(statements) - 1 < statementsIndex: statements.append("") statements[statementsIndex] = "{}{}".format( statements[statementsIndex], c ) if c == delimiter: statementsIndex += 1 return statements def runInteraction(self, interaction, *args, **kwargs): """ Interact with the database and return the result. :param interaction: <function> method with first argument is a <adbapi.Transaction> instance :param args: additional positional arguments to be passed to interaction :param kwargs: keyword arguments to be passed to interaction :return: <defer> """ try: return self._connectionPool.runInteraction( interaction, *args, **kwargs ) except: d = defer.Deferred() d.errback() return d def runOperation(self, *args, **kwargs): """ Execute an SQL query and return None. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """ try: return self._connectionPool.runOperation(*args, **kwargs) except: d = defer.Deferred() d.errback() return d
Nixiware/viper
nx/viper/dispatcher.py
Dispatcher.dispatch
python
def dispatch(self, requestProtocol, requestPayload): # method decoding method = requestPayload["method"].split(".") if len(method) != 3: requestProtocol.failRequestWithErrors(["InvalidMethod"]) return # parsing method name methodModule = method[0] methodController = method[1] methodAction = method[2] # checking if module exists if not self.application.isModuleLoaded(methodModule): requestProtocol.failRequestWithErrors(["InvalidMethodModule"]) return # checking if controller exists controllerPath = os.path.join( "application", "module", methodModule, "controller", "{}.py".format(methodController) ) if not os.path.isfile(controllerPath): requestProtocol.failRequestWithErrors(["InvalidMethodController"]) return # importing controller controllerSpec = importlib.util.spec_from_file_location( methodController, controllerPath ) controller = importlib.util.module_from_spec(controllerSpec) controllerSpec.loader.exec_module(controller) # instancing controller controllerInstance = controller.Controller( self.application, requestProtocol, requestPayload["version"], requestPayload["parameters"] ) # checking if action exists action = getattr( controllerInstance, "{}Action".format(methodAction), None ) if not callable(action): requestProtocol.failRequestWithErrors(["InvalidMethodAction"]) return # executing action requestProtocol.requestPassedDispatcherValidation() preDispatchAction = getattr(controllerInstance, "preDispatch") postDispatchAction = getattr(controllerInstance, "postDispatch") preDispatchAction() action() postDispatchAction()
Dispatch the request to the appropriate handler. :param requestProtocol: <AbstractApplicationInterfaceProtocol> request protocol :param requestPayload: <dict> request :param version: <float> version :param method: <str> method name :param parameters: <dict> data parameters :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/dispatcher.py#L16-L89
null
class Dispatcher(): """ Viper dispatcher Handles requests coming through any of the application's communication interfaces and dispatches the appropriate controller. """ def __init__(self, application): self.application = application
Nixiware/viper
nx/viper/config.py
Config.mergeDictionaries
python
def mergeDictionaries(sourceDictionary, destinationDictionary): log = Logger() varNamePattern = re.compile(r"^((__((ENV)|(FILE))__[A-Z]{3,})|(__((ENV)|(FILE))))__(?P<name>.*)$") varTypePattern = re.compile(r"^__((ENV)|(FILE))__(?P<type>[A-Z]{3,})__(.*)$") for key, value in sourceDictionary.items(): # ignoring comments if key == "//": continue if isinstance(value, dict): # get node or create one node = destinationDictionary.setdefault(key, {}) Config.mergeDictionaries(value, node) elif isinstance(value, str) and (value.startswith("__ENV__") or value.startswith("__FILE__")): # extracting environment variable name nameMatch = varNamePattern.match(value) if nameMatch is None: log.warn("Invalid environmental variable specified: {name}", name=value) continue envVariableName = nameMatch.group("name") # checking if environment variable is set if envVariableName not in os.environ: log.warn("No environment variable {name} is set.", name=envVariableName) continue if value.startswith("__ENV__"): # checking if value is set in the environment variable # checking if variable has a defined cast type typeMatch = varTypePattern.match(value) if typeMatch is not None: envVariableType = typeMatch.group("type") # casting value to the specified type if envVariableType == "STR": destinationDictionary[key] = str(os.environ[envVariableName]) elif envVariableType == "BOOL": if os.environ[envVariableName] == "1": destinationDictionary[key] = True elif os.environ[envVariableName] == "0": destinationDictionary[key] = False elif envVariableType == "INT": destinationDictionary[key] = int(os.environ[envVariableName]) elif envVariableType == "FLOAT": destinationDictionary[key] = float(os.environ[envVariableName]) elif envVariableType == "JSON": try: destinationDictionary[key] = json.loads(os.environ[envVariableName]) except Exception: log.warn( "Environment variable {name} contains an invalid JSON value.", name=envVariableName ) else: log.warn( "Unsupported type {type} specified for variable {name}.", name=envVariableName, type=envVariableType ) continue else: destinationDictionary[key] = os.environ[envVariableName] elif value.startswith("__FILE__"): # checking if value is set in a file filePath = os.environ[envVariableName] # checking if file exists if not os.path.isfile(filePath): log.warn( "File {filePath} does not exist.", filePath=filePath, ) continue # checking if file can be read if not os.access(filePath, os.R_OK): log.warn( "File {filePath} cannot be read.", filePath=filePath, ) continue # load file contents filePointer = open(filePath, "r") destinationDictionary[key] = filePointer.read().strip() filePointer.close() elif isinstance(value, str) and value.startswith("__FILE__"): pass else: destinationDictionary[key] = value return destinationDictionary
Deep merge dictionaries recursively. :param sourceDictionary: <dict> first dictionary with data :param destinationDictionary: <dict> second dictionary with data :return: <dict> merged dictionary
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/config.py#L70-L167
[ "def mergeDictionaries(sourceDictionary, destinationDictionary):\n \"\"\"\n Deep merge dictionaries recursively.\n\n :param sourceDictionary: <dict> first dictionary with data\n :param destinationDictionary: <dict> second dictionary with data\n :return: <dict> merged dictionary\n \"\"\"\n log =...
class Config: """ Configuration Load JSON configuration files at a specified directory, prioritizing *.local over *.global and merging into a single dictionary. Allows inclusion of comments in JSON. """ def __init__(self, directoryPath): """ Load all configuration files at a given path. :param directoryPath: <str> path to load """ self._data = {} configFiles = os.listdir(directoryPath) configFilesPendingLoading = [] # loading global and *.global.json files if "global.json" in configFiles: configFilesPendingLoading.append( os.path.join(directoryPath, "global.json") ) for configFile in configFiles: if configFile.endswith(".global.json"): configFilesPendingLoading.append( os.path.join(directoryPath, configFile) ) # loading local and *.local.json files if "local.json" in configFiles: configFilesPendingLoading.append( os.path.join(directoryPath, "local.json") ) for configFile in configFiles: if configFile.endswith(".local.json"): configFilesPendingLoading.append( os.path.join(directoryPath, configFile) ) # loading remaining config files for configFile in configFiles: if configFile.endswith(".config.json"): configFilesPendingLoading.append( os.path.join(directoryPath, configFile) ) for configFilePath in configFilesPendingLoading: configFile = open(configFilePath, "r") Config.mergeDictionaries(json.load(configFile), self._data) def getData(self): """ Return the loaded configuration data. :return: <dict> """ return self._data @staticmethod
Nixiware/viper
nx/viper/application.py
Application._getConfiguration
python
def _getConfiguration(self): configDirectoryPath = os.path.join("application", "config") config = Config(configDirectoryPath) configData = config.getData() # setting application parameters reactor.suggestThreadPoolSize( int(configData["performance"]["threadPoolSize"]) ) return configData
Load application configuration files. :return: <dict>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L42-L57
null
class Application: """ Viper application Core component, handles the loading of configuration, instances all the modules and their services and models. """ # # Events # eventDispatcher = EventDispatcher() kEventApplicationStart = "//event/applicationStart" kEventApplicationStop = "//event/applicationStop" def __init__(self): self.requestDispatcher = Dispatcher(self) self.config = self._getConfiguration() self._interfaces = self._getInterfaces() self._models = {} self._services = {} self._loadViperServices() self._modules = self._getModules() # # Configuration # # # Interfaces # def _getInterfaces(self): """ Load application communication interfaces. :return: <dict> """ interfaces = {} interfacesPath = os.path.join("application", "interface") interfaceList = os.listdir(interfacesPath) for file in interfaceList: interfaceDirectoryPath = os.path.join(interfacesPath, file) if not os.path.isdir(interfaceDirectoryPath) or file.startswith("__") or file.startswith("."): continue interfaceName = ntpath.basename(interfaceDirectoryPath) interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + ".py" if not os.path.isfile(interfacePath): continue # importing interface interfaceSpec = importlib.util.spec_from_file_location( interfaceName, interfacePath ) interface = importlib.util.module_from_spec(interfaceSpec) interfaceSpec.loader.exec_module(interface) # checking if there is an interface in the file if hasattr(interface, "Service"): # initializing interface interfaceInstance = interface.Service(self) interfaces[interfaceName] = interfaceInstance return interfaces def getInterfaces(self): """ Return loaded communication interfaces. :return: <dict> """ return self._interfaces # # Modules # def _getModules(self): """ Import and load application modules. :return: <dict> """ modules = {} modulesPath = os.path.join("application", "module") moduleList = os.listdir(modulesPath) for moduleName in moduleList: modulePath = os.path.join(modulesPath, moduleName, "module.py") if not os.path.isfile(modulePath): continue # importing module moduleSpec = importlib.util.spec_from_file_location( moduleName, modulePath ) module = importlib.util.module_from_spec(moduleSpec) moduleSpec.loader.exec_module(module) # initializing module moduleInstance = module.Module(self) modules[moduleName] = moduleInstance return modules def isModuleLoaded(self, moduleName): """ Verify if a module is loaded. :param moduleName: <str> module name :return: <bool> True if loaded, False otherwise """ if moduleName in self._modules: return True return False # # Models # def addModel(self, moduleName, modelName, model): """ Add a model instance to the application model pool. :param moduleName: <str> module name in which the model is located :param modelName: <str> model name :param model: <object> model instance :return: <void> """ modelIdentifier = "{}.{}".format(moduleName, modelName) if modelIdentifier not in self._models: self._models[modelIdentifier] = model else: message = "Application - addModel() - " \ "A model with the identifier {} already exists." \ .format(modelIdentifier) raise Exception(message) def getModel(self, modelIdentifier): """ Return the requested model. :param modelIdentifier: <str> model identifier :return: <object> model instance """ if modelIdentifier in self._models: return self._models[modelIdentifier] else: message = "Application - getModel() - " \ "Model with identifier {} does not exist." \ .format(modelIdentifier) raise Exception(message) # # Services # def _loadViperServices(self): """ Load application bundled services. :return: <void> """ servicesPath = os.path.join( os.path.dirname(os.path.realpath(__file__)), "service" ) for serviceFile in os.listdir(servicesPath): if serviceFile.startswith("__") or serviceFile.startswith("."): continue serviceName = serviceFile.replace(".py", "") servicePath = os.path.join( servicesPath, serviceFile ) if not os.path.isfile(servicePath): continue # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # initializing service serviceInstance = service.Service(self) self.addService("viper", serviceName, serviceInstance) def addService(self, moduleName, serviceName, service): """ Add a service instance to the application service pool. :param moduleName: <str> module name in which the service is located :param serviceName: <str> service name :param service: <object> service instance :return: <void> """ serviceIdentifier = "{}.{}".format(moduleName, serviceName) if serviceIdentifier not in self._services: self._services[serviceIdentifier] = service else: message = "Application - addService() - " \ "A service with the identifier {} already exists." \ .format(serviceIdentifier) raise Exception(message) def getService(self, serviceIdentifier): """ Return the requested service instance. :param serviceIdentifier: <str> service identifier :return: <object> service instance """ if serviceIdentifier in self._services: return self._services[serviceIdentifier] else: message = "Application - getService() - " \ "Service with identifier {} does not exist." \ .format(serviceIdentifier) raise Exception(message) def start(self): """ Start the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStart) def stop(self): """ Stop the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStop)
Nixiware/viper
nx/viper/application.py
Application._getInterfaces
python
def _getInterfaces(self): interfaces = {} interfacesPath = os.path.join("application", "interface") interfaceList = os.listdir(interfacesPath) for file in interfaceList: interfaceDirectoryPath = os.path.join(interfacesPath, file) if not os.path.isdir(interfaceDirectoryPath) or file.startswith("__") or file.startswith("."): continue interfaceName = ntpath.basename(interfaceDirectoryPath) interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + ".py" if not os.path.isfile(interfacePath): continue # importing interface interfaceSpec = importlib.util.spec_from_file_location( interfaceName, interfacePath ) interface = importlib.util.module_from_spec(interfaceSpec) interfaceSpec.loader.exec_module(interface) # checking if there is an interface in the file if hasattr(interface, "Service"): # initializing interface interfaceInstance = interface.Service(self) interfaces[interfaceName] = interfaceInstance return interfaces
Load application communication interfaces. :return: <dict>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L62-L98
null
class Application: """ Viper application Core component, handles the loading of configuration, instances all the modules and their services and models. """ # # Events # eventDispatcher = EventDispatcher() kEventApplicationStart = "//event/applicationStart" kEventApplicationStop = "//event/applicationStop" def __init__(self): self.requestDispatcher = Dispatcher(self) self.config = self._getConfiguration() self._interfaces = self._getInterfaces() self._models = {} self._services = {} self._loadViperServices() self._modules = self._getModules() # # Configuration # def _getConfiguration(self): """ Load application configuration files. :return: <dict> """ configDirectoryPath = os.path.join("application", "config") config = Config(configDirectoryPath) configData = config.getData() # setting application parameters reactor.suggestThreadPoolSize( int(configData["performance"]["threadPoolSize"]) ) return configData # # Interfaces # def getInterfaces(self): """ Return loaded communication interfaces. :return: <dict> """ return self._interfaces # # Modules # def _getModules(self): """ Import and load application modules. :return: <dict> """ modules = {} modulesPath = os.path.join("application", "module") moduleList = os.listdir(modulesPath) for moduleName in moduleList: modulePath = os.path.join(modulesPath, moduleName, "module.py") if not os.path.isfile(modulePath): continue # importing module moduleSpec = importlib.util.spec_from_file_location( moduleName, modulePath ) module = importlib.util.module_from_spec(moduleSpec) moduleSpec.loader.exec_module(module) # initializing module moduleInstance = module.Module(self) modules[moduleName] = moduleInstance return modules def isModuleLoaded(self, moduleName): """ Verify if a module is loaded. :param moduleName: <str> module name :return: <bool> True if loaded, False otherwise """ if moduleName in self._modules: return True return False # # Models # def addModel(self, moduleName, modelName, model): """ Add a model instance to the application model pool. :param moduleName: <str> module name in which the model is located :param modelName: <str> model name :param model: <object> model instance :return: <void> """ modelIdentifier = "{}.{}".format(moduleName, modelName) if modelIdentifier not in self._models: self._models[modelIdentifier] = model else: message = "Application - addModel() - " \ "A model with the identifier {} already exists." \ .format(modelIdentifier) raise Exception(message) def getModel(self, modelIdentifier): """ Return the requested model. :param modelIdentifier: <str> model identifier :return: <object> model instance """ if modelIdentifier in self._models: return self._models[modelIdentifier] else: message = "Application - getModel() - " \ "Model with identifier {} does not exist." \ .format(modelIdentifier) raise Exception(message) # # Services # def _loadViperServices(self): """ Load application bundled services. :return: <void> """ servicesPath = os.path.join( os.path.dirname(os.path.realpath(__file__)), "service" ) for serviceFile in os.listdir(servicesPath): if serviceFile.startswith("__") or serviceFile.startswith("."): continue serviceName = serviceFile.replace(".py", "") servicePath = os.path.join( servicesPath, serviceFile ) if not os.path.isfile(servicePath): continue # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # initializing service serviceInstance = service.Service(self) self.addService("viper", serviceName, serviceInstance) def addService(self, moduleName, serviceName, service): """ Add a service instance to the application service pool. :param moduleName: <str> module name in which the service is located :param serviceName: <str> service name :param service: <object> service instance :return: <void> """ serviceIdentifier = "{}.{}".format(moduleName, serviceName) if serviceIdentifier not in self._services: self._services[serviceIdentifier] = service else: message = "Application - addService() - " \ "A service with the identifier {} already exists." \ .format(serviceIdentifier) raise Exception(message) def getService(self, serviceIdentifier): """ Return the requested service instance. :param serviceIdentifier: <str> service identifier :return: <object> service instance """ if serviceIdentifier in self._services: return self._services[serviceIdentifier] else: message = "Application - getService() - " \ "Service with identifier {} does not exist." \ .format(serviceIdentifier) raise Exception(message) def start(self): """ Start the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStart) def stop(self): """ Stop the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStop)
Nixiware/viper
nx/viper/application.py
Application._getModules
python
def _getModules(self): modules = {} modulesPath = os.path.join("application", "module") moduleList = os.listdir(modulesPath) for moduleName in moduleList: modulePath = os.path.join(modulesPath, moduleName, "module.py") if not os.path.isfile(modulePath): continue # importing module moduleSpec = importlib.util.spec_from_file_location( moduleName, modulePath ) module = importlib.util.module_from_spec(moduleSpec) moduleSpec.loader.exec_module(module) # initializing module moduleInstance = module.Module(self) modules[moduleName] = moduleInstance return modules
Import and load application modules. :return: <dict>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L111-L138
null
class Application: """ Viper application Core component, handles the loading of configuration, instances all the modules and their services and models. """ # # Events # eventDispatcher = EventDispatcher() kEventApplicationStart = "//event/applicationStart" kEventApplicationStop = "//event/applicationStop" def __init__(self): self.requestDispatcher = Dispatcher(self) self.config = self._getConfiguration() self._interfaces = self._getInterfaces() self._models = {} self._services = {} self._loadViperServices() self._modules = self._getModules() # # Configuration # def _getConfiguration(self): """ Load application configuration files. :return: <dict> """ configDirectoryPath = os.path.join("application", "config") config = Config(configDirectoryPath) configData = config.getData() # setting application parameters reactor.suggestThreadPoolSize( int(configData["performance"]["threadPoolSize"]) ) return configData # # Interfaces # def _getInterfaces(self): """ Load application communication interfaces. :return: <dict> """ interfaces = {} interfacesPath = os.path.join("application", "interface") interfaceList = os.listdir(interfacesPath) for file in interfaceList: interfaceDirectoryPath = os.path.join(interfacesPath, file) if not os.path.isdir(interfaceDirectoryPath) or file.startswith("__") or file.startswith("."): continue interfaceName = ntpath.basename(interfaceDirectoryPath) interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + ".py" if not os.path.isfile(interfacePath): continue # importing interface interfaceSpec = importlib.util.spec_from_file_location( interfaceName, interfacePath ) interface = importlib.util.module_from_spec(interfaceSpec) interfaceSpec.loader.exec_module(interface) # checking if there is an interface in the file if hasattr(interface, "Service"): # initializing interface interfaceInstance = interface.Service(self) interfaces[interfaceName] = interfaceInstance return interfaces def getInterfaces(self): """ Return loaded communication interfaces. :return: <dict> """ return self._interfaces # # Modules # def isModuleLoaded(self, moduleName): """ Verify if a module is loaded. :param moduleName: <str> module name :return: <bool> True if loaded, False otherwise """ if moduleName in self._modules: return True return False # # Models # def addModel(self, moduleName, modelName, model): """ Add a model instance to the application model pool. :param moduleName: <str> module name in which the model is located :param modelName: <str> model name :param model: <object> model instance :return: <void> """ modelIdentifier = "{}.{}".format(moduleName, modelName) if modelIdentifier not in self._models: self._models[modelIdentifier] = model else: message = "Application - addModel() - " \ "A model with the identifier {} already exists." \ .format(modelIdentifier) raise Exception(message) def getModel(self, modelIdentifier): """ Return the requested model. :param modelIdentifier: <str> model identifier :return: <object> model instance """ if modelIdentifier in self._models: return self._models[modelIdentifier] else: message = "Application - getModel() - " \ "Model with identifier {} does not exist." \ .format(modelIdentifier) raise Exception(message) # # Services # def _loadViperServices(self): """ Load application bundled services. :return: <void> """ servicesPath = os.path.join( os.path.dirname(os.path.realpath(__file__)), "service" ) for serviceFile in os.listdir(servicesPath): if serviceFile.startswith("__") or serviceFile.startswith("."): continue serviceName = serviceFile.replace(".py", "") servicePath = os.path.join( servicesPath, serviceFile ) if not os.path.isfile(servicePath): continue # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # initializing service serviceInstance = service.Service(self) self.addService("viper", serviceName, serviceInstance) def addService(self, moduleName, serviceName, service): """ Add a service instance to the application service pool. :param moduleName: <str> module name in which the service is located :param serviceName: <str> service name :param service: <object> service instance :return: <void> """ serviceIdentifier = "{}.{}".format(moduleName, serviceName) if serviceIdentifier not in self._services: self._services[serviceIdentifier] = service else: message = "Application - addService() - " \ "A service with the identifier {} already exists." \ .format(serviceIdentifier) raise Exception(message) def getService(self, serviceIdentifier): """ Return the requested service instance. :param serviceIdentifier: <str> service identifier :return: <object> service instance """ if serviceIdentifier in self._services: return self._services[serviceIdentifier] else: message = "Application - getService() - " \ "Service with identifier {} does not exist." \ .format(serviceIdentifier) raise Exception(message) def start(self): """ Start the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStart) def stop(self): """ Stop the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStop)
Nixiware/viper
nx/viper/application.py
Application.addModel
python
def addModel(self, moduleName, modelName, model): modelIdentifier = "{}.{}".format(moduleName, modelName) if modelIdentifier not in self._models: self._models[modelIdentifier] = model else: message = "Application - addModel() - " \ "A model with the identifier {} already exists." \ .format(modelIdentifier) raise Exception(message)
Add a model instance to the application model pool. :param moduleName: <str> module name in which the model is located :param modelName: <str> model name :param model: <object> model instance :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L155-L171
null
class Application: """ Viper application Core component, handles the loading of configuration, instances all the modules and their services and models. """ # # Events # eventDispatcher = EventDispatcher() kEventApplicationStart = "//event/applicationStart" kEventApplicationStop = "//event/applicationStop" def __init__(self): self.requestDispatcher = Dispatcher(self) self.config = self._getConfiguration() self._interfaces = self._getInterfaces() self._models = {} self._services = {} self._loadViperServices() self._modules = self._getModules() # # Configuration # def _getConfiguration(self): """ Load application configuration files. :return: <dict> """ configDirectoryPath = os.path.join("application", "config") config = Config(configDirectoryPath) configData = config.getData() # setting application parameters reactor.suggestThreadPoolSize( int(configData["performance"]["threadPoolSize"]) ) return configData # # Interfaces # def _getInterfaces(self): """ Load application communication interfaces. :return: <dict> """ interfaces = {} interfacesPath = os.path.join("application", "interface") interfaceList = os.listdir(interfacesPath) for file in interfaceList: interfaceDirectoryPath = os.path.join(interfacesPath, file) if not os.path.isdir(interfaceDirectoryPath) or file.startswith("__") or file.startswith("."): continue interfaceName = ntpath.basename(interfaceDirectoryPath) interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + ".py" if not os.path.isfile(interfacePath): continue # importing interface interfaceSpec = importlib.util.spec_from_file_location( interfaceName, interfacePath ) interface = importlib.util.module_from_spec(interfaceSpec) interfaceSpec.loader.exec_module(interface) # checking if there is an interface in the file if hasattr(interface, "Service"): # initializing interface interfaceInstance = interface.Service(self) interfaces[interfaceName] = interfaceInstance return interfaces def getInterfaces(self): """ Return loaded communication interfaces. :return: <dict> """ return self._interfaces # # Modules # def _getModules(self): """ Import and load application modules. :return: <dict> """ modules = {} modulesPath = os.path.join("application", "module") moduleList = os.listdir(modulesPath) for moduleName in moduleList: modulePath = os.path.join(modulesPath, moduleName, "module.py") if not os.path.isfile(modulePath): continue # importing module moduleSpec = importlib.util.spec_from_file_location( moduleName, modulePath ) module = importlib.util.module_from_spec(moduleSpec) moduleSpec.loader.exec_module(module) # initializing module moduleInstance = module.Module(self) modules[moduleName] = moduleInstance return modules def isModuleLoaded(self, moduleName): """ Verify if a module is loaded. :param moduleName: <str> module name :return: <bool> True if loaded, False otherwise """ if moduleName in self._modules: return True return False # # Models # def getModel(self, modelIdentifier): """ Return the requested model. :param modelIdentifier: <str> model identifier :return: <object> model instance """ if modelIdentifier in self._models: return self._models[modelIdentifier] else: message = "Application - getModel() - " \ "Model with identifier {} does not exist." \ .format(modelIdentifier) raise Exception(message) # # Services # def _loadViperServices(self): """ Load application bundled services. :return: <void> """ servicesPath = os.path.join( os.path.dirname(os.path.realpath(__file__)), "service" ) for serviceFile in os.listdir(servicesPath): if serviceFile.startswith("__") or serviceFile.startswith("."): continue serviceName = serviceFile.replace(".py", "") servicePath = os.path.join( servicesPath, serviceFile ) if not os.path.isfile(servicePath): continue # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # initializing service serviceInstance = service.Service(self) self.addService("viper", serviceName, serviceInstance) def addService(self, moduleName, serviceName, service): """ Add a service instance to the application service pool. :param moduleName: <str> module name in which the service is located :param serviceName: <str> service name :param service: <object> service instance :return: <void> """ serviceIdentifier = "{}.{}".format(moduleName, serviceName) if serviceIdentifier not in self._services: self._services[serviceIdentifier] = service else: message = "Application - addService() - " \ "A service with the identifier {} already exists." \ .format(serviceIdentifier) raise Exception(message) def getService(self, serviceIdentifier): """ Return the requested service instance. :param serviceIdentifier: <str> service identifier :return: <object> service instance """ if serviceIdentifier in self._services: return self._services[serviceIdentifier] else: message = "Application - getService() - " \ "Service with identifier {} does not exist." \ .format(serviceIdentifier) raise Exception(message) def start(self): """ Start the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStart) def stop(self): """ Stop the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStop)
Nixiware/viper
nx/viper/application.py
Application.getModel
python
def getModel(self, modelIdentifier): if modelIdentifier in self._models: return self._models[modelIdentifier] else: message = "Application - getModel() - " \ "Model with identifier {} does not exist." \ .format(modelIdentifier) raise Exception(message)
Return the requested model. :param modelIdentifier: <str> model identifier :return: <object> model instance
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L173-L186
null
class Application: """ Viper application Core component, handles the loading of configuration, instances all the modules and their services and models. """ # # Events # eventDispatcher = EventDispatcher() kEventApplicationStart = "//event/applicationStart" kEventApplicationStop = "//event/applicationStop" def __init__(self): self.requestDispatcher = Dispatcher(self) self.config = self._getConfiguration() self._interfaces = self._getInterfaces() self._models = {} self._services = {} self._loadViperServices() self._modules = self._getModules() # # Configuration # def _getConfiguration(self): """ Load application configuration files. :return: <dict> """ configDirectoryPath = os.path.join("application", "config") config = Config(configDirectoryPath) configData = config.getData() # setting application parameters reactor.suggestThreadPoolSize( int(configData["performance"]["threadPoolSize"]) ) return configData # # Interfaces # def _getInterfaces(self): """ Load application communication interfaces. :return: <dict> """ interfaces = {} interfacesPath = os.path.join("application", "interface") interfaceList = os.listdir(interfacesPath) for file in interfaceList: interfaceDirectoryPath = os.path.join(interfacesPath, file) if not os.path.isdir(interfaceDirectoryPath) or file.startswith("__") or file.startswith("."): continue interfaceName = ntpath.basename(interfaceDirectoryPath) interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + ".py" if not os.path.isfile(interfacePath): continue # importing interface interfaceSpec = importlib.util.spec_from_file_location( interfaceName, interfacePath ) interface = importlib.util.module_from_spec(interfaceSpec) interfaceSpec.loader.exec_module(interface) # checking if there is an interface in the file if hasattr(interface, "Service"): # initializing interface interfaceInstance = interface.Service(self) interfaces[interfaceName] = interfaceInstance return interfaces def getInterfaces(self): """ Return loaded communication interfaces. :return: <dict> """ return self._interfaces # # Modules # def _getModules(self): """ Import and load application modules. :return: <dict> """ modules = {} modulesPath = os.path.join("application", "module") moduleList = os.listdir(modulesPath) for moduleName in moduleList: modulePath = os.path.join(modulesPath, moduleName, "module.py") if not os.path.isfile(modulePath): continue # importing module moduleSpec = importlib.util.spec_from_file_location( moduleName, modulePath ) module = importlib.util.module_from_spec(moduleSpec) moduleSpec.loader.exec_module(module) # initializing module moduleInstance = module.Module(self) modules[moduleName] = moduleInstance return modules def isModuleLoaded(self, moduleName): """ Verify if a module is loaded. :param moduleName: <str> module name :return: <bool> True if loaded, False otherwise """ if moduleName in self._modules: return True return False # # Models # def addModel(self, moduleName, modelName, model): """ Add a model instance to the application model pool. :param moduleName: <str> module name in which the model is located :param modelName: <str> model name :param model: <object> model instance :return: <void> """ modelIdentifier = "{}.{}".format(moduleName, modelName) if modelIdentifier not in self._models: self._models[modelIdentifier] = model else: message = "Application - addModel() - " \ "A model with the identifier {} already exists." \ .format(modelIdentifier) raise Exception(message) # # Services # def _loadViperServices(self): """ Load application bundled services. :return: <void> """ servicesPath = os.path.join( os.path.dirname(os.path.realpath(__file__)), "service" ) for serviceFile in os.listdir(servicesPath): if serviceFile.startswith("__") or serviceFile.startswith("."): continue serviceName = serviceFile.replace(".py", "") servicePath = os.path.join( servicesPath, serviceFile ) if not os.path.isfile(servicePath): continue # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # initializing service serviceInstance = service.Service(self) self.addService("viper", serviceName, serviceInstance) def addService(self, moduleName, serviceName, service): """ Add a service instance to the application service pool. :param moduleName: <str> module name in which the service is located :param serviceName: <str> service name :param service: <object> service instance :return: <void> """ serviceIdentifier = "{}.{}".format(moduleName, serviceName) if serviceIdentifier not in self._services: self._services[serviceIdentifier] = service else: message = "Application - addService() - " \ "A service with the identifier {} already exists." \ .format(serviceIdentifier) raise Exception(message) def getService(self, serviceIdentifier): """ Return the requested service instance. :param serviceIdentifier: <str> service identifier :return: <object> service instance """ if serviceIdentifier in self._services: return self._services[serviceIdentifier] else: message = "Application - getService() - " \ "Service with identifier {} does not exist." \ .format(serviceIdentifier) raise Exception(message) def start(self): """ Start the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStart) def stop(self): """ Stop the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStop)
Nixiware/viper
nx/viper/application.py
Application._loadViperServices
python
def _loadViperServices(self): servicesPath = os.path.join( os.path.dirname(os.path.realpath(__file__)), "service" ) for serviceFile in os.listdir(servicesPath): if serviceFile.startswith("__") or serviceFile.startswith("."): continue serviceName = serviceFile.replace(".py", "") servicePath = os.path.join( servicesPath, serviceFile ) if not os.path.isfile(servicePath): continue # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # initializing service serviceInstance = service.Service(self) self.addService("viper", serviceName, serviceInstance)
Load application bundled services. :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L191-L223
null
class Application: """ Viper application Core component, handles the loading of configuration, instances all the modules and their services and models. """ # # Events # eventDispatcher = EventDispatcher() kEventApplicationStart = "//event/applicationStart" kEventApplicationStop = "//event/applicationStop" def __init__(self): self.requestDispatcher = Dispatcher(self) self.config = self._getConfiguration() self._interfaces = self._getInterfaces() self._models = {} self._services = {} self._loadViperServices() self._modules = self._getModules() # # Configuration # def _getConfiguration(self): """ Load application configuration files. :return: <dict> """ configDirectoryPath = os.path.join("application", "config") config = Config(configDirectoryPath) configData = config.getData() # setting application parameters reactor.suggestThreadPoolSize( int(configData["performance"]["threadPoolSize"]) ) return configData # # Interfaces # def _getInterfaces(self): """ Load application communication interfaces. :return: <dict> """ interfaces = {} interfacesPath = os.path.join("application", "interface") interfaceList = os.listdir(interfacesPath) for file in interfaceList: interfaceDirectoryPath = os.path.join(interfacesPath, file) if not os.path.isdir(interfaceDirectoryPath) or file.startswith("__") or file.startswith("."): continue interfaceName = ntpath.basename(interfaceDirectoryPath) interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + ".py" if not os.path.isfile(interfacePath): continue # importing interface interfaceSpec = importlib.util.spec_from_file_location( interfaceName, interfacePath ) interface = importlib.util.module_from_spec(interfaceSpec) interfaceSpec.loader.exec_module(interface) # checking if there is an interface in the file if hasattr(interface, "Service"): # initializing interface interfaceInstance = interface.Service(self) interfaces[interfaceName] = interfaceInstance return interfaces def getInterfaces(self): """ Return loaded communication interfaces. :return: <dict> """ return self._interfaces # # Modules # def _getModules(self): """ Import and load application modules. :return: <dict> """ modules = {} modulesPath = os.path.join("application", "module") moduleList = os.listdir(modulesPath) for moduleName in moduleList: modulePath = os.path.join(modulesPath, moduleName, "module.py") if not os.path.isfile(modulePath): continue # importing module moduleSpec = importlib.util.spec_from_file_location( moduleName, modulePath ) module = importlib.util.module_from_spec(moduleSpec) moduleSpec.loader.exec_module(module) # initializing module moduleInstance = module.Module(self) modules[moduleName] = moduleInstance return modules def isModuleLoaded(self, moduleName): """ Verify if a module is loaded. :param moduleName: <str> module name :return: <bool> True if loaded, False otherwise """ if moduleName in self._modules: return True return False # # Models # def addModel(self, moduleName, modelName, model): """ Add a model instance to the application model pool. :param moduleName: <str> module name in which the model is located :param modelName: <str> model name :param model: <object> model instance :return: <void> """ modelIdentifier = "{}.{}".format(moduleName, modelName) if modelIdentifier not in self._models: self._models[modelIdentifier] = model else: message = "Application - addModel() - " \ "A model with the identifier {} already exists." \ .format(modelIdentifier) raise Exception(message) def getModel(self, modelIdentifier): """ Return the requested model. :param modelIdentifier: <str> model identifier :return: <object> model instance """ if modelIdentifier in self._models: return self._models[modelIdentifier] else: message = "Application - getModel() - " \ "Model with identifier {} does not exist." \ .format(modelIdentifier) raise Exception(message) # # Services # def addService(self, moduleName, serviceName, service): """ Add a service instance to the application service pool. :param moduleName: <str> module name in which the service is located :param serviceName: <str> service name :param service: <object> service instance :return: <void> """ serviceIdentifier = "{}.{}".format(moduleName, serviceName) if serviceIdentifier not in self._services: self._services[serviceIdentifier] = service else: message = "Application - addService() - " \ "A service with the identifier {} already exists." \ .format(serviceIdentifier) raise Exception(message) def getService(self, serviceIdentifier): """ Return the requested service instance. :param serviceIdentifier: <str> service identifier :return: <object> service instance """ if serviceIdentifier in self._services: return self._services[serviceIdentifier] else: message = "Application - getService() - " \ "Service with identifier {} does not exist." \ .format(serviceIdentifier) raise Exception(message) def start(self): """ Start the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStart) def stop(self): """ Stop the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStop)
Nixiware/viper
nx/viper/application.py
Application.addService
python
def addService(self, moduleName, serviceName, service): serviceIdentifier = "{}.{}".format(moduleName, serviceName) if serviceIdentifier not in self._services: self._services[serviceIdentifier] = service else: message = "Application - addService() - " \ "A service with the identifier {} already exists." \ .format(serviceIdentifier) raise Exception(message)
Add a service instance to the application service pool. :param moduleName: <str> module name in which the service is located :param serviceName: <str> service name :param service: <object> service instance :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L225-L241
null
class Application: """ Viper application Core component, handles the loading of configuration, instances all the modules and their services and models. """ # # Events # eventDispatcher = EventDispatcher() kEventApplicationStart = "//event/applicationStart" kEventApplicationStop = "//event/applicationStop" def __init__(self): self.requestDispatcher = Dispatcher(self) self.config = self._getConfiguration() self._interfaces = self._getInterfaces() self._models = {} self._services = {} self._loadViperServices() self._modules = self._getModules() # # Configuration # def _getConfiguration(self): """ Load application configuration files. :return: <dict> """ configDirectoryPath = os.path.join("application", "config") config = Config(configDirectoryPath) configData = config.getData() # setting application parameters reactor.suggestThreadPoolSize( int(configData["performance"]["threadPoolSize"]) ) return configData # # Interfaces # def _getInterfaces(self): """ Load application communication interfaces. :return: <dict> """ interfaces = {} interfacesPath = os.path.join("application", "interface") interfaceList = os.listdir(interfacesPath) for file in interfaceList: interfaceDirectoryPath = os.path.join(interfacesPath, file) if not os.path.isdir(interfaceDirectoryPath) or file.startswith("__") or file.startswith("."): continue interfaceName = ntpath.basename(interfaceDirectoryPath) interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + ".py" if not os.path.isfile(interfacePath): continue # importing interface interfaceSpec = importlib.util.spec_from_file_location( interfaceName, interfacePath ) interface = importlib.util.module_from_spec(interfaceSpec) interfaceSpec.loader.exec_module(interface) # checking if there is an interface in the file if hasattr(interface, "Service"): # initializing interface interfaceInstance = interface.Service(self) interfaces[interfaceName] = interfaceInstance return interfaces def getInterfaces(self): """ Return loaded communication interfaces. :return: <dict> """ return self._interfaces # # Modules # def _getModules(self): """ Import and load application modules. :return: <dict> """ modules = {} modulesPath = os.path.join("application", "module") moduleList = os.listdir(modulesPath) for moduleName in moduleList: modulePath = os.path.join(modulesPath, moduleName, "module.py") if not os.path.isfile(modulePath): continue # importing module moduleSpec = importlib.util.spec_from_file_location( moduleName, modulePath ) module = importlib.util.module_from_spec(moduleSpec) moduleSpec.loader.exec_module(module) # initializing module moduleInstance = module.Module(self) modules[moduleName] = moduleInstance return modules def isModuleLoaded(self, moduleName): """ Verify if a module is loaded. :param moduleName: <str> module name :return: <bool> True if loaded, False otherwise """ if moduleName in self._modules: return True return False # # Models # def addModel(self, moduleName, modelName, model): """ Add a model instance to the application model pool. :param moduleName: <str> module name in which the model is located :param modelName: <str> model name :param model: <object> model instance :return: <void> """ modelIdentifier = "{}.{}".format(moduleName, modelName) if modelIdentifier not in self._models: self._models[modelIdentifier] = model else: message = "Application - addModel() - " \ "A model with the identifier {} already exists." \ .format(modelIdentifier) raise Exception(message) def getModel(self, modelIdentifier): """ Return the requested model. :param modelIdentifier: <str> model identifier :return: <object> model instance """ if modelIdentifier in self._models: return self._models[modelIdentifier] else: message = "Application - getModel() - " \ "Model with identifier {} does not exist." \ .format(modelIdentifier) raise Exception(message) # # Services # def _loadViperServices(self): """ Load application bundled services. :return: <void> """ servicesPath = os.path.join( os.path.dirname(os.path.realpath(__file__)), "service" ) for serviceFile in os.listdir(servicesPath): if serviceFile.startswith("__") or serviceFile.startswith("."): continue serviceName = serviceFile.replace(".py", "") servicePath = os.path.join( servicesPath, serviceFile ) if not os.path.isfile(servicePath): continue # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # initializing service serviceInstance = service.Service(self) self.addService("viper", serviceName, serviceInstance) def getService(self, serviceIdentifier): """ Return the requested service instance. :param serviceIdentifier: <str> service identifier :return: <object> service instance """ if serviceIdentifier in self._services: return self._services[serviceIdentifier] else: message = "Application - getService() - " \ "Service with identifier {} does not exist." \ .format(serviceIdentifier) raise Exception(message) def start(self): """ Start the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStart) def stop(self): """ Stop the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStop)
Nixiware/viper
nx/viper/application.py
Application.getService
python
def getService(self, serviceIdentifier): if serviceIdentifier in self._services: return self._services[serviceIdentifier] else: message = "Application - getService() - " \ "Service with identifier {} does not exist." \ .format(serviceIdentifier) raise Exception(message)
Return the requested service instance. :param serviceIdentifier: <str> service identifier :return: <object> service instance
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L243-L256
null
class Application: """ Viper application Core component, handles the loading of configuration, instances all the modules and their services and models. """ # # Events # eventDispatcher = EventDispatcher() kEventApplicationStart = "//event/applicationStart" kEventApplicationStop = "//event/applicationStop" def __init__(self): self.requestDispatcher = Dispatcher(self) self.config = self._getConfiguration() self._interfaces = self._getInterfaces() self._models = {} self._services = {} self._loadViperServices() self._modules = self._getModules() # # Configuration # def _getConfiguration(self): """ Load application configuration files. :return: <dict> """ configDirectoryPath = os.path.join("application", "config") config = Config(configDirectoryPath) configData = config.getData() # setting application parameters reactor.suggestThreadPoolSize( int(configData["performance"]["threadPoolSize"]) ) return configData # # Interfaces # def _getInterfaces(self): """ Load application communication interfaces. :return: <dict> """ interfaces = {} interfacesPath = os.path.join("application", "interface") interfaceList = os.listdir(interfacesPath) for file in interfaceList: interfaceDirectoryPath = os.path.join(interfacesPath, file) if not os.path.isdir(interfaceDirectoryPath) or file.startswith("__") or file.startswith("."): continue interfaceName = ntpath.basename(interfaceDirectoryPath) interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + ".py" if not os.path.isfile(interfacePath): continue # importing interface interfaceSpec = importlib.util.spec_from_file_location( interfaceName, interfacePath ) interface = importlib.util.module_from_spec(interfaceSpec) interfaceSpec.loader.exec_module(interface) # checking if there is an interface in the file if hasattr(interface, "Service"): # initializing interface interfaceInstance = interface.Service(self) interfaces[interfaceName] = interfaceInstance return interfaces def getInterfaces(self): """ Return loaded communication interfaces. :return: <dict> """ return self._interfaces # # Modules # def _getModules(self): """ Import and load application modules. :return: <dict> """ modules = {} modulesPath = os.path.join("application", "module") moduleList = os.listdir(modulesPath) for moduleName in moduleList: modulePath = os.path.join(modulesPath, moduleName, "module.py") if not os.path.isfile(modulePath): continue # importing module moduleSpec = importlib.util.spec_from_file_location( moduleName, modulePath ) module = importlib.util.module_from_spec(moduleSpec) moduleSpec.loader.exec_module(module) # initializing module moduleInstance = module.Module(self) modules[moduleName] = moduleInstance return modules def isModuleLoaded(self, moduleName): """ Verify if a module is loaded. :param moduleName: <str> module name :return: <bool> True if loaded, False otherwise """ if moduleName in self._modules: return True return False # # Models # def addModel(self, moduleName, modelName, model): """ Add a model instance to the application model pool. :param moduleName: <str> module name in which the model is located :param modelName: <str> model name :param model: <object> model instance :return: <void> """ modelIdentifier = "{}.{}".format(moduleName, modelName) if modelIdentifier not in self._models: self._models[modelIdentifier] = model else: message = "Application - addModel() - " \ "A model with the identifier {} already exists." \ .format(modelIdentifier) raise Exception(message) def getModel(self, modelIdentifier): """ Return the requested model. :param modelIdentifier: <str> model identifier :return: <object> model instance """ if modelIdentifier in self._models: return self._models[modelIdentifier] else: message = "Application - getModel() - " \ "Model with identifier {} does not exist." \ .format(modelIdentifier) raise Exception(message) # # Services # def _loadViperServices(self): """ Load application bundled services. :return: <void> """ servicesPath = os.path.join( os.path.dirname(os.path.realpath(__file__)), "service" ) for serviceFile in os.listdir(servicesPath): if serviceFile.startswith("__") or serviceFile.startswith("."): continue serviceName = serviceFile.replace(".py", "") servicePath = os.path.join( servicesPath, serviceFile ) if not os.path.isfile(servicePath): continue # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # initializing service serviceInstance = service.Service(self) self.addService("viper", serviceName, serviceInstance) def addService(self, moduleName, serviceName, service): """ Add a service instance to the application service pool. :param moduleName: <str> module name in which the service is located :param serviceName: <str> service name :param service: <object> service instance :return: <void> """ serviceIdentifier = "{}.{}".format(moduleName, serviceName) if serviceIdentifier not in self._services: self._services[serviceIdentifier] = service else: message = "Application - addService() - " \ "A service with the identifier {} already exists." \ .format(serviceIdentifier) raise Exception(message) def start(self): """ Start the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStart) def stop(self): """ Stop the application. :return: <void> """ self.eventDispatcher.dispatch(None, self.kEventApplicationStop)
Nixiware/viper
nx/viper/module.py
Module._loadConfiguration
python
def _loadConfiguration(self): configPath = os.path.join(self.path, "config") if not os.path.isdir(configPath): return config = Config(configPath) Config.mergeDictionaries(config.getData(), self.application.config)
Load module configuration files. :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/module.py#L24-L36
null
class Module: """ Viper module Container for models and services together with their configuration. """ def __init__(self, moduleName, modulePath, application): self.name = moduleName self.path = os.path.dirname(os.path.realpath(modulePath)) self.application = application self._loadConfiguration() self._loadModels() self._loadServices() def _loadModels(self): """ Load module models. :return: <void> """ modelsPath = os.path.join(self.path, "model") if not os.path.isdir(modelsPath): return for modelFile in os.listdir(modelsPath): modelName = modelFile.replace(".py", "") modelPath = os.path.join( self.path, "model", modelFile ) if not os.path.isfile(modelPath): continue # importing model modelSpec = importlib.util.spec_from_file_location( modelName, modelPath ) model = importlib.util.module_from_spec(modelSpec) modelSpec.loader.exec_module(model) # initializing model modelInstance = model.Model(self.application) self.application.addModel(self.name, modelName, modelInstance) def _loadServices(self): """ Load module services. :return: <void> """ servicesPath = os.path.join(self.path, "service") if not os.path.isdir(servicesPath): return self._scanDirectoryForServices(servicesPath) def _scanDirectoryForServices(self, directoryPath): """ Scan a directory looking for service files. If another directory is found (excluding any python bytecode cache), the method recursively calls itself on that directory. If a .py file is found, a quiet attempt to load the service from it is performed. :param: <str> path to look for services :return: <void> """ # checking if path is actually a directory if not os.path.isdir(directoryPath): return for item in os.listdir(directoryPath): itemPath = os.path.join( directoryPath, item ) if os.path.isdir(itemPath) and not item.startswith("__") and not item.startswith("."): self._scanDirectoryForServices(itemPath) continue if os.path.isfile(itemPath) and itemPath.lower().endswith((".py",)): self._loadService(itemPath) continue def _loadService(self, servicePath): """ Check if an application service can be found at the specified path. If found, instantiate it and add it to the application service pool. :param: <str> service file path :return: <void> """ serviceName = ntpath.basename(servicePath).replace(".py", "") # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # checking if there is a service in the file if hasattr(service, "Service"): # instantiate the service serviceInstance = service.Service(self.application) self.application.addService( self.name, serviceName, serviceInstance )
Nixiware/viper
nx/viper/module.py
Module._loadModels
python
def _loadModels(self): modelsPath = os.path.join(self.path, "model") if not os.path.isdir(modelsPath): return for modelFile in os.listdir(modelsPath): modelName = modelFile.replace(".py", "") modelPath = os.path.join( self.path, "model", modelFile ) if not os.path.isfile(modelPath): continue # importing model modelSpec = importlib.util.spec_from_file_location( modelName, modelPath ) model = importlib.util.module_from_spec(modelSpec) modelSpec.loader.exec_module(model) # initializing model modelInstance = model.Model(self.application) self.application.addModel(self.name, modelName, modelInstance)
Load module models. :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/module.py#L38-L67
null
class Module: """ Viper module Container for models and services together with their configuration. """ def __init__(self, moduleName, modulePath, application): self.name = moduleName self.path = os.path.dirname(os.path.realpath(modulePath)) self.application = application self._loadConfiguration() self._loadModels() self._loadServices() def _loadConfiguration(self): """ Load module configuration files. :return: <void> """ configPath = os.path.join(self.path, "config") if not os.path.isdir(configPath): return config = Config(configPath) Config.mergeDictionaries(config.getData(), self.application.config) def _loadServices(self): """ Load module services. :return: <void> """ servicesPath = os.path.join(self.path, "service") if not os.path.isdir(servicesPath): return self._scanDirectoryForServices(servicesPath) def _scanDirectoryForServices(self, directoryPath): """ Scan a directory looking for service files. If another directory is found (excluding any python bytecode cache), the method recursively calls itself on that directory. If a .py file is found, a quiet attempt to load the service from it is performed. :param: <str> path to look for services :return: <void> """ # checking if path is actually a directory if not os.path.isdir(directoryPath): return for item in os.listdir(directoryPath): itemPath = os.path.join( directoryPath, item ) if os.path.isdir(itemPath) and not item.startswith("__") and not item.startswith("."): self._scanDirectoryForServices(itemPath) continue if os.path.isfile(itemPath) and itemPath.lower().endswith((".py",)): self._loadService(itemPath) continue def _loadService(self, servicePath): """ Check if an application service can be found at the specified path. If found, instantiate it and add it to the application service pool. :param: <str> service file path :return: <void> """ serviceName = ntpath.basename(servicePath).replace(".py", "") # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # checking if there is a service in the file if hasattr(service, "Service"): # instantiate the service serviceInstance = service.Service(self.application) self.application.addService( self.name, serviceName, serviceInstance )
Nixiware/viper
nx/viper/module.py
Module._loadServices
python
def _loadServices(self): servicesPath = os.path.join(self.path, "service") if not os.path.isdir(servicesPath): return self._scanDirectoryForServices(servicesPath)
Load module services. :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/module.py#L69-L79
[ "def _scanDirectoryForServices(self, directoryPath):\n \"\"\"\n Scan a directory looking for service files.\n If another directory is found (excluding any python bytecode cache), the method recursively calls itself on\n that directory.\n If a .py file is found, a quiet attempt to load the service fro...
class Module: """ Viper module Container for models and services together with their configuration. """ def __init__(self, moduleName, modulePath, application): self.name = moduleName self.path = os.path.dirname(os.path.realpath(modulePath)) self.application = application self._loadConfiguration() self._loadModels() self._loadServices() def _loadConfiguration(self): """ Load module configuration files. :return: <void> """ configPath = os.path.join(self.path, "config") if not os.path.isdir(configPath): return config = Config(configPath) Config.mergeDictionaries(config.getData(), self.application.config) def _loadModels(self): """ Load module models. :return: <void> """ modelsPath = os.path.join(self.path, "model") if not os.path.isdir(modelsPath): return for modelFile in os.listdir(modelsPath): modelName = modelFile.replace(".py", "") modelPath = os.path.join( self.path, "model", modelFile ) if not os.path.isfile(modelPath): continue # importing model modelSpec = importlib.util.spec_from_file_location( modelName, modelPath ) model = importlib.util.module_from_spec(modelSpec) modelSpec.loader.exec_module(model) # initializing model modelInstance = model.Model(self.application) self.application.addModel(self.name, modelName, modelInstance) def _scanDirectoryForServices(self, directoryPath): """ Scan a directory looking for service files. If another directory is found (excluding any python bytecode cache), the method recursively calls itself on that directory. If a .py file is found, a quiet attempt to load the service from it is performed. :param: <str> path to look for services :return: <void> """ # checking if path is actually a directory if not os.path.isdir(directoryPath): return for item in os.listdir(directoryPath): itemPath = os.path.join( directoryPath, item ) if os.path.isdir(itemPath) and not item.startswith("__") and not item.startswith("."): self._scanDirectoryForServices(itemPath) continue if os.path.isfile(itemPath) and itemPath.lower().endswith((".py",)): self._loadService(itemPath) continue def _loadService(self, servicePath): """ Check if an application service can be found at the specified path. If found, instantiate it and add it to the application service pool. :param: <str> service file path :return: <void> """ serviceName = ntpath.basename(servicePath).replace(".py", "") # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # checking if there is a service in the file if hasattr(service, "Service"): # instantiate the service serviceInstance = service.Service(self.application) self.application.addService( self.name, serviceName, serviceInstance )
Nixiware/viper
nx/viper/module.py
Module._scanDirectoryForServices
python
def _scanDirectoryForServices(self, directoryPath): # checking if path is actually a directory if not os.path.isdir(directoryPath): return for item in os.listdir(directoryPath): itemPath = os.path.join( directoryPath, item ) if os.path.isdir(itemPath) and not item.startswith("__") and not item.startswith("."): self._scanDirectoryForServices(itemPath) continue if os.path.isfile(itemPath) and itemPath.lower().endswith((".py",)): self._loadService(itemPath) continue
Scan a directory looking for service files. If another directory is found (excluding any python bytecode cache), the method recursively calls itself on that directory. If a .py file is found, a quiet attempt to load the service from it is performed. :param: <str> path to look for services :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/module.py#L81-L106
null
class Module: """ Viper module Container for models and services together with their configuration. """ def __init__(self, moduleName, modulePath, application): self.name = moduleName self.path = os.path.dirname(os.path.realpath(modulePath)) self.application = application self._loadConfiguration() self._loadModels() self._loadServices() def _loadConfiguration(self): """ Load module configuration files. :return: <void> """ configPath = os.path.join(self.path, "config") if not os.path.isdir(configPath): return config = Config(configPath) Config.mergeDictionaries(config.getData(), self.application.config) def _loadModels(self): """ Load module models. :return: <void> """ modelsPath = os.path.join(self.path, "model") if not os.path.isdir(modelsPath): return for modelFile in os.listdir(modelsPath): modelName = modelFile.replace(".py", "") modelPath = os.path.join( self.path, "model", modelFile ) if not os.path.isfile(modelPath): continue # importing model modelSpec = importlib.util.spec_from_file_location( modelName, modelPath ) model = importlib.util.module_from_spec(modelSpec) modelSpec.loader.exec_module(model) # initializing model modelInstance = model.Model(self.application) self.application.addModel(self.name, modelName, modelInstance) def _loadServices(self): """ Load module services. :return: <void> """ servicesPath = os.path.join(self.path, "service") if not os.path.isdir(servicesPath): return self._scanDirectoryForServices(servicesPath) def _loadService(self, servicePath): """ Check if an application service can be found at the specified path. If found, instantiate it and add it to the application service pool. :param: <str> service file path :return: <void> """ serviceName = ntpath.basename(servicePath).replace(".py", "") # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # checking if there is a service in the file if hasattr(service, "Service"): # instantiate the service serviceInstance = service.Service(self.application) self.application.addService( self.name, serviceName, serviceInstance )
Nixiware/viper
nx/viper/module.py
Module._loadService
python
def _loadService(self, servicePath): serviceName = ntpath.basename(servicePath).replace(".py", "") # importing service serviceSpec = importlib.util.spec_from_file_location( serviceName, servicePath ) service = importlib.util.module_from_spec(serviceSpec) serviceSpec.loader.exec_module(service) # checking if there is a service in the file if hasattr(service, "Service"): # instantiate the service serviceInstance = service.Service(self.application) self.application.addService( self.name, serviceName, serviceInstance )
Check if an application service can be found at the specified path. If found, instantiate it and add it to the application service pool. :param: <str> service file path :return: <void>
train
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/module.py#L108-L134
null
class Module: """ Viper module Container for models and services together with their configuration. """ def __init__(self, moduleName, modulePath, application): self.name = moduleName self.path = os.path.dirname(os.path.realpath(modulePath)) self.application = application self._loadConfiguration() self._loadModels() self._loadServices() def _loadConfiguration(self): """ Load module configuration files. :return: <void> """ configPath = os.path.join(self.path, "config") if not os.path.isdir(configPath): return config = Config(configPath) Config.mergeDictionaries(config.getData(), self.application.config) def _loadModels(self): """ Load module models. :return: <void> """ modelsPath = os.path.join(self.path, "model") if not os.path.isdir(modelsPath): return for modelFile in os.listdir(modelsPath): modelName = modelFile.replace(".py", "") modelPath = os.path.join( self.path, "model", modelFile ) if not os.path.isfile(modelPath): continue # importing model modelSpec = importlib.util.spec_from_file_location( modelName, modelPath ) model = importlib.util.module_from_spec(modelSpec) modelSpec.loader.exec_module(model) # initializing model modelInstance = model.Model(self.application) self.application.addModel(self.name, modelName, modelInstance) def _loadServices(self): """ Load module services. :return: <void> """ servicesPath = os.path.join(self.path, "service") if not os.path.isdir(servicesPath): return self._scanDirectoryForServices(servicesPath) def _scanDirectoryForServices(self, directoryPath): """ Scan a directory looking for service files. If another directory is found (excluding any python bytecode cache), the method recursively calls itself on that directory. If a .py file is found, a quiet attempt to load the service from it is performed. :param: <str> path to look for services :return: <void> """ # checking if path is actually a directory if not os.path.isdir(directoryPath): return for item in os.listdir(directoryPath): itemPath = os.path.join( directoryPath, item ) if os.path.isdir(itemPath) and not item.startswith("__") and not item.startswith("."): self._scanDirectoryForServices(itemPath) continue if os.path.isfile(itemPath) and itemPath.lower().endswith((".py",)): self._loadService(itemPath) continue
kxgames/vecrec
vecrec/shapes.py
Vector.random
python
def random(magnitude=1): theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta))
Create a unit vector pointing in a random direction.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L172-L175
null
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.from_rectangle
python
def from_rectangle(box): x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y)
Create a vector randomly within the given rectangle.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L198-L202
null
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.interpolate
python
def interpolate(self, target, extent): target = cast_anything_to_vector(target) self += extent * (target - self)
Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L231-L235
[ "def cast_anything_to_vector(input):\n if isinstance(input, Vector):\n return input\n\n # If the input object is a container with two elements, use those elements \n # to construct a vector.\n\n try: return Vector(*input)\n except: pass\n\n # If the input object has x and y attributes, use ...
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.project
python
def project(self, axis): projection = self.get_projection(axis) self.assign(projection)
Project this vector onto the given axis.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L238-L241
[ "def decorator(self, *input):\n if len(input) == 1: input = input[0]\n vector = cast_anything_to_vector(input)\n return function(self, vector)\n" ]
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.dot_product
python
def dot_product(self, other): return self.x * other.x + self.y * other.y
Return the dot product of the given vectors.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L244-L246
null
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.perp_product
python
def perp_product(self, other): return self.x * other.y - self.y * other.x
Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L249-L254
null
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.rotate
python
def rotate(self, angle): x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle)
Rotate the given vector by an angle. Angle measured in radians counter-clockwise.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L256-L260
null
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.round
python
def round(self, digits=0): # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits)
Round the elements of the given vector to the given number of digits.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L262-L273
null
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.get_scaled
python
def get_scaled(self, magnitude): result = self.copy() result.scale(magnitude) return result
Return a unit vector parallel to this one.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L412-L416
[ "def copy(self):\n \"\"\" Return a copy of this vector. \"\"\"\n from copy import deepcopy\n return deepcopy(self)\n" ]
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.get_interpolated
python
def get_interpolated(self, target, extent): result = self.copy() result.interpolate(target, extent) return result
Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L418-L423
[ "def copy(self):\n \"\"\" Return a copy of this vector. \"\"\"\n from copy import deepcopy\n return deepcopy(self)\n" ]
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.get_projection
python
def get_projection(self, axis): scale = axis.dot(self) / axis.dot(axis) return axis * scale
Return the projection of this vector onto the given axis. The axis does not need to be normalized.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L426-L430
null
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.get_components
python
def get_components(self, other): tangent = self.get_projection(other) normal = self - tangent return normal, tangent
Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L433-L438
[ "def decorator(self, *input):\n if len(input) == 1: input = input[0]\n vector = cast_anything_to_vector(input)\n return function(self, vector)\n" ]
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.get_radians
python
def get_radians(self): if not self: raise NullVectorError() return math.atan2(self.y, self.x)
Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L440-L444
null
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.get_rotated
python
def get_rotated(self, angle): result = self.copy() result.rotate(angle) return result
Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L468-L472
[ "def copy(self):\n \"\"\" Return a copy of this vector. \"\"\"\n from copy import deepcopy\n return deepcopy(self)\n" ]
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.get_rounded
python
def get_rounded(self, digits): result = self.copy() result.round(digits) return result
Return a vector with the elements rounded to the given number of digits.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L474-L478
[ "def copy(self):\n \"\"\" Return a copy of this vector. \"\"\"\n from copy import deepcopy\n return deepcopy(self)\n" ]
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.x, self.y = math.cos(angle), math.sin(angle) def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Vector.set_radians
python
def set_radians(self, angle): self.x, self.y = math.cos(angle), math.sin(angle)
Set the angle that this vector makes with the x-axis.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L496-L498
null
class Vector (object): """ Represents a two-dimensional vector. In particular, this class features a number of factory methods to create vectors from various inputs and a number of overloaded operators to facilitate vector arithmetic. """ @staticmethod def null(): """ Return a null vector. """ return Vector(0, 0) @staticmethod def random(magnitude=1): """ Create a unit vector pointing in a random direction. """ theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta)) @staticmethod def from_radians(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector(math.cos(angle), math.sin(angle)) @staticmethod def from_degrees(angle): """ Create a unit vector that makes the given angle with the x-axis. """ return Vector.from_radians(angle * math.pi / 180) @staticmethod def from_tuple(coordinates): """ Create a vector from a two element tuple. """ return Vector(*coordinates) @staticmethod def from_scalar(scalar): """ Create a vector from a single scalar value. """ return Vector(scalar, scalar) @staticmethod def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y) @staticmethod def from_anything(input): return cast_anything_to_vector(input) def copy(self): """ Return a copy of this vector. """ from copy import deepcopy return deepcopy(self) @accept_anything_as_vector def assign(self, other): """ Copy the given vector into this one. """ self.x, self.y = other.tuple def normalize(self): """ Set the magnitude of this vector to unity, in place. """ try: self /= self.magnitude except ZeroDivisionError: raise NullVectorError def scale(self, magnitude): """ Set the magnitude of this vector in place. """ self.normalize() self *= magnitude def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """ target = cast_anything_to_vector(target) self += extent * (target - self) @accept_anything_as_vector def project(self, axis): """ Project this vector onto the given axis. """ projection = self.get_projection(axis) self.assign(projection) @accept_anything_as_vector def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y @accept_anything_as_vector def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to be zero and the result is returned as a scalar. """ return self.x * other.y - self.y * other.x def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """ x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle) def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """ # Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(self.x, digits) self.y = round(self.y, digits) def __init__(self, x, y): """ Construct a vector using the given coordinates. """ self.x = x self.y = y def __repr__(self): """ Return a string representation of this vector. """ return "Vector(%f, %f)" % self.tuple def __str__(self): """ Return a string representation of this vector. """ return "<%.2f, %.2f>" % self.tuple def __iter__(self): """ Iterate over this vectors coordinates. """ yield self.x yield self.y def __bool__(self): """ Return true is the vector is not degenerate. """ return self != (0, 0) __nonzero__ = __bool__ def __getitem__(self, i): """ Return the specified coordinate. """ return self.tuple[i] def __eq__(self, other): """Return true if the given object has the same coordinates as this vector.""" try: other = cast_anything_to_vector(other) return self.x == other.x and self.y == other.y except VectorCastError: return False def __ne__(self, other): """Return true if the given object has different coordinates than this vector.""" return not self.__eq__(other) def __neg__(self): """ Return a copy of this vector with the signs flipped. """ return Vector(-self.x, -self.y) def __abs__(self): """ Return the absolute value of this vector. """ return Vector(abs(self.x), abs(self.y)) # Binary Operators (fold) __add__ = _overload_left_side(operator.add) __radd__ = _overload_right_side(operator.add) __iadd__ = _overload_in_place(operator.add) __sub__ = _overload_left_side(operator.sub) __rsub__ = _overload_right_side(operator.sub) __isub__ = _overload_in_place(operator.sub) __mul__ = _overload_left_side(operator.mul, scalar_ok=True) __rmul__ = _overload_right_side(operator.mul, scalar_ok=True) __imul__ = _overload_in_place(operator.mul, scalar_ok=True) __floordiv__ = _overload_left_side(operator.floordiv, scalar_ok=True) __rfloordiv__ = _overload_right_side(operator.floordiv, scalar_ok=True) __ifloordiv__ = _overload_in_place(operator.floordiv, scalar_ok=True) __truediv__ = _overload_left_side(operator.truediv, scalar_ok=True) __rtruediv__ = _overload_right_side(operator.truediv, scalar_ok=True) __itruediv__ = _overload_in_place(operator.truediv, scalar_ok=True) __div__ = __truediv__ __rdiv__ = __rtruediv__ __idiv__ = __itruediv__ __mod__ = _overload_left_side(operator.mod, scalar_ok=True) __rmod__ = _overload_right_side(operator.mod, scalar_ok=True) __imod__ = _overload_in_place(operator.mod, scalar_ok=True) __pow__ = _overload_left_side(operator.pow, scalar_ok=True) __rpow__ = _overload_right_side(operator.pow, scalar_ok=True) __ipow__ = _overload_in_place(operator.pow, scalar_ok=True) def get_x(self): """ Get the x coordinate of this vector. """ return self.x def get_y(self): """ Get the y coordinate of this vector. """ return self.y def get_xy(self): """ Return the vector as a tuple. """ return self.x, self.y def get_tuple(self): """ Return the vector as a tuple. """ return self.x, self.y def get_magnitude(self): """ Calculate the length of this vector. """ return math.sqrt(self.magnitude_squared) def get_magnitude_squared(self): """ Calculate the square of the length of this vector. This is slightly more efficient that finding the real length. """ return self.x**2 + self.y**2 @accept_anything_as_vector def get_distance(self, other): """ Return the Euclidean distance between the two input vectors. """ return (other - self).magnitude @accept_anything_as_vector def get_manhattan(self, other): """ Return the Manhattan distance between the two input vectors. """ return sum(abs(other - self)) def get_unit(self): """ Return a unit vector parallel to this one. """ result = self.copy() result.normalize() return result def get_orthogonal(self): """ Return a vector that is orthogonal to this one. The resulting vector is not normalized. """ return Vector(-self.y, self.x) def get_orthonormal(self): """ Return a vector that is orthogonal to this one and that has been normalized. """ return self.orthogonal.unit def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """ result = self.copy() result.scale(magnitude) return result def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result @accept_anything_as_vector def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """ scale = axis.dot(self) / axis.dot(axis) return axis * scale @accept_anything_as_vector def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """ if not self: raise NullVectorError() return math.atan2(self.y, self.x) def get_positive_radians(self): """ Return the positive angle between this vector and the positive x-axis measured in radians. """ return (2 * math.pi + self.get_radians()) % (2 * math.pi) def get_degrees(self): """ Return the angle between this vector and the positive x-axis measured in degrees. """ return self.radians * 180 / math.pi @accept_anything_as_vector def get_radians_to(self, other): """ Return the angle between the two given vectors in radians. If either of the inputs are null vectors, an exception is thrown. """ return other.radians - self.radians @accept_anything_as_vector def get_degrees_to(self, other): """ Return the angle between the two given vectors in degrees. If either of the inputs are null vectors, an exception is thrown. """ return other.degrees - self.degrees def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result def set_x(self, x): """ Set the x coordinate of this vector. """ self.x = x def set_y(self, y): """ Set the y coordinate of this vector. """ self.y = y def set_xy(self, xy): """ Set the x and y coordinates of this vector from a tuple. """ self.x, self.y = xy def set_tuple(self, coordinates): """ Set the x and y coordinates of this vector. """ self.x, self.y = coordinates def set_degrees(self, angle): """ Set the angle that this vector makes with the x-axis. """ self.set_radians(angle * math.pi / 180) # Aliases (fold) dot = dot_product perp = perp_product # Properties (fold) xy = property(get_xy, set_xy) tuple = property(get_tuple, set_tuple) magnitude = property(get_magnitude, scale) magnitude_squared = property(get_magnitude_squared) unit = property(get_unit) orthogonal = property(get_orthogonal) orthonormal = property(get_orthonormal) radians = property(get_radians, set_radians) degrees = property(get_degrees, set_degrees)
kxgames/vecrec
vecrec/shapes.py
Rectangle.grow
python
def grow(self, *padding): try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom -= bpad self._left -= lpad self._width += lpad + rpad self._height += tpad + bpad return self
Grow this rectangle by the given padding on all sides.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L676-L687
null
class Rectangle (Shape): def __init__(self, left, bottom, width, height): self._left = left self._bottom = bottom self._width = width self._height = height def __repr__(self): return "Rectangle(%f, %f, %f, %f)" % self.tuple def __str__(self): return '<Rect bottom={0} left={1} width={2} height={3}>'.format( self.bottom, self.left, self.width, self.height) def __eq__(self, other): try: return (self.bottom == other.bottom and self.left == other.left and self.width == other.width and self.height == other.height) except AttributeError: return False @accept_anything_as_vector def __add__(self, vector): result = self.copy() result.displace(vector) return result @accept_anything_as_vector def __iadd__(self, vector): self.displace(vector) return self @accept_anything_as_vector def __sub__(self, vector): result = self.copy() result.displace(-vector) return result @accept_anything_as_vector def __isub__(self, vector): self.displace(-vector) return self def __contains__(self, other): return self.contains(other) @staticmethod def null(): """ Return a rectangle with everything set to zero. It is located at the origin and has no area. """ return Rectangle(0, 0, 0, 0) @staticmethod def from_size(width, height): return Rectangle(0, 0, width, height) @staticmethod def from_width(width, ratio=1/golden_ratio): return Rectangle.from_size(width, ratio * width) @staticmethod def from_height(height, ratio=golden_ratio): return Rectangle.from_size(ratio * height, height) @staticmethod def from_square(size): return Rectangle.from_size(size, size) @staticmethod def from_dimensions(left, bottom, width, height): return Rectangle(left, bottom, width, height) @staticmethod def from_sides(left, top, right, bottom): width = right - left; height = top - bottom return Rectangle.from_dimensions(left, bottom, width, height) @staticmethod def from_corners(first, second): first = cast_anything_to_vector(first) second = cast_anything_to_vector(second) left = min(first.x, second.x); top = max(first.y, second.y) right = max(first.x, second.x); bottom = min(first.y, second.y) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_bottom_left(position, width, height): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, width, height) @staticmethod def from_center(position, width, height): position = cast_anything_to_vector(position) - (width/2, height/2) return Rectangle(position.x, position.y, width, height) @staticmethod def from_vector(position): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, 0, 0) @staticmethod def from_points(*points): left = min(cast_anything_to_vector(p).x for p in points) top = max(cast_anything_to_vector(p).y for p in points) right = max(cast_anything_to_vector(p).x for p in points) bottom = min(cast_anything_to_vector(p).y for p in points) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_shape(shape): bottom, left = shape.bottom, shape.left width, height = shape.width, shape.height return Rectangle(left, bottom, width, height) @staticmethod def from_surface(surface): width, height = surface.get_size() return Rectangle.from_size(width, height) @staticmethod def from_pyglet_window(window): return Rectangle.from_size(window.width, window.height) @staticmethod def from_pyglet_image(image): return Rectangle.from_size(image.width, image.height) @staticmethod def from_union(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = min(x.left for x in rectangles) top = max(x.top for x in rectangles) right = max(x.right for x in rectangles) bottom = min(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_intersection(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = max(x.left for x in rectangles) top = min(x.top for x in rectangles) right = min(x.right for x in rectangles) bottom = max(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) def shrink(self, *padding): """ Shrink this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom += bpad self._left += lpad self._width -= lpad + rpad self._height -= tpad + bpad return self @accept_anything_as_vector def displace(self, vector): """ Displace this rectangle by the given vector. """ self._bottom += vector.y self._left += vector.x return self def round(self, digits=0): """ Round the dimensions of the given rectangle to the given number of digits. """ self._left = round(self._left, digits) self._bottom = round(self._bottom, digits) self._width = round(self._width, digits) self._height = round(self._height, digits) def set(self, shape): """ Fill this rectangle with the dimensions of the given shape. """ self.bottom, self.left = shape.bottom, shape.left self.width, self.height = shape.width, shape.height return self def copy(self): """ Return a copy of this rectangle. """ from copy import deepcopy return deepcopy(self) @accept_shape_as_rectangle def inside(self, other): """ Return true if this rectangle is inside the given shape. """ return ( self.left >= other.left and self.right <= other.right and self.top <= other.top and self.bottom >= other.bottom) @accept_anything_as_rectangle def outside(self, other): """ Return true if this rectangle is outside the given shape. """ return not self.touching(other) @accept_anything_as_rectangle def touching(self, other): """ Return true if this rectangle is touching the given shape. """ if self.top < other.bottom: return False if self.bottom > other.top: return False if self.left > other.right: return False if self.right < other.left: return False return True @accept_anything_as_rectangle def contains(self, other): """ Return true if the given shape is inside this rectangle. """ return (self.left <= other.left and self.right >= other.right and self.top >= other.top and self.bottom <= other.bottom) @accept_anything_as_rectangle def align_left(self, target): self.left = target.left @accept_anything_as_rectangle def align_center_x(self, target): self.center_x = target.center_x @accept_anything_as_rectangle def align_right(self, target): self.right = target.right @accept_anything_as_rectangle def align_top(self, target): self.top = target.top @accept_anything_as_rectangle def align_center_y(self, target): self.center_y = target.center_y @accept_anything_as_rectangle def align_bottom(self, target): self.bottom = target.bottom def get_left(self): return self._left def get_center_x(self): return self._left + self._width / 2 def get_right(self): return self._left + self._width def get_top(self): return self._bottom + self._height def get_center_y(self): return self._bottom + self._height / 2 def get_bottom(self): return self._bottom def get_area(self): return self._width * self._height def get_width(self): return self._width def get_height(self): return self._height def get_half_width(self): return self._width / 2 def get_half_height(self): return self._height / 2 def get_size(self): return Vector(self._width, self._height) def get_size_as_int(self): from math import ceil return Vector(int(ceil(self._width)), int(ceil(self._height))) def get_top_left(self): return Vector(self.left, self.top) def get_top_center(self): return Vector(self.center_x, self.top) def get_top_right(self): return Vector(self.right, self.top) def get_center_left(self): return Vector(self.left, self.center_y) def get_center(self): return Vector(self.center_x, self.center_y) def get_center_right(self): return Vector(self.right, self.center_y) def get_bottom_left(self): return Vector(self.left, self.bottom) def get_bottom_center(self): return Vector(self.center_x, self.bottom) def get_bottom_right(self): return Vector(self.right, self.bottom) def get_vertices(self): return self.top_left, self.top_right, self.bottom_right, self.bottom_left def get_dimensions(self): return (self._left, self._bottom), (self._width, self._height) def get_tuple(self): return self._left, self._bottom, self._width, self._height def get_union(self, *rectangles): return Rectangle.from_union(self, *rectangles) def get_intersection(self, *rectangles): return Rectangle.from_intersection(self, *rectangles) def get_grown(self, padding): result = self.copy() result.grow(padding) return result def get_shrunk(self, padding): result = self.copy() result.shrink(padding) return result def get_rounded(self, digits=0): result = self.copy() result.round(digits) return result def set_left(self, x): self._left = x def set_center_x(self, x): self._left = x - self._width / 2 def set_right(self, x): self._left = x - self._width def set_top(self, y): self._bottom = y - self._height def set_center_y(self, y): self._bottom = y - self._height / 2 def set_bottom(self, y): self._bottom = y def set_width(self, width): self._width = width def set_height(self, height): self._height = height def set_size(self, width, height): self._width = width self._height = height @accept_anything_as_vector def set_top_left(self, point): self.top = point[1] self.left = point[0] @accept_anything_as_vector def set_top_center(self, point): self.top = point[1] self.center_x = point[0] @accept_anything_as_vector def set_top_right(self, point): self.top = point[1] self.right = point[0] @accept_anything_as_vector def set_center_left(self, point): self.center_y = point[1] self.left = point[0] @accept_anything_as_vector def set_center(self, point): self.center_y = point[1] self.center_x = point[0] @accept_anything_as_vector def set_center_right(self, point): self.center_y = point[1] self.right = point[0] @accept_anything_as_vector def set_bottom_left(self, point): self.bottom = point[1] self.left = point[0] @accept_anything_as_vector def set_bottom_center(self, point): self.bottom = point[1] self.center_x = point[0] @accept_anything_as_vector def set_bottom_right(self, point): self.bottom = point[1] self.right = point[0] def set_vertices(self, vertices): self.top_left = vertices[0] self.top_right = vertices[1] self.bottom_right = vertices[2] self.bottom_left = vertices[3] # Properties (fold) left = property(get_left, set_left) center_x = property(get_center_x, set_center_x) right = property(get_right, set_right) top = property(get_top, set_top) center_y = property(get_center_y, set_center_y) bottom = property(get_bottom, set_bottom) area = property(get_area) width = property(get_width, set_width) height = property(get_height, set_height) half_width = property(get_half_width) half_height = property(get_half_height) size = property(get_size, set_size) size_as_int = property(get_size_as_int) top_left = property(get_top_left, set_top_left) top_center = property(get_top_center, set_top_center) top_right = property(get_top_right, set_top_right) center_left = property(get_center_left, set_center_left) center = property(get_center, set_center) center_right = property(get_center_right, set_center_right) bottom_left = property(get_bottom_left, set_bottom_left) bottom_center = property(get_bottom_center, set_bottom_center) bottom_right = property(get_bottom_right, set_bottom_right) vertices = property(get_vertices, set_vertices) dimensions = property(get_dimensions) tuple = property(get_tuple)
kxgames/vecrec
vecrec/shapes.py
Rectangle.displace
python
def displace(self, vector): self._bottom += vector.y self._left += vector.x return self
Displace this rectangle by the given vector.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L703-L707
null
class Rectangle (Shape): def __init__(self, left, bottom, width, height): self._left = left self._bottom = bottom self._width = width self._height = height def __repr__(self): return "Rectangle(%f, %f, %f, %f)" % self.tuple def __str__(self): return '<Rect bottom={0} left={1} width={2} height={3}>'.format( self.bottom, self.left, self.width, self.height) def __eq__(self, other): try: return (self.bottom == other.bottom and self.left == other.left and self.width == other.width and self.height == other.height) except AttributeError: return False @accept_anything_as_vector def __add__(self, vector): result = self.copy() result.displace(vector) return result @accept_anything_as_vector def __iadd__(self, vector): self.displace(vector) return self @accept_anything_as_vector def __sub__(self, vector): result = self.copy() result.displace(-vector) return result @accept_anything_as_vector def __isub__(self, vector): self.displace(-vector) return self def __contains__(self, other): return self.contains(other) @staticmethod def null(): """ Return a rectangle with everything set to zero. It is located at the origin and has no area. """ return Rectangle(0, 0, 0, 0) @staticmethod def from_size(width, height): return Rectangle(0, 0, width, height) @staticmethod def from_width(width, ratio=1/golden_ratio): return Rectangle.from_size(width, ratio * width) @staticmethod def from_height(height, ratio=golden_ratio): return Rectangle.from_size(ratio * height, height) @staticmethod def from_square(size): return Rectangle.from_size(size, size) @staticmethod def from_dimensions(left, bottom, width, height): return Rectangle(left, bottom, width, height) @staticmethod def from_sides(left, top, right, bottom): width = right - left; height = top - bottom return Rectangle.from_dimensions(left, bottom, width, height) @staticmethod def from_corners(first, second): first = cast_anything_to_vector(first) second = cast_anything_to_vector(second) left = min(first.x, second.x); top = max(first.y, second.y) right = max(first.x, second.x); bottom = min(first.y, second.y) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_bottom_left(position, width, height): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, width, height) @staticmethod def from_center(position, width, height): position = cast_anything_to_vector(position) - (width/2, height/2) return Rectangle(position.x, position.y, width, height) @staticmethod def from_vector(position): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, 0, 0) @staticmethod def from_points(*points): left = min(cast_anything_to_vector(p).x for p in points) top = max(cast_anything_to_vector(p).y for p in points) right = max(cast_anything_to_vector(p).x for p in points) bottom = min(cast_anything_to_vector(p).y for p in points) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_shape(shape): bottom, left = shape.bottom, shape.left width, height = shape.width, shape.height return Rectangle(left, bottom, width, height) @staticmethod def from_surface(surface): width, height = surface.get_size() return Rectangle.from_size(width, height) @staticmethod def from_pyglet_window(window): return Rectangle.from_size(window.width, window.height) @staticmethod def from_pyglet_image(image): return Rectangle.from_size(image.width, image.height) @staticmethod def from_union(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = min(x.left for x in rectangles) top = max(x.top for x in rectangles) right = max(x.right for x in rectangles) bottom = min(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_intersection(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = max(x.left for x in rectangles) top = min(x.top for x in rectangles) right = min(x.right for x in rectangles) bottom = max(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) def grow(self, *padding): """ Grow this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom -= bpad self._left -= lpad self._width += lpad + rpad self._height += tpad + bpad return self def shrink(self, *padding): """ Shrink this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom += bpad self._left += lpad self._width -= lpad + rpad self._height -= tpad + bpad return self @accept_anything_as_vector def round(self, digits=0): """ Round the dimensions of the given rectangle to the given number of digits. """ self._left = round(self._left, digits) self._bottom = round(self._bottom, digits) self._width = round(self._width, digits) self._height = round(self._height, digits) def set(self, shape): """ Fill this rectangle with the dimensions of the given shape. """ self.bottom, self.left = shape.bottom, shape.left self.width, self.height = shape.width, shape.height return self def copy(self): """ Return a copy of this rectangle. """ from copy import deepcopy return deepcopy(self) @accept_shape_as_rectangle def inside(self, other): """ Return true if this rectangle is inside the given shape. """ return ( self.left >= other.left and self.right <= other.right and self.top <= other.top and self.bottom >= other.bottom) @accept_anything_as_rectangle def outside(self, other): """ Return true if this rectangle is outside the given shape. """ return not self.touching(other) @accept_anything_as_rectangle def touching(self, other): """ Return true if this rectangle is touching the given shape. """ if self.top < other.bottom: return False if self.bottom > other.top: return False if self.left > other.right: return False if self.right < other.left: return False return True @accept_anything_as_rectangle def contains(self, other): """ Return true if the given shape is inside this rectangle. """ return (self.left <= other.left and self.right >= other.right and self.top >= other.top and self.bottom <= other.bottom) @accept_anything_as_rectangle def align_left(self, target): self.left = target.left @accept_anything_as_rectangle def align_center_x(self, target): self.center_x = target.center_x @accept_anything_as_rectangle def align_right(self, target): self.right = target.right @accept_anything_as_rectangle def align_top(self, target): self.top = target.top @accept_anything_as_rectangle def align_center_y(self, target): self.center_y = target.center_y @accept_anything_as_rectangle def align_bottom(self, target): self.bottom = target.bottom def get_left(self): return self._left def get_center_x(self): return self._left + self._width / 2 def get_right(self): return self._left + self._width def get_top(self): return self._bottom + self._height def get_center_y(self): return self._bottom + self._height / 2 def get_bottom(self): return self._bottom def get_area(self): return self._width * self._height def get_width(self): return self._width def get_height(self): return self._height def get_half_width(self): return self._width / 2 def get_half_height(self): return self._height / 2 def get_size(self): return Vector(self._width, self._height) def get_size_as_int(self): from math import ceil return Vector(int(ceil(self._width)), int(ceil(self._height))) def get_top_left(self): return Vector(self.left, self.top) def get_top_center(self): return Vector(self.center_x, self.top) def get_top_right(self): return Vector(self.right, self.top) def get_center_left(self): return Vector(self.left, self.center_y) def get_center(self): return Vector(self.center_x, self.center_y) def get_center_right(self): return Vector(self.right, self.center_y) def get_bottom_left(self): return Vector(self.left, self.bottom) def get_bottom_center(self): return Vector(self.center_x, self.bottom) def get_bottom_right(self): return Vector(self.right, self.bottom) def get_vertices(self): return self.top_left, self.top_right, self.bottom_right, self.bottom_left def get_dimensions(self): return (self._left, self._bottom), (self._width, self._height) def get_tuple(self): return self._left, self._bottom, self._width, self._height def get_union(self, *rectangles): return Rectangle.from_union(self, *rectangles) def get_intersection(self, *rectangles): return Rectangle.from_intersection(self, *rectangles) def get_grown(self, padding): result = self.copy() result.grow(padding) return result def get_shrunk(self, padding): result = self.copy() result.shrink(padding) return result def get_rounded(self, digits=0): result = self.copy() result.round(digits) return result def set_left(self, x): self._left = x def set_center_x(self, x): self._left = x - self._width / 2 def set_right(self, x): self._left = x - self._width def set_top(self, y): self._bottom = y - self._height def set_center_y(self, y): self._bottom = y - self._height / 2 def set_bottom(self, y): self._bottom = y def set_width(self, width): self._width = width def set_height(self, height): self._height = height def set_size(self, width, height): self._width = width self._height = height @accept_anything_as_vector def set_top_left(self, point): self.top = point[1] self.left = point[0] @accept_anything_as_vector def set_top_center(self, point): self.top = point[1] self.center_x = point[0] @accept_anything_as_vector def set_top_right(self, point): self.top = point[1] self.right = point[0] @accept_anything_as_vector def set_center_left(self, point): self.center_y = point[1] self.left = point[0] @accept_anything_as_vector def set_center(self, point): self.center_y = point[1] self.center_x = point[0] @accept_anything_as_vector def set_center_right(self, point): self.center_y = point[1] self.right = point[0] @accept_anything_as_vector def set_bottom_left(self, point): self.bottom = point[1] self.left = point[0] @accept_anything_as_vector def set_bottom_center(self, point): self.bottom = point[1] self.center_x = point[0] @accept_anything_as_vector def set_bottom_right(self, point): self.bottom = point[1] self.right = point[0] def set_vertices(self, vertices): self.top_left = vertices[0] self.top_right = vertices[1] self.bottom_right = vertices[2] self.bottom_left = vertices[3] # Properties (fold) left = property(get_left, set_left) center_x = property(get_center_x, set_center_x) right = property(get_right, set_right) top = property(get_top, set_top) center_y = property(get_center_y, set_center_y) bottom = property(get_bottom, set_bottom) area = property(get_area) width = property(get_width, set_width) height = property(get_height, set_height) half_width = property(get_half_width) half_height = property(get_half_height) size = property(get_size, set_size) size_as_int = property(get_size_as_int) top_left = property(get_top_left, set_top_left) top_center = property(get_top_center, set_top_center) top_right = property(get_top_right, set_top_right) center_left = property(get_center_left, set_center_left) center = property(get_center, set_center) center_right = property(get_center_right, set_center_right) bottom_left = property(get_bottom_left, set_bottom_left) bottom_center = property(get_bottom_center, set_bottom_center) bottom_right = property(get_bottom_right, set_bottom_right) vertices = property(get_vertices, set_vertices) dimensions = property(get_dimensions) tuple = property(get_tuple)
kxgames/vecrec
vecrec/shapes.py
Rectangle.round
python
def round(self, digits=0): self._left = round(self._left, digits) self._bottom = round(self._bottom, digits) self._width = round(self._width, digits) self._height = round(self._height, digits)
Round the dimensions of the given rectangle to the given number of digits.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L709-L714
null
class Rectangle (Shape): def __init__(self, left, bottom, width, height): self._left = left self._bottom = bottom self._width = width self._height = height def __repr__(self): return "Rectangle(%f, %f, %f, %f)" % self.tuple def __str__(self): return '<Rect bottom={0} left={1} width={2} height={3}>'.format( self.bottom, self.left, self.width, self.height) def __eq__(self, other): try: return (self.bottom == other.bottom and self.left == other.left and self.width == other.width and self.height == other.height) except AttributeError: return False @accept_anything_as_vector def __add__(self, vector): result = self.copy() result.displace(vector) return result @accept_anything_as_vector def __iadd__(self, vector): self.displace(vector) return self @accept_anything_as_vector def __sub__(self, vector): result = self.copy() result.displace(-vector) return result @accept_anything_as_vector def __isub__(self, vector): self.displace(-vector) return self def __contains__(self, other): return self.contains(other) @staticmethod def null(): """ Return a rectangle with everything set to zero. It is located at the origin and has no area. """ return Rectangle(0, 0, 0, 0) @staticmethod def from_size(width, height): return Rectangle(0, 0, width, height) @staticmethod def from_width(width, ratio=1/golden_ratio): return Rectangle.from_size(width, ratio * width) @staticmethod def from_height(height, ratio=golden_ratio): return Rectangle.from_size(ratio * height, height) @staticmethod def from_square(size): return Rectangle.from_size(size, size) @staticmethod def from_dimensions(left, bottom, width, height): return Rectangle(left, bottom, width, height) @staticmethod def from_sides(left, top, right, bottom): width = right - left; height = top - bottom return Rectangle.from_dimensions(left, bottom, width, height) @staticmethod def from_corners(first, second): first = cast_anything_to_vector(first) second = cast_anything_to_vector(second) left = min(first.x, second.x); top = max(first.y, second.y) right = max(first.x, second.x); bottom = min(first.y, second.y) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_bottom_left(position, width, height): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, width, height) @staticmethod def from_center(position, width, height): position = cast_anything_to_vector(position) - (width/2, height/2) return Rectangle(position.x, position.y, width, height) @staticmethod def from_vector(position): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, 0, 0) @staticmethod def from_points(*points): left = min(cast_anything_to_vector(p).x for p in points) top = max(cast_anything_to_vector(p).y for p in points) right = max(cast_anything_to_vector(p).x for p in points) bottom = min(cast_anything_to_vector(p).y for p in points) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_shape(shape): bottom, left = shape.bottom, shape.left width, height = shape.width, shape.height return Rectangle(left, bottom, width, height) @staticmethod def from_surface(surface): width, height = surface.get_size() return Rectangle.from_size(width, height) @staticmethod def from_pyglet_window(window): return Rectangle.from_size(window.width, window.height) @staticmethod def from_pyglet_image(image): return Rectangle.from_size(image.width, image.height) @staticmethod def from_union(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = min(x.left for x in rectangles) top = max(x.top for x in rectangles) right = max(x.right for x in rectangles) bottom = min(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_intersection(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = max(x.left for x in rectangles) top = min(x.top for x in rectangles) right = min(x.right for x in rectangles) bottom = max(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) def grow(self, *padding): """ Grow this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom -= bpad self._left -= lpad self._width += lpad + rpad self._height += tpad + bpad return self def shrink(self, *padding): """ Shrink this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom += bpad self._left += lpad self._width -= lpad + rpad self._height -= tpad + bpad return self @accept_anything_as_vector def displace(self, vector): """ Displace this rectangle by the given vector. """ self._bottom += vector.y self._left += vector.x return self def set(self, shape): """ Fill this rectangle with the dimensions of the given shape. """ self.bottom, self.left = shape.bottom, shape.left self.width, self.height = shape.width, shape.height return self def copy(self): """ Return a copy of this rectangle. """ from copy import deepcopy return deepcopy(self) @accept_shape_as_rectangle def inside(self, other): """ Return true if this rectangle is inside the given shape. """ return ( self.left >= other.left and self.right <= other.right and self.top <= other.top and self.bottom >= other.bottom) @accept_anything_as_rectangle def outside(self, other): """ Return true if this rectangle is outside the given shape. """ return not self.touching(other) @accept_anything_as_rectangle def touching(self, other): """ Return true if this rectangle is touching the given shape. """ if self.top < other.bottom: return False if self.bottom > other.top: return False if self.left > other.right: return False if self.right < other.left: return False return True @accept_anything_as_rectangle def contains(self, other): """ Return true if the given shape is inside this rectangle. """ return (self.left <= other.left and self.right >= other.right and self.top >= other.top and self.bottom <= other.bottom) @accept_anything_as_rectangle def align_left(self, target): self.left = target.left @accept_anything_as_rectangle def align_center_x(self, target): self.center_x = target.center_x @accept_anything_as_rectangle def align_right(self, target): self.right = target.right @accept_anything_as_rectangle def align_top(self, target): self.top = target.top @accept_anything_as_rectangle def align_center_y(self, target): self.center_y = target.center_y @accept_anything_as_rectangle def align_bottom(self, target): self.bottom = target.bottom def get_left(self): return self._left def get_center_x(self): return self._left + self._width / 2 def get_right(self): return self._left + self._width def get_top(self): return self._bottom + self._height def get_center_y(self): return self._bottom + self._height / 2 def get_bottom(self): return self._bottom def get_area(self): return self._width * self._height def get_width(self): return self._width def get_height(self): return self._height def get_half_width(self): return self._width / 2 def get_half_height(self): return self._height / 2 def get_size(self): return Vector(self._width, self._height) def get_size_as_int(self): from math import ceil return Vector(int(ceil(self._width)), int(ceil(self._height))) def get_top_left(self): return Vector(self.left, self.top) def get_top_center(self): return Vector(self.center_x, self.top) def get_top_right(self): return Vector(self.right, self.top) def get_center_left(self): return Vector(self.left, self.center_y) def get_center(self): return Vector(self.center_x, self.center_y) def get_center_right(self): return Vector(self.right, self.center_y) def get_bottom_left(self): return Vector(self.left, self.bottom) def get_bottom_center(self): return Vector(self.center_x, self.bottom) def get_bottom_right(self): return Vector(self.right, self.bottom) def get_vertices(self): return self.top_left, self.top_right, self.bottom_right, self.bottom_left def get_dimensions(self): return (self._left, self._bottom), (self._width, self._height) def get_tuple(self): return self._left, self._bottom, self._width, self._height def get_union(self, *rectangles): return Rectangle.from_union(self, *rectangles) def get_intersection(self, *rectangles): return Rectangle.from_intersection(self, *rectangles) def get_grown(self, padding): result = self.copy() result.grow(padding) return result def get_shrunk(self, padding): result = self.copy() result.shrink(padding) return result def get_rounded(self, digits=0): result = self.copy() result.round(digits) return result def set_left(self, x): self._left = x def set_center_x(self, x): self._left = x - self._width / 2 def set_right(self, x): self._left = x - self._width def set_top(self, y): self._bottom = y - self._height def set_center_y(self, y): self._bottom = y - self._height / 2 def set_bottom(self, y): self._bottom = y def set_width(self, width): self._width = width def set_height(self, height): self._height = height def set_size(self, width, height): self._width = width self._height = height @accept_anything_as_vector def set_top_left(self, point): self.top = point[1] self.left = point[0] @accept_anything_as_vector def set_top_center(self, point): self.top = point[1] self.center_x = point[0] @accept_anything_as_vector def set_top_right(self, point): self.top = point[1] self.right = point[0] @accept_anything_as_vector def set_center_left(self, point): self.center_y = point[1] self.left = point[0] @accept_anything_as_vector def set_center(self, point): self.center_y = point[1] self.center_x = point[0] @accept_anything_as_vector def set_center_right(self, point): self.center_y = point[1] self.right = point[0] @accept_anything_as_vector def set_bottom_left(self, point): self.bottom = point[1] self.left = point[0] @accept_anything_as_vector def set_bottom_center(self, point): self.bottom = point[1] self.center_x = point[0] @accept_anything_as_vector def set_bottom_right(self, point): self.bottom = point[1] self.right = point[0] def set_vertices(self, vertices): self.top_left = vertices[0] self.top_right = vertices[1] self.bottom_right = vertices[2] self.bottom_left = vertices[3] # Properties (fold) left = property(get_left, set_left) center_x = property(get_center_x, set_center_x) right = property(get_right, set_right) top = property(get_top, set_top) center_y = property(get_center_y, set_center_y) bottom = property(get_bottom, set_bottom) area = property(get_area) width = property(get_width, set_width) height = property(get_height, set_height) half_width = property(get_half_width) half_height = property(get_half_height) size = property(get_size, set_size) size_as_int = property(get_size_as_int) top_left = property(get_top_left, set_top_left) top_center = property(get_top_center, set_top_center) top_right = property(get_top_right, set_top_right) center_left = property(get_center_left, set_center_left) center = property(get_center, set_center) center_right = property(get_center_right, set_center_right) bottom_left = property(get_bottom_left, set_bottom_left) bottom_center = property(get_bottom_center, set_bottom_center) bottom_right = property(get_bottom_right, set_bottom_right) vertices = property(get_vertices, set_vertices) dimensions = property(get_dimensions) tuple = property(get_tuple)
kxgames/vecrec
vecrec/shapes.py
Rectangle.set
python
def set(self, shape): self.bottom, self.left = shape.bottom, shape.left self.width, self.height = shape.width, shape.height return self
Fill this rectangle with the dimensions of the given shape.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L716-L720
null
class Rectangle (Shape): def __init__(self, left, bottom, width, height): self._left = left self._bottom = bottom self._width = width self._height = height def __repr__(self): return "Rectangle(%f, %f, %f, %f)" % self.tuple def __str__(self): return '<Rect bottom={0} left={1} width={2} height={3}>'.format( self.bottom, self.left, self.width, self.height) def __eq__(self, other): try: return (self.bottom == other.bottom and self.left == other.left and self.width == other.width and self.height == other.height) except AttributeError: return False @accept_anything_as_vector def __add__(self, vector): result = self.copy() result.displace(vector) return result @accept_anything_as_vector def __iadd__(self, vector): self.displace(vector) return self @accept_anything_as_vector def __sub__(self, vector): result = self.copy() result.displace(-vector) return result @accept_anything_as_vector def __isub__(self, vector): self.displace(-vector) return self def __contains__(self, other): return self.contains(other) @staticmethod def null(): """ Return a rectangle with everything set to zero. It is located at the origin and has no area. """ return Rectangle(0, 0, 0, 0) @staticmethod def from_size(width, height): return Rectangle(0, 0, width, height) @staticmethod def from_width(width, ratio=1/golden_ratio): return Rectangle.from_size(width, ratio * width) @staticmethod def from_height(height, ratio=golden_ratio): return Rectangle.from_size(ratio * height, height) @staticmethod def from_square(size): return Rectangle.from_size(size, size) @staticmethod def from_dimensions(left, bottom, width, height): return Rectangle(left, bottom, width, height) @staticmethod def from_sides(left, top, right, bottom): width = right - left; height = top - bottom return Rectangle.from_dimensions(left, bottom, width, height) @staticmethod def from_corners(first, second): first = cast_anything_to_vector(first) second = cast_anything_to_vector(second) left = min(first.x, second.x); top = max(first.y, second.y) right = max(first.x, second.x); bottom = min(first.y, second.y) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_bottom_left(position, width, height): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, width, height) @staticmethod def from_center(position, width, height): position = cast_anything_to_vector(position) - (width/2, height/2) return Rectangle(position.x, position.y, width, height) @staticmethod def from_vector(position): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, 0, 0) @staticmethod def from_points(*points): left = min(cast_anything_to_vector(p).x for p in points) top = max(cast_anything_to_vector(p).y for p in points) right = max(cast_anything_to_vector(p).x for p in points) bottom = min(cast_anything_to_vector(p).y for p in points) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_shape(shape): bottom, left = shape.bottom, shape.left width, height = shape.width, shape.height return Rectangle(left, bottom, width, height) @staticmethod def from_surface(surface): width, height = surface.get_size() return Rectangle.from_size(width, height) @staticmethod def from_pyglet_window(window): return Rectangle.from_size(window.width, window.height) @staticmethod def from_pyglet_image(image): return Rectangle.from_size(image.width, image.height) @staticmethod def from_union(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = min(x.left for x in rectangles) top = max(x.top for x in rectangles) right = max(x.right for x in rectangles) bottom = min(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_intersection(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = max(x.left for x in rectangles) top = min(x.top for x in rectangles) right = min(x.right for x in rectangles) bottom = max(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) def grow(self, *padding): """ Grow this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom -= bpad self._left -= lpad self._width += lpad + rpad self._height += tpad + bpad return self def shrink(self, *padding): """ Shrink this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom += bpad self._left += lpad self._width -= lpad + rpad self._height -= tpad + bpad return self @accept_anything_as_vector def displace(self, vector): """ Displace this rectangle by the given vector. """ self._bottom += vector.y self._left += vector.x return self def round(self, digits=0): """ Round the dimensions of the given rectangle to the given number of digits. """ self._left = round(self._left, digits) self._bottom = round(self._bottom, digits) self._width = round(self._width, digits) self._height = round(self._height, digits) def copy(self): """ Return a copy of this rectangle. """ from copy import deepcopy return deepcopy(self) @accept_shape_as_rectangle def inside(self, other): """ Return true if this rectangle is inside the given shape. """ return ( self.left >= other.left and self.right <= other.right and self.top <= other.top and self.bottom >= other.bottom) @accept_anything_as_rectangle def outside(self, other): """ Return true if this rectangle is outside the given shape. """ return not self.touching(other) @accept_anything_as_rectangle def touching(self, other): """ Return true if this rectangle is touching the given shape. """ if self.top < other.bottom: return False if self.bottom > other.top: return False if self.left > other.right: return False if self.right < other.left: return False return True @accept_anything_as_rectangle def contains(self, other): """ Return true if the given shape is inside this rectangle. """ return (self.left <= other.left and self.right >= other.right and self.top >= other.top and self.bottom <= other.bottom) @accept_anything_as_rectangle def align_left(self, target): self.left = target.left @accept_anything_as_rectangle def align_center_x(self, target): self.center_x = target.center_x @accept_anything_as_rectangle def align_right(self, target): self.right = target.right @accept_anything_as_rectangle def align_top(self, target): self.top = target.top @accept_anything_as_rectangle def align_center_y(self, target): self.center_y = target.center_y @accept_anything_as_rectangle def align_bottom(self, target): self.bottom = target.bottom def get_left(self): return self._left def get_center_x(self): return self._left + self._width / 2 def get_right(self): return self._left + self._width def get_top(self): return self._bottom + self._height def get_center_y(self): return self._bottom + self._height / 2 def get_bottom(self): return self._bottom def get_area(self): return self._width * self._height def get_width(self): return self._width def get_height(self): return self._height def get_half_width(self): return self._width / 2 def get_half_height(self): return self._height / 2 def get_size(self): return Vector(self._width, self._height) def get_size_as_int(self): from math import ceil return Vector(int(ceil(self._width)), int(ceil(self._height))) def get_top_left(self): return Vector(self.left, self.top) def get_top_center(self): return Vector(self.center_x, self.top) def get_top_right(self): return Vector(self.right, self.top) def get_center_left(self): return Vector(self.left, self.center_y) def get_center(self): return Vector(self.center_x, self.center_y) def get_center_right(self): return Vector(self.right, self.center_y) def get_bottom_left(self): return Vector(self.left, self.bottom) def get_bottom_center(self): return Vector(self.center_x, self.bottom) def get_bottom_right(self): return Vector(self.right, self.bottom) def get_vertices(self): return self.top_left, self.top_right, self.bottom_right, self.bottom_left def get_dimensions(self): return (self._left, self._bottom), (self._width, self._height) def get_tuple(self): return self._left, self._bottom, self._width, self._height def get_union(self, *rectangles): return Rectangle.from_union(self, *rectangles) def get_intersection(self, *rectangles): return Rectangle.from_intersection(self, *rectangles) def get_grown(self, padding): result = self.copy() result.grow(padding) return result def get_shrunk(self, padding): result = self.copy() result.shrink(padding) return result def get_rounded(self, digits=0): result = self.copy() result.round(digits) return result def set_left(self, x): self._left = x def set_center_x(self, x): self._left = x - self._width / 2 def set_right(self, x): self._left = x - self._width def set_top(self, y): self._bottom = y - self._height def set_center_y(self, y): self._bottom = y - self._height / 2 def set_bottom(self, y): self._bottom = y def set_width(self, width): self._width = width def set_height(self, height): self._height = height def set_size(self, width, height): self._width = width self._height = height @accept_anything_as_vector def set_top_left(self, point): self.top = point[1] self.left = point[0] @accept_anything_as_vector def set_top_center(self, point): self.top = point[1] self.center_x = point[0] @accept_anything_as_vector def set_top_right(self, point): self.top = point[1] self.right = point[0] @accept_anything_as_vector def set_center_left(self, point): self.center_y = point[1] self.left = point[0] @accept_anything_as_vector def set_center(self, point): self.center_y = point[1] self.center_x = point[0] @accept_anything_as_vector def set_center_right(self, point): self.center_y = point[1] self.right = point[0] @accept_anything_as_vector def set_bottom_left(self, point): self.bottom = point[1] self.left = point[0] @accept_anything_as_vector def set_bottom_center(self, point): self.bottom = point[1] self.center_x = point[0] @accept_anything_as_vector def set_bottom_right(self, point): self.bottom = point[1] self.right = point[0] def set_vertices(self, vertices): self.top_left = vertices[0] self.top_right = vertices[1] self.bottom_right = vertices[2] self.bottom_left = vertices[3] # Properties (fold) left = property(get_left, set_left) center_x = property(get_center_x, set_center_x) right = property(get_right, set_right) top = property(get_top, set_top) center_y = property(get_center_y, set_center_y) bottom = property(get_bottom, set_bottom) area = property(get_area) width = property(get_width, set_width) height = property(get_height, set_height) half_width = property(get_half_width) half_height = property(get_half_height) size = property(get_size, set_size) size_as_int = property(get_size_as_int) top_left = property(get_top_left, set_top_left) top_center = property(get_top_center, set_top_center) top_right = property(get_top_right, set_top_right) center_left = property(get_center_left, set_center_left) center = property(get_center, set_center) center_right = property(get_center_right, set_center_right) bottom_left = property(get_bottom_left, set_bottom_left) bottom_center = property(get_bottom_center, set_bottom_center) bottom_right = property(get_bottom_right, set_bottom_right) vertices = property(get_vertices, set_vertices) dimensions = property(get_dimensions) tuple = property(get_tuple)
kxgames/vecrec
vecrec/shapes.py
Rectangle.inside
python
def inside(self, other): return ( self.left >= other.left and self.right <= other.right and self.top <= other.top and self.bottom >= other.bottom)
Return true if this rectangle is inside the given shape.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L729-L734
null
class Rectangle (Shape): def __init__(self, left, bottom, width, height): self._left = left self._bottom = bottom self._width = width self._height = height def __repr__(self): return "Rectangle(%f, %f, %f, %f)" % self.tuple def __str__(self): return '<Rect bottom={0} left={1} width={2} height={3}>'.format( self.bottom, self.left, self.width, self.height) def __eq__(self, other): try: return (self.bottom == other.bottom and self.left == other.left and self.width == other.width and self.height == other.height) except AttributeError: return False @accept_anything_as_vector def __add__(self, vector): result = self.copy() result.displace(vector) return result @accept_anything_as_vector def __iadd__(self, vector): self.displace(vector) return self @accept_anything_as_vector def __sub__(self, vector): result = self.copy() result.displace(-vector) return result @accept_anything_as_vector def __isub__(self, vector): self.displace(-vector) return self def __contains__(self, other): return self.contains(other) @staticmethod def null(): """ Return a rectangle with everything set to zero. It is located at the origin and has no area. """ return Rectangle(0, 0, 0, 0) @staticmethod def from_size(width, height): return Rectangle(0, 0, width, height) @staticmethod def from_width(width, ratio=1/golden_ratio): return Rectangle.from_size(width, ratio * width) @staticmethod def from_height(height, ratio=golden_ratio): return Rectangle.from_size(ratio * height, height) @staticmethod def from_square(size): return Rectangle.from_size(size, size) @staticmethod def from_dimensions(left, bottom, width, height): return Rectangle(left, bottom, width, height) @staticmethod def from_sides(left, top, right, bottom): width = right - left; height = top - bottom return Rectangle.from_dimensions(left, bottom, width, height) @staticmethod def from_corners(first, second): first = cast_anything_to_vector(first) second = cast_anything_to_vector(second) left = min(first.x, second.x); top = max(first.y, second.y) right = max(first.x, second.x); bottom = min(first.y, second.y) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_bottom_left(position, width, height): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, width, height) @staticmethod def from_center(position, width, height): position = cast_anything_to_vector(position) - (width/2, height/2) return Rectangle(position.x, position.y, width, height) @staticmethod def from_vector(position): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, 0, 0) @staticmethod def from_points(*points): left = min(cast_anything_to_vector(p).x for p in points) top = max(cast_anything_to_vector(p).y for p in points) right = max(cast_anything_to_vector(p).x for p in points) bottom = min(cast_anything_to_vector(p).y for p in points) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_shape(shape): bottom, left = shape.bottom, shape.left width, height = shape.width, shape.height return Rectangle(left, bottom, width, height) @staticmethod def from_surface(surface): width, height = surface.get_size() return Rectangle.from_size(width, height) @staticmethod def from_pyglet_window(window): return Rectangle.from_size(window.width, window.height) @staticmethod def from_pyglet_image(image): return Rectangle.from_size(image.width, image.height) @staticmethod def from_union(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = min(x.left for x in rectangles) top = max(x.top for x in rectangles) right = max(x.right for x in rectangles) bottom = min(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_intersection(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = max(x.left for x in rectangles) top = min(x.top for x in rectangles) right = min(x.right for x in rectangles) bottom = max(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) def grow(self, *padding): """ Grow this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom -= bpad self._left -= lpad self._width += lpad + rpad self._height += tpad + bpad return self def shrink(self, *padding): """ Shrink this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom += bpad self._left += lpad self._width -= lpad + rpad self._height -= tpad + bpad return self @accept_anything_as_vector def displace(self, vector): """ Displace this rectangle by the given vector. """ self._bottom += vector.y self._left += vector.x return self def round(self, digits=0): """ Round the dimensions of the given rectangle to the given number of digits. """ self._left = round(self._left, digits) self._bottom = round(self._bottom, digits) self._width = round(self._width, digits) self._height = round(self._height, digits) def set(self, shape): """ Fill this rectangle with the dimensions of the given shape. """ self.bottom, self.left = shape.bottom, shape.left self.width, self.height = shape.width, shape.height return self def copy(self): """ Return a copy of this rectangle. """ from copy import deepcopy return deepcopy(self) @accept_shape_as_rectangle @accept_anything_as_rectangle def outside(self, other): """ Return true if this rectangle is outside the given shape. """ return not self.touching(other) @accept_anything_as_rectangle def touching(self, other): """ Return true if this rectangle is touching the given shape. """ if self.top < other.bottom: return False if self.bottom > other.top: return False if self.left > other.right: return False if self.right < other.left: return False return True @accept_anything_as_rectangle def contains(self, other): """ Return true if the given shape is inside this rectangle. """ return (self.left <= other.left and self.right >= other.right and self.top >= other.top and self.bottom <= other.bottom) @accept_anything_as_rectangle def align_left(self, target): self.left = target.left @accept_anything_as_rectangle def align_center_x(self, target): self.center_x = target.center_x @accept_anything_as_rectangle def align_right(self, target): self.right = target.right @accept_anything_as_rectangle def align_top(self, target): self.top = target.top @accept_anything_as_rectangle def align_center_y(self, target): self.center_y = target.center_y @accept_anything_as_rectangle def align_bottom(self, target): self.bottom = target.bottom def get_left(self): return self._left def get_center_x(self): return self._left + self._width / 2 def get_right(self): return self._left + self._width def get_top(self): return self._bottom + self._height def get_center_y(self): return self._bottom + self._height / 2 def get_bottom(self): return self._bottom def get_area(self): return self._width * self._height def get_width(self): return self._width def get_height(self): return self._height def get_half_width(self): return self._width / 2 def get_half_height(self): return self._height / 2 def get_size(self): return Vector(self._width, self._height) def get_size_as_int(self): from math import ceil return Vector(int(ceil(self._width)), int(ceil(self._height))) def get_top_left(self): return Vector(self.left, self.top) def get_top_center(self): return Vector(self.center_x, self.top) def get_top_right(self): return Vector(self.right, self.top) def get_center_left(self): return Vector(self.left, self.center_y) def get_center(self): return Vector(self.center_x, self.center_y) def get_center_right(self): return Vector(self.right, self.center_y) def get_bottom_left(self): return Vector(self.left, self.bottom) def get_bottom_center(self): return Vector(self.center_x, self.bottom) def get_bottom_right(self): return Vector(self.right, self.bottom) def get_vertices(self): return self.top_left, self.top_right, self.bottom_right, self.bottom_left def get_dimensions(self): return (self._left, self._bottom), (self._width, self._height) def get_tuple(self): return self._left, self._bottom, self._width, self._height def get_union(self, *rectangles): return Rectangle.from_union(self, *rectangles) def get_intersection(self, *rectangles): return Rectangle.from_intersection(self, *rectangles) def get_grown(self, padding): result = self.copy() result.grow(padding) return result def get_shrunk(self, padding): result = self.copy() result.shrink(padding) return result def get_rounded(self, digits=0): result = self.copy() result.round(digits) return result def set_left(self, x): self._left = x def set_center_x(self, x): self._left = x - self._width / 2 def set_right(self, x): self._left = x - self._width def set_top(self, y): self._bottom = y - self._height def set_center_y(self, y): self._bottom = y - self._height / 2 def set_bottom(self, y): self._bottom = y def set_width(self, width): self._width = width def set_height(self, height): self._height = height def set_size(self, width, height): self._width = width self._height = height @accept_anything_as_vector def set_top_left(self, point): self.top = point[1] self.left = point[0] @accept_anything_as_vector def set_top_center(self, point): self.top = point[1] self.center_x = point[0] @accept_anything_as_vector def set_top_right(self, point): self.top = point[1] self.right = point[0] @accept_anything_as_vector def set_center_left(self, point): self.center_y = point[1] self.left = point[0] @accept_anything_as_vector def set_center(self, point): self.center_y = point[1] self.center_x = point[0] @accept_anything_as_vector def set_center_right(self, point): self.center_y = point[1] self.right = point[0] @accept_anything_as_vector def set_bottom_left(self, point): self.bottom = point[1] self.left = point[0] @accept_anything_as_vector def set_bottom_center(self, point): self.bottom = point[1] self.center_x = point[0] @accept_anything_as_vector def set_bottom_right(self, point): self.bottom = point[1] self.right = point[0] def set_vertices(self, vertices): self.top_left = vertices[0] self.top_right = vertices[1] self.bottom_right = vertices[2] self.bottom_left = vertices[3] # Properties (fold) left = property(get_left, set_left) center_x = property(get_center_x, set_center_x) right = property(get_right, set_right) top = property(get_top, set_top) center_y = property(get_center_y, set_center_y) bottom = property(get_bottom, set_bottom) area = property(get_area) width = property(get_width, set_width) height = property(get_height, set_height) half_width = property(get_half_width) half_height = property(get_half_height) size = property(get_size, set_size) size_as_int = property(get_size_as_int) top_left = property(get_top_left, set_top_left) top_center = property(get_top_center, set_top_center) top_right = property(get_top_right, set_top_right) center_left = property(get_center_left, set_center_left) center = property(get_center, set_center) center_right = property(get_center_right, set_center_right) bottom_left = property(get_bottom_left, set_bottom_left) bottom_center = property(get_bottom_center, set_bottom_center) bottom_right = property(get_bottom_right, set_bottom_right) vertices = property(get_vertices, set_vertices) dimensions = property(get_dimensions) tuple = property(get_tuple)
kxgames/vecrec
vecrec/shapes.py
Rectangle.touching
python
def touching(self, other): if self.top < other.bottom: return False if self.bottom > other.top: return False if self.left > other.right: return False if self.right < other.left: return False return True
Return true if this rectangle is touching the given shape.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L742-L750
null
class Rectangle (Shape): def __init__(self, left, bottom, width, height): self._left = left self._bottom = bottom self._width = width self._height = height def __repr__(self): return "Rectangle(%f, %f, %f, %f)" % self.tuple def __str__(self): return '<Rect bottom={0} left={1} width={2} height={3}>'.format( self.bottom, self.left, self.width, self.height) def __eq__(self, other): try: return (self.bottom == other.bottom and self.left == other.left and self.width == other.width and self.height == other.height) except AttributeError: return False @accept_anything_as_vector def __add__(self, vector): result = self.copy() result.displace(vector) return result @accept_anything_as_vector def __iadd__(self, vector): self.displace(vector) return self @accept_anything_as_vector def __sub__(self, vector): result = self.copy() result.displace(-vector) return result @accept_anything_as_vector def __isub__(self, vector): self.displace(-vector) return self def __contains__(self, other): return self.contains(other) @staticmethod def null(): """ Return a rectangle with everything set to zero. It is located at the origin and has no area. """ return Rectangle(0, 0, 0, 0) @staticmethod def from_size(width, height): return Rectangle(0, 0, width, height) @staticmethod def from_width(width, ratio=1/golden_ratio): return Rectangle.from_size(width, ratio * width) @staticmethod def from_height(height, ratio=golden_ratio): return Rectangle.from_size(ratio * height, height) @staticmethod def from_square(size): return Rectangle.from_size(size, size) @staticmethod def from_dimensions(left, bottom, width, height): return Rectangle(left, bottom, width, height) @staticmethod def from_sides(left, top, right, bottom): width = right - left; height = top - bottom return Rectangle.from_dimensions(left, bottom, width, height) @staticmethod def from_corners(first, second): first = cast_anything_to_vector(first) second = cast_anything_to_vector(second) left = min(first.x, second.x); top = max(first.y, second.y) right = max(first.x, second.x); bottom = min(first.y, second.y) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_bottom_left(position, width, height): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, width, height) @staticmethod def from_center(position, width, height): position = cast_anything_to_vector(position) - (width/2, height/2) return Rectangle(position.x, position.y, width, height) @staticmethod def from_vector(position): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, 0, 0) @staticmethod def from_points(*points): left = min(cast_anything_to_vector(p).x for p in points) top = max(cast_anything_to_vector(p).y for p in points) right = max(cast_anything_to_vector(p).x for p in points) bottom = min(cast_anything_to_vector(p).y for p in points) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_shape(shape): bottom, left = shape.bottom, shape.left width, height = shape.width, shape.height return Rectangle(left, bottom, width, height) @staticmethod def from_surface(surface): width, height = surface.get_size() return Rectangle.from_size(width, height) @staticmethod def from_pyglet_window(window): return Rectangle.from_size(window.width, window.height) @staticmethod def from_pyglet_image(image): return Rectangle.from_size(image.width, image.height) @staticmethod def from_union(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = min(x.left for x in rectangles) top = max(x.top for x in rectangles) right = max(x.right for x in rectangles) bottom = min(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_intersection(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = max(x.left for x in rectangles) top = min(x.top for x in rectangles) right = min(x.right for x in rectangles) bottom = max(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) def grow(self, *padding): """ Grow this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom -= bpad self._left -= lpad self._width += lpad + rpad self._height += tpad + bpad return self def shrink(self, *padding): """ Shrink this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom += bpad self._left += lpad self._width -= lpad + rpad self._height -= tpad + bpad return self @accept_anything_as_vector def displace(self, vector): """ Displace this rectangle by the given vector. """ self._bottom += vector.y self._left += vector.x return self def round(self, digits=0): """ Round the dimensions of the given rectangle to the given number of digits. """ self._left = round(self._left, digits) self._bottom = round(self._bottom, digits) self._width = round(self._width, digits) self._height = round(self._height, digits) def set(self, shape): """ Fill this rectangle with the dimensions of the given shape. """ self.bottom, self.left = shape.bottom, shape.left self.width, self.height = shape.width, shape.height return self def copy(self): """ Return a copy of this rectangle. """ from copy import deepcopy return deepcopy(self) @accept_shape_as_rectangle def inside(self, other): """ Return true if this rectangle is inside the given shape. """ return ( self.left >= other.left and self.right <= other.right and self.top <= other.top and self.bottom >= other.bottom) @accept_anything_as_rectangle def outside(self, other): """ Return true if this rectangle is outside the given shape. """ return not self.touching(other) @accept_anything_as_rectangle @accept_anything_as_rectangle def contains(self, other): """ Return true if the given shape is inside this rectangle. """ return (self.left <= other.left and self.right >= other.right and self.top >= other.top and self.bottom <= other.bottom) @accept_anything_as_rectangle def align_left(self, target): self.left = target.left @accept_anything_as_rectangle def align_center_x(self, target): self.center_x = target.center_x @accept_anything_as_rectangle def align_right(self, target): self.right = target.right @accept_anything_as_rectangle def align_top(self, target): self.top = target.top @accept_anything_as_rectangle def align_center_y(self, target): self.center_y = target.center_y @accept_anything_as_rectangle def align_bottom(self, target): self.bottom = target.bottom def get_left(self): return self._left def get_center_x(self): return self._left + self._width / 2 def get_right(self): return self._left + self._width def get_top(self): return self._bottom + self._height def get_center_y(self): return self._bottom + self._height / 2 def get_bottom(self): return self._bottom def get_area(self): return self._width * self._height def get_width(self): return self._width def get_height(self): return self._height def get_half_width(self): return self._width / 2 def get_half_height(self): return self._height / 2 def get_size(self): return Vector(self._width, self._height) def get_size_as_int(self): from math import ceil return Vector(int(ceil(self._width)), int(ceil(self._height))) def get_top_left(self): return Vector(self.left, self.top) def get_top_center(self): return Vector(self.center_x, self.top) def get_top_right(self): return Vector(self.right, self.top) def get_center_left(self): return Vector(self.left, self.center_y) def get_center(self): return Vector(self.center_x, self.center_y) def get_center_right(self): return Vector(self.right, self.center_y) def get_bottom_left(self): return Vector(self.left, self.bottom) def get_bottom_center(self): return Vector(self.center_x, self.bottom) def get_bottom_right(self): return Vector(self.right, self.bottom) def get_vertices(self): return self.top_left, self.top_right, self.bottom_right, self.bottom_left def get_dimensions(self): return (self._left, self._bottom), (self._width, self._height) def get_tuple(self): return self._left, self._bottom, self._width, self._height def get_union(self, *rectangles): return Rectangle.from_union(self, *rectangles) def get_intersection(self, *rectangles): return Rectangle.from_intersection(self, *rectangles) def get_grown(self, padding): result = self.copy() result.grow(padding) return result def get_shrunk(self, padding): result = self.copy() result.shrink(padding) return result def get_rounded(self, digits=0): result = self.copy() result.round(digits) return result def set_left(self, x): self._left = x def set_center_x(self, x): self._left = x - self._width / 2 def set_right(self, x): self._left = x - self._width def set_top(self, y): self._bottom = y - self._height def set_center_y(self, y): self._bottom = y - self._height / 2 def set_bottom(self, y): self._bottom = y def set_width(self, width): self._width = width def set_height(self, height): self._height = height def set_size(self, width, height): self._width = width self._height = height @accept_anything_as_vector def set_top_left(self, point): self.top = point[1] self.left = point[0] @accept_anything_as_vector def set_top_center(self, point): self.top = point[1] self.center_x = point[0] @accept_anything_as_vector def set_top_right(self, point): self.top = point[1] self.right = point[0] @accept_anything_as_vector def set_center_left(self, point): self.center_y = point[1] self.left = point[0] @accept_anything_as_vector def set_center(self, point): self.center_y = point[1] self.center_x = point[0] @accept_anything_as_vector def set_center_right(self, point): self.center_y = point[1] self.right = point[0] @accept_anything_as_vector def set_bottom_left(self, point): self.bottom = point[1] self.left = point[0] @accept_anything_as_vector def set_bottom_center(self, point): self.bottom = point[1] self.center_x = point[0] @accept_anything_as_vector def set_bottom_right(self, point): self.bottom = point[1] self.right = point[0] def set_vertices(self, vertices): self.top_left = vertices[0] self.top_right = vertices[1] self.bottom_right = vertices[2] self.bottom_left = vertices[3] # Properties (fold) left = property(get_left, set_left) center_x = property(get_center_x, set_center_x) right = property(get_right, set_right) top = property(get_top, set_top) center_y = property(get_center_y, set_center_y) bottom = property(get_bottom, set_bottom) area = property(get_area) width = property(get_width, set_width) height = property(get_height, set_height) half_width = property(get_half_width) half_height = property(get_half_height) size = property(get_size, set_size) size_as_int = property(get_size_as_int) top_left = property(get_top_left, set_top_left) top_center = property(get_top_center, set_top_center) top_right = property(get_top_right, set_top_right) center_left = property(get_center_left, set_center_left) center = property(get_center, set_center) center_right = property(get_center_right, set_center_right) bottom_left = property(get_bottom_left, set_bottom_left) bottom_center = property(get_bottom_center, set_bottom_center) bottom_right = property(get_bottom_right, set_bottom_right) vertices = property(get_vertices, set_vertices) dimensions = property(get_dimensions) tuple = property(get_tuple)
kxgames/vecrec
vecrec/shapes.py
Rectangle.contains
python
def contains(self, other): return (self.left <= other.left and self.right >= other.right and self.top >= other.top and self.bottom <= other.bottom)
Return true if the given shape is inside this rectangle.
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L753-L758
null
class Rectangle (Shape): def __init__(self, left, bottom, width, height): self._left = left self._bottom = bottom self._width = width self._height = height def __repr__(self): return "Rectangle(%f, %f, %f, %f)" % self.tuple def __str__(self): return '<Rect bottom={0} left={1} width={2} height={3}>'.format( self.bottom, self.left, self.width, self.height) def __eq__(self, other): try: return (self.bottom == other.bottom and self.left == other.left and self.width == other.width and self.height == other.height) except AttributeError: return False @accept_anything_as_vector def __add__(self, vector): result = self.copy() result.displace(vector) return result @accept_anything_as_vector def __iadd__(self, vector): self.displace(vector) return self @accept_anything_as_vector def __sub__(self, vector): result = self.copy() result.displace(-vector) return result @accept_anything_as_vector def __isub__(self, vector): self.displace(-vector) return self def __contains__(self, other): return self.contains(other) @staticmethod def null(): """ Return a rectangle with everything set to zero. It is located at the origin and has no area. """ return Rectangle(0, 0, 0, 0) @staticmethod def from_size(width, height): return Rectangle(0, 0, width, height) @staticmethod def from_width(width, ratio=1/golden_ratio): return Rectangle.from_size(width, ratio * width) @staticmethod def from_height(height, ratio=golden_ratio): return Rectangle.from_size(ratio * height, height) @staticmethod def from_square(size): return Rectangle.from_size(size, size) @staticmethod def from_dimensions(left, bottom, width, height): return Rectangle(left, bottom, width, height) @staticmethod def from_sides(left, top, right, bottom): width = right - left; height = top - bottom return Rectangle.from_dimensions(left, bottom, width, height) @staticmethod def from_corners(first, second): first = cast_anything_to_vector(first) second = cast_anything_to_vector(second) left = min(first.x, second.x); top = max(first.y, second.y) right = max(first.x, second.x); bottom = min(first.y, second.y) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_bottom_left(position, width, height): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, width, height) @staticmethod def from_center(position, width, height): position = cast_anything_to_vector(position) - (width/2, height/2) return Rectangle(position.x, position.y, width, height) @staticmethod def from_vector(position): position = cast_anything_to_vector(position) return Rectangle(position.x, position.y, 0, 0) @staticmethod def from_points(*points): left = min(cast_anything_to_vector(p).x for p in points) top = max(cast_anything_to_vector(p).y for p in points) right = max(cast_anything_to_vector(p).x for p in points) bottom = min(cast_anything_to_vector(p).y for p in points) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_shape(shape): bottom, left = shape.bottom, shape.left width, height = shape.width, shape.height return Rectangle(left, bottom, width, height) @staticmethod def from_surface(surface): width, height = surface.get_size() return Rectangle.from_size(width, height) @staticmethod def from_pyglet_window(window): return Rectangle.from_size(window.width, window.height) @staticmethod def from_pyglet_image(image): return Rectangle.from_size(image.width, image.height) @staticmethod def from_union(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = min(x.left for x in rectangles) top = max(x.top for x in rectangles) right = max(x.right for x in rectangles) bottom = min(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) @staticmethod def from_intersection(*inputs): rectangles = [cast_shape_to_rectangle(x) for x in inputs] left = max(x.left for x in rectangles) top = min(x.top for x in rectangles) right = min(x.right for x in rectangles) bottom = max(x.bottom for x in rectangles) return Rectangle.from_sides(left, top, right, bottom) def grow(self, *padding): """ Grow this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom -= bpad self._left -= lpad self._width += lpad + rpad self._height += tpad + bpad return self def shrink(self, *padding): """ Shrink this rectangle by the given padding on all sides. """ try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom += bpad self._left += lpad self._width -= lpad + rpad self._height -= tpad + bpad return self @accept_anything_as_vector def displace(self, vector): """ Displace this rectangle by the given vector. """ self._bottom += vector.y self._left += vector.x return self def round(self, digits=0): """ Round the dimensions of the given rectangle to the given number of digits. """ self._left = round(self._left, digits) self._bottom = round(self._bottom, digits) self._width = round(self._width, digits) self._height = round(self._height, digits) def set(self, shape): """ Fill this rectangle with the dimensions of the given shape. """ self.bottom, self.left = shape.bottom, shape.left self.width, self.height = shape.width, shape.height return self def copy(self): """ Return a copy of this rectangle. """ from copy import deepcopy return deepcopy(self) @accept_shape_as_rectangle def inside(self, other): """ Return true if this rectangle is inside the given shape. """ return ( self.left >= other.left and self.right <= other.right and self.top <= other.top and self.bottom >= other.bottom) @accept_anything_as_rectangle def outside(self, other): """ Return true if this rectangle is outside the given shape. """ return not self.touching(other) @accept_anything_as_rectangle def touching(self, other): """ Return true if this rectangle is touching the given shape. """ if self.top < other.bottom: return False if self.bottom > other.top: return False if self.left > other.right: return False if self.right < other.left: return False return True @accept_anything_as_rectangle @accept_anything_as_rectangle def align_left(self, target): self.left = target.left @accept_anything_as_rectangle def align_center_x(self, target): self.center_x = target.center_x @accept_anything_as_rectangle def align_right(self, target): self.right = target.right @accept_anything_as_rectangle def align_top(self, target): self.top = target.top @accept_anything_as_rectangle def align_center_y(self, target): self.center_y = target.center_y @accept_anything_as_rectangle def align_bottom(self, target): self.bottom = target.bottom def get_left(self): return self._left def get_center_x(self): return self._left + self._width / 2 def get_right(self): return self._left + self._width def get_top(self): return self._bottom + self._height def get_center_y(self): return self._bottom + self._height / 2 def get_bottom(self): return self._bottom def get_area(self): return self._width * self._height def get_width(self): return self._width def get_height(self): return self._height def get_half_width(self): return self._width / 2 def get_half_height(self): return self._height / 2 def get_size(self): return Vector(self._width, self._height) def get_size_as_int(self): from math import ceil return Vector(int(ceil(self._width)), int(ceil(self._height))) def get_top_left(self): return Vector(self.left, self.top) def get_top_center(self): return Vector(self.center_x, self.top) def get_top_right(self): return Vector(self.right, self.top) def get_center_left(self): return Vector(self.left, self.center_y) def get_center(self): return Vector(self.center_x, self.center_y) def get_center_right(self): return Vector(self.right, self.center_y) def get_bottom_left(self): return Vector(self.left, self.bottom) def get_bottom_center(self): return Vector(self.center_x, self.bottom) def get_bottom_right(self): return Vector(self.right, self.bottom) def get_vertices(self): return self.top_left, self.top_right, self.bottom_right, self.bottom_left def get_dimensions(self): return (self._left, self._bottom), (self._width, self._height) def get_tuple(self): return self._left, self._bottom, self._width, self._height def get_union(self, *rectangles): return Rectangle.from_union(self, *rectangles) def get_intersection(self, *rectangles): return Rectangle.from_intersection(self, *rectangles) def get_grown(self, padding): result = self.copy() result.grow(padding) return result def get_shrunk(self, padding): result = self.copy() result.shrink(padding) return result def get_rounded(self, digits=0): result = self.copy() result.round(digits) return result def set_left(self, x): self._left = x def set_center_x(self, x): self._left = x - self._width / 2 def set_right(self, x): self._left = x - self._width def set_top(self, y): self._bottom = y - self._height def set_center_y(self, y): self._bottom = y - self._height / 2 def set_bottom(self, y): self._bottom = y def set_width(self, width): self._width = width def set_height(self, height): self._height = height def set_size(self, width, height): self._width = width self._height = height @accept_anything_as_vector def set_top_left(self, point): self.top = point[1] self.left = point[0] @accept_anything_as_vector def set_top_center(self, point): self.top = point[1] self.center_x = point[0] @accept_anything_as_vector def set_top_right(self, point): self.top = point[1] self.right = point[0] @accept_anything_as_vector def set_center_left(self, point): self.center_y = point[1] self.left = point[0] @accept_anything_as_vector def set_center(self, point): self.center_y = point[1] self.center_x = point[0] @accept_anything_as_vector def set_center_right(self, point): self.center_y = point[1] self.right = point[0] @accept_anything_as_vector def set_bottom_left(self, point): self.bottom = point[1] self.left = point[0] @accept_anything_as_vector def set_bottom_center(self, point): self.bottom = point[1] self.center_x = point[0] @accept_anything_as_vector def set_bottom_right(self, point): self.bottom = point[1] self.right = point[0] def set_vertices(self, vertices): self.top_left = vertices[0] self.top_right = vertices[1] self.bottom_right = vertices[2] self.bottom_left = vertices[3] # Properties (fold) left = property(get_left, set_left) center_x = property(get_center_x, set_center_x) right = property(get_right, set_right) top = property(get_top, set_top) center_y = property(get_center_y, set_center_y) bottom = property(get_bottom, set_bottom) area = property(get_area) width = property(get_width, set_width) height = property(get_height, set_height) half_width = property(get_half_width) half_height = property(get_half_height) size = property(get_size, set_size) size_as_int = property(get_size_as_int) top_left = property(get_top_left, set_top_left) top_center = property(get_top_center, set_top_center) top_right = property(get_top_right, set_top_right) center_left = property(get_center_left, set_center_left) center = property(get_center, set_center) center_right = property(get_center_right, set_center_right) bottom_left = property(get_bottom_left, set_bottom_left) bottom_center = property(get_bottom_center, set_bottom_center) bottom_right = property(get_bottom_right, set_bottom_right) vertices = property(get_vertices, set_vertices) dimensions = property(get_dimensions) tuple = property(get_tuple)
kxgames/vecrec
vecrec/collisions.py
circle_touching_line
python
def circle_touching_line(center, radius, start, end): C, R = center, radius A, B = start, end a = (B.x - A.x)**2 + (B.y - A.y)**2 b = 2 * (B.x - A.x) * (A.x - C.x) \ + 2 * (B.y - A.y) * (A.y - C.y) c = C.x**2 + C.y**2 + A.x**2 + A.y**2 \ - 2 * (C.x * A.x + C.y * A.y) - R**2 discriminant = b**2 - 4 * a * c if discriminant < 0: return False elif discriminant == 0: u = v = -b / float(2 * a) else: u = (-b + math.sqrt(discriminant)) / float(2 * a) v = (-b - math.sqrt(discriminant)) / float(2 * a) if u < 0 and v < 0: return False if u > 1 and v > 1: return False return True
Return true if the given circle intersects the given segment. Note that this checks for intersection with a line segment, and not an actual line. :param center: Center of the circle. :type center: Vector :param radius: Radius of the circle. :type radius: float :param start: The first end of the line segment. :type start: Vector :param end: The second end of the line segment. :type end: Vector
train
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/collisions.py#L3-L40
null
#!/usr/bin/env python
boronine/discipline
disciplinesite/tools.py
word
python
def word(cap=False): syllables = [] for x in range(random.randint(2,3)): syllables.append(_syllable()) word = "".join(syllables) if cap: word = word[0].upper() + word[1:] return word
This function generates a fake word by creating between two and three random syllables and then joining them together.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/disciplinesite/tools.py#L23-L32
[ "def _syllable():\n return random.choice([_vowel, _cv, _cvc])()\n" ]
# -*- coding: utf-8 -*- import random vowels = "aeiou" consonants = 'bcdfghjklmnpqrstvwz' def _vowel(): return random.choice(vowels) def _consonant(): return random.choice(consonants) def _cv(): return _consonant() + _vowel() def _cvc(): return _cv() + _consonant() def _syllable(): return random.choice([_vowel, _cv, _cvc])() def sentence(): ret = word(True) for i in range(random.randint(5,15)): ret += " " + word() if random.randint(0,5) == 0: ret += "," return ret + ". " def mutate(word): p = random.randint(0,len(word)-1) w = word[:p] if word[p] in vowels: w += _vowel() else: w += _consonant() newword = w + word[p+1:] if newword == word: return mutate(word) return w + word[p+1:]
boronine/discipline
discipline/models.py
Editor.save_object
python
def save_object(self, obj): obj.save() try: save_object(obj, editor=self) except DisciplineException: pass
Save an object with Discipline Only argument is a Django object. This function saves the object (regardless of whether it already exists or not) and registers with Discipline, creating a new Action object. Do not use obj.save()!
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L112-L123
[ "def save_object(instance, editor):\n\n fields = []\n fks = []\n mods = []\n\n for field in instance.__class__._meta.fields:\n if field.name == \"uid\": continue\n fields.append(field.name)\n if field.__class__.__name__ == \"ForeignKey\":\n fks.append(field.name)\n\n #...
class Editor(Model): user = ForeignKey(User, unique=True, null=True) def __unicode__(self): text = self.user.first_name + " " + self.user.last_name text = text.strip() if not text: text = u"Anonymous %d" % self.user.id return text def delete_object(self, obj, post_delete=False): """Delete an object with Discipline Only argument is a Django object. Analogous to Editor.save_object. """ # Collect related objects that will be deleted by cascading links = [rel.get_accessor_name() for rel in \ obj._meta.get_all_related_objects()] # Recursively delete each of them for link in links: objects = getattr(obj, link).all() for o in objects: self.delete_object(o, post_delete) # Delete the actual object self._delete_object(obj, post_delete) def _delete_object(self, obj, post_delete): action = Action.objects.create( object_uid = obj.uid, action_type = "dl", editor = self, ) DeletionCommit( object_uid = obj.uid, action = action, ).save() if not post_delete: obj.delete() def undo_action(self, action): """Undo the given action""" action.undo(self)
boronine/discipline
discipline/models.py
Editor.delete_object
python
def delete_object(self, obj, post_delete=False): # Collect related objects that will be deleted by cascading links = [rel.get_accessor_name() for rel in \ obj._meta.get_all_related_objects()] # Recursively delete each of them for link in links: objects = getattr(obj, link).all() for o in objects: self.delete_object(o, post_delete) # Delete the actual object self._delete_object(obj, post_delete)
Delete an object with Discipline Only argument is a Django object. Analogous to Editor.save_object.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L125-L139
null
class Editor(Model): user = ForeignKey(User, unique=True, null=True) def __unicode__(self): text = self.user.first_name + " " + self.user.last_name text = text.strip() if not text: text = u"Anonymous %d" % self.user.id return text def save_object(self, obj): """Save an object with Discipline Only argument is a Django object. This function saves the object (regardless of whether it already exists or not) and registers with Discipline, creating a new Action object. Do not use obj.save()! """ obj.save() try: save_object(obj, editor=self) except DisciplineException: pass def _delete_object(self, obj, post_delete): action = Action.objects.create( object_uid = obj.uid, action_type = "dl", editor = self, ) DeletionCommit( object_uid = obj.uid, action = action, ).save() if not post_delete: obj.delete() def undo_action(self, action): """Undo the given action""" action.undo(self)
boronine/discipline
discipline/models.py
Action._description
python
def _description(self): inst = self.timemachine.presently if self.action_type == "dl": return "Deleted %s" % inst.content_type.name elif self.action_type == "cr": return "Created %s" % inst._object_type_html() else: return "Modified %s" % inst._object_type_html()
A concise html explanation of this Action.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L232-L242
null
class Action(Model): """Represents a unit of change at a specific point in time by a specific editor.""" editor = ForeignKey( "Editor", related_name = "commits", db_index = True, ) when = DateTimeField( auto_now_add = True, verbose_name = "commit time", db_index = True, ) reverted = OneToOneField( "Action", related_name = "reverts", db_index = True, null = True, ) object_uid = CharField( max_length = 32, db_index = True, ) action_type = CharField( max_length = 2, db_index = True, ) class Meta: # Most of the time you will need most recent ordering = ["-when"] get_latest_by = "id" def __unicode__(self): return "%s: %s" % (unicode(self.editor), unicode(self.when)) _description.allow_tags = True # To save database queries __timemachine = False def __get_timemachine(self): """Return a TimeMachine for the object on which this action was performed and at the time of this action.""" if not self.__timemachine: self.__timemachine = TimeMachine( self.object_uid, step = self.id, ) return self.__timemachine.at(self.id) timemachine = property(__get_timemachine) def __get_is_revertible(self): """Return a boolean representing whether this Action is revertible or not""" # If it was already reverted if self.reverted: return False errors = [] inst = self.timemachine if inst.fields != inst.presently.fields or \ inst.foreignkeys != inst.presently.foreignkeys: self.__undo_errors = [ "Cannot undo action %s. The database schema" " for %s has changed" % (self.id, inst.content_type.name,)] return False if self.action_type in ["dl", "md"]: # If undoing deletion, make sure it actually doesn't exist if self.action_type == "dl" and inst.presently.exists: errors.append( "Cannot undo action %d: the %s you are trying to" " recreate already exists" % (self.id, inst.content_type.name,)) # The only problem we can have by reversing this action # is that some of its foreignkeys could be pointing to # objects that have since been deleted. check_here = inst.at_previous_action for field in inst.foreignkeys: fk = check_here.get_timemachine_instance(field) # If the ForeignKey doesn't have a value if not fk: continue if not fk.exists: errors.append( "Cannot undo action %s: the %s used to link to" " a %s that has since been deleted" % (self.id, inst.content_type.name, fk.content_type.name,)) else: # self.action_type == "cr" # Make sure it actually exists if not self.timemachine.presently.exists: errors.append( "Cannot undo action %s: the %s you are trying" " to delete doesn't currently exist" % (self.id, inst.content_type.name,)) # The only problem we can have by undoing this action is # that it could have foreignkeys pointed to it, so deleting # it will cause deletion of other objects else: links = [rel.get_accessor_name() for rel in \ inst.get_object()._meta.get_all_related_objects()] for link in links: objects = getattr(inst.get_object(), link).all() for rel in objects: errors.append( "Cannot undo action %s: you are trying to" " delete a %s that has a %s pointing to it" % (self.id, inst.content_type.name, ContentType.objects.get_for_model(rel.__class__),)) self.__undo_errors = errors return (len(errors) == 0) is_revertible = property(__get_is_revertible) def __get__undo_errors(self): if self.__undo_errors == None: self._get__is_revertible() return self.__undo_errors undo_errors = property(__get__undo_errors) def undo(self, editor): """Create a new Action that undos the effects of this one, or, more accurately, reverts the object of this Action to the state at which it was right before the Action took place.""" inst = self.timemachine if not self.is_revertible: raise DisciplineException("You tried to undo a non-revertible action! " "Check action.is_revertible and action.undo_errors" " before trying to undo.") if self.action_type == "dl": obj = inst.restore() self.reverted = save_object(obj, editor) self.save() elif self.action_type == "md": # Restore as it was *before* the modification obj = inst.at_previous_action.restore() self.reverted = save_object(obj, editor) self.save() else: editor.delete_object(inst.get_object()) # This is safe from race conditions but still a pretty inelegant # solution. I can't figure out a different way to find the last action # for now self.reverted = DeletionCommit.objects.filter( object_uid = self.object_uid ).order_by("-action__id")[0].action self.save() def _status(self): """Return html saying whether this Action is reverted by another one or reverts another one.""" text = "" # Turns out that is related field in null, Django # doesn't even make it a property of the object # http://code.djangoproject.com/ticket/11920 if hasattr(self, "reverts"): text += '(reverts <a href="%s">%s</a>)<br/>' % ( self.reverts.get_absolute_url(), self.reverts.id ) if self.reverted: text += '(reverted in <a href="%s">%s</a>)<br/>' % ( self.reverted.get_absolute_url(), self.reverted.id ) return text _status.allow_tags = True def get_absolute_url(self): return urlresolvers.reverse( "admin:discipline_action_change", args = (self.id,) ) def __summary(self): """A plaintext summary of the Action, useful for debugging.""" text = "Time: %s\n" % self.when text += "Comitter: %s\n" % self.editor inst = self.timemachine.presently if self.action_type == "dl": text += "Deleted %s\n" % inst._object_type_text() elif self.action_type == "cr": text += "Created %s\n" % inst._object_type_text() else: text += "Modified %s\n" % inst._object_type_text() text += self._details(nohtml=True) return text summary = property(__summary) def _details(self, nohtml=False): """Return the html representation of the Action.""" text = "" inst = self.timemachine # If deleted or created, show every field, otherwise only # the modified if self.action_type in ("dl","cr",): fields = inst.fields + inst.foreignkeys else: fields = [i.key for i in self.modification_commits.all()] for field in fields: if not nohtml: text += "<strong>%s</strong>: " % field else: text += "%s: " % field # If modified, show what it was like one step earlier if self.action_type == "md": if not nohtml: text += "%s &#8594; " % \ inst.at_previous_action._field_value_html(field) else: text += "%s -> " % \ inst.at_previous_action._field_value_text(field) if not nohtml: text += "%s<br/>" % inst._field_value_html(field) else: text += "%s\n" % inst._field_value_text(field) return text _details.allow_tags = True
boronine/discipline
discipline/models.py
Action.__get_timemachine
python
def __get_timemachine(self): if not self.__timemachine: self.__timemachine = TimeMachine( self.object_uid, step = self.id, ) return self.__timemachine.at(self.id)
Return a TimeMachine for the object on which this action was performed and at the time of this action.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L249-L258
null
class Action(Model): """Represents a unit of change at a specific point in time by a specific editor.""" editor = ForeignKey( "Editor", related_name = "commits", db_index = True, ) when = DateTimeField( auto_now_add = True, verbose_name = "commit time", db_index = True, ) reverted = OneToOneField( "Action", related_name = "reverts", db_index = True, null = True, ) object_uid = CharField( max_length = 32, db_index = True, ) action_type = CharField( max_length = 2, db_index = True, ) class Meta: # Most of the time you will need most recent ordering = ["-when"] get_latest_by = "id" def __unicode__(self): return "%s: %s" % (unicode(self.editor), unicode(self.when)) def _description(self): """A concise html explanation of this Action.""" inst = self.timemachine.presently if self.action_type == "dl": return "Deleted %s" % inst.content_type.name elif self.action_type == "cr": return "Created %s" % inst._object_type_html() else: return "Modified %s" % inst._object_type_html() _description.allow_tags = True # To save database queries __timemachine = False timemachine = property(__get_timemachine) def __get_is_revertible(self): """Return a boolean representing whether this Action is revertible or not""" # If it was already reverted if self.reverted: return False errors = [] inst = self.timemachine if inst.fields != inst.presently.fields or \ inst.foreignkeys != inst.presently.foreignkeys: self.__undo_errors = [ "Cannot undo action %s. The database schema" " for %s has changed" % (self.id, inst.content_type.name,)] return False if self.action_type in ["dl", "md"]: # If undoing deletion, make sure it actually doesn't exist if self.action_type == "dl" and inst.presently.exists: errors.append( "Cannot undo action %d: the %s you are trying to" " recreate already exists" % (self.id, inst.content_type.name,)) # The only problem we can have by reversing this action # is that some of its foreignkeys could be pointing to # objects that have since been deleted. check_here = inst.at_previous_action for field in inst.foreignkeys: fk = check_here.get_timemachine_instance(field) # If the ForeignKey doesn't have a value if not fk: continue if not fk.exists: errors.append( "Cannot undo action %s: the %s used to link to" " a %s that has since been deleted" % (self.id, inst.content_type.name, fk.content_type.name,)) else: # self.action_type == "cr" # Make sure it actually exists if not self.timemachine.presently.exists: errors.append( "Cannot undo action %s: the %s you are trying" " to delete doesn't currently exist" % (self.id, inst.content_type.name,)) # The only problem we can have by undoing this action is # that it could have foreignkeys pointed to it, so deleting # it will cause deletion of other objects else: links = [rel.get_accessor_name() for rel in \ inst.get_object()._meta.get_all_related_objects()] for link in links: objects = getattr(inst.get_object(), link).all() for rel in objects: errors.append( "Cannot undo action %s: you are trying to" " delete a %s that has a %s pointing to it" % (self.id, inst.content_type.name, ContentType.objects.get_for_model(rel.__class__),)) self.__undo_errors = errors return (len(errors) == 0) is_revertible = property(__get_is_revertible) def __get__undo_errors(self): if self.__undo_errors == None: self._get__is_revertible() return self.__undo_errors undo_errors = property(__get__undo_errors) def undo(self, editor): """Create a new Action that undos the effects of this one, or, more accurately, reverts the object of this Action to the state at which it was right before the Action took place.""" inst = self.timemachine if not self.is_revertible: raise DisciplineException("You tried to undo a non-revertible action! " "Check action.is_revertible and action.undo_errors" " before trying to undo.") if self.action_type == "dl": obj = inst.restore() self.reverted = save_object(obj, editor) self.save() elif self.action_type == "md": # Restore as it was *before* the modification obj = inst.at_previous_action.restore() self.reverted = save_object(obj, editor) self.save() else: editor.delete_object(inst.get_object()) # This is safe from race conditions but still a pretty inelegant # solution. I can't figure out a different way to find the last action # for now self.reverted = DeletionCommit.objects.filter( object_uid = self.object_uid ).order_by("-action__id")[0].action self.save() def _status(self): """Return html saying whether this Action is reverted by another one or reverts another one.""" text = "" # Turns out that is related field in null, Django # doesn't even make it a property of the object # http://code.djangoproject.com/ticket/11920 if hasattr(self, "reverts"): text += '(reverts <a href="%s">%s</a>)<br/>' % ( self.reverts.get_absolute_url(), self.reverts.id ) if self.reverted: text += '(reverted in <a href="%s">%s</a>)<br/>' % ( self.reverted.get_absolute_url(), self.reverted.id ) return text _status.allow_tags = True def get_absolute_url(self): return urlresolvers.reverse( "admin:discipline_action_change", args = (self.id,) ) def __summary(self): """A plaintext summary of the Action, useful for debugging.""" text = "Time: %s\n" % self.when text += "Comitter: %s\n" % self.editor inst = self.timemachine.presently if self.action_type == "dl": text += "Deleted %s\n" % inst._object_type_text() elif self.action_type == "cr": text += "Created %s\n" % inst._object_type_text() else: text += "Modified %s\n" % inst._object_type_text() text += self._details(nohtml=True) return text summary = property(__summary) def _details(self, nohtml=False): """Return the html representation of the Action.""" text = "" inst = self.timemachine # If deleted or created, show every field, otherwise only # the modified if self.action_type in ("dl","cr",): fields = inst.fields + inst.foreignkeys else: fields = [i.key for i in self.modification_commits.all()] for field in fields: if not nohtml: text += "<strong>%s</strong>: " % field else: text += "%s: " % field # If modified, show what it was like one step earlier if self.action_type == "md": if not nohtml: text += "%s &#8594; " % \ inst.at_previous_action._field_value_html(field) else: text += "%s -> " % \ inst.at_previous_action._field_value_text(field) if not nohtml: text += "%s<br/>" % inst._field_value_html(field) else: text += "%s\n" % inst._field_value_text(field) return text _details.allow_tags = True
boronine/discipline
discipline/models.py
Action.__get_is_revertible
python
def __get_is_revertible(self): # If it was already reverted if self.reverted: return False errors = [] inst = self.timemachine if inst.fields != inst.presently.fields or \ inst.foreignkeys != inst.presently.foreignkeys: self.__undo_errors = [ "Cannot undo action %s. The database schema" " for %s has changed" % (self.id, inst.content_type.name,)] return False if self.action_type in ["dl", "md"]: # If undoing deletion, make sure it actually doesn't exist if self.action_type == "dl" and inst.presently.exists: errors.append( "Cannot undo action %d: the %s you are trying to" " recreate already exists" % (self.id, inst.content_type.name,)) # The only problem we can have by reversing this action # is that some of its foreignkeys could be pointing to # objects that have since been deleted. check_here = inst.at_previous_action for field in inst.foreignkeys: fk = check_here.get_timemachine_instance(field) # If the ForeignKey doesn't have a value if not fk: continue if not fk.exists: errors.append( "Cannot undo action %s: the %s used to link to" " a %s that has since been deleted" % (self.id, inst.content_type.name, fk.content_type.name,)) else: # self.action_type == "cr" # Make sure it actually exists if not self.timemachine.presently.exists: errors.append( "Cannot undo action %s: the %s you are trying" " to delete doesn't currently exist" % (self.id, inst.content_type.name,)) # The only problem we can have by undoing this action is # that it could have foreignkeys pointed to it, so deleting # it will cause deletion of other objects else: links = [rel.get_accessor_name() for rel in \ inst.get_object()._meta.get_all_related_objects()] for link in links: objects = getattr(inst.get_object(), link).all() for rel in objects: errors.append( "Cannot undo action %s: you are trying to" " delete a %s that has a %s pointing to it" % (self.id, inst.content_type.name, ContentType.objects.get_for_model(rel.__class__),)) self.__undo_errors = errors return (len(errors) == 0)
Return a boolean representing whether this Action is revertible or not
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L262-L332
null
class Action(Model): """Represents a unit of change at a specific point in time by a specific editor.""" editor = ForeignKey( "Editor", related_name = "commits", db_index = True, ) when = DateTimeField( auto_now_add = True, verbose_name = "commit time", db_index = True, ) reverted = OneToOneField( "Action", related_name = "reverts", db_index = True, null = True, ) object_uid = CharField( max_length = 32, db_index = True, ) action_type = CharField( max_length = 2, db_index = True, ) class Meta: # Most of the time you will need most recent ordering = ["-when"] get_latest_by = "id" def __unicode__(self): return "%s: %s" % (unicode(self.editor), unicode(self.when)) def _description(self): """A concise html explanation of this Action.""" inst = self.timemachine.presently if self.action_type == "dl": return "Deleted %s" % inst.content_type.name elif self.action_type == "cr": return "Created %s" % inst._object_type_html() else: return "Modified %s" % inst._object_type_html() _description.allow_tags = True # To save database queries __timemachine = False def __get_timemachine(self): """Return a TimeMachine for the object on which this action was performed and at the time of this action.""" if not self.__timemachine: self.__timemachine = TimeMachine( self.object_uid, step = self.id, ) return self.__timemachine.at(self.id) timemachine = property(__get_timemachine) def __get_is_revertible(self): """Return a boolean representing whether this Action is revertible or not""" # If it was already reverted if self.reverted: return False errors = [] inst = self.timemachine if inst.fields != inst.presently.fields or \ inst.foreignkeys != inst.presently.foreignkeys: self.__undo_errors = [ "Cannot undo action %s. The database schema" " for %s has changed" % (self.id, inst.content_type.name,)] return False if self.action_type in ["dl", "md"]: # If undoing deletion, make sure it actually doesn't exist if self.action_type == "dl" and inst.presently.exists: errors.append( "Cannot undo action %d: the %s you are trying to" " recreate already exists" % (self.id, inst.content_type.name,)) # The only problem we can have by reversing this action # is that some of its foreignkeys could be pointing to # objects that have since been deleted. check_here = inst.at_previous_action for field in inst.foreignkeys: fk = check_here.get_timemachine_instance(field) # If the ForeignKey doesn't have a value if not fk: continue if not fk.exists: errors.append( "Cannot undo action %s: the %s used to link to" " a %s that has since been deleted" % (self.id, inst.content_type.name, fk.content_type.name,)) else: # self.action_type == "cr" # Make sure it actually exists if not self.timemachine.presently.exists: errors.append( "Cannot undo action %s: the %s you are trying" " to delete doesn't currently exist" % (self.id, inst.content_type.name,)) # The only problem we can have by undoing this action is # that it could have foreignkeys pointed to it, so deleting # it will cause deletion of other objects else: links = [rel.get_accessor_name() for rel in \ inst.get_object()._meta.get_all_related_objects()] for link in links: objects = getattr(inst.get_object(), link).all() for rel in objects: errors.append( "Cannot undo action %s: you are trying to" " delete a %s that has a %s pointing to it" % (self.id, inst.content_type.name, ContentType.objects.get_for_model(rel.__class__),)) self.__undo_errors = errors return (len(errors) == 0) is_revertible = property(__get_is_revertible) def __get__undo_errors(self): if self.__undo_errors == None: self._get__is_revertible() return self.__undo_errors undo_errors = property(__get__undo_errors) def undo(self, editor): """Create a new Action that undos the effects of this one, or, more accurately, reverts the object of this Action to the state at which it was right before the Action took place.""" inst = self.timemachine if not self.is_revertible: raise DisciplineException("You tried to undo a non-revertible action! " "Check action.is_revertible and action.undo_errors" " before trying to undo.") if self.action_type == "dl": obj = inst.restore() self.reverted = save_object(obj, editor) self.save() elif self.action_type == "md": # Restore as it was *before* the modification obj = inst.at_previous_action.restore() self.reverted = save_object(obj, editor) self.save() else: editor.delete_object(inst.get_object()) # This is safe from race conditions but still a pretty inelegant # solution. I can't figure out a different way to find the last action # for now self.reverted = DeletionCommit.objects.filter( object_uid = self.object_uid ).order_by("-action__id")[0].action self.save() def _status(self): """Return html saying whether this Action is reverted by another one or reverts another one.""" text = "" # Turns out that is related field in null, Django # doesn't even make it a property of the object # http://code.djangoproject.com/ticket/11920 if hasattr(self, "reverts"): text += '(reverts <a href="%s">%s</a>)<br/>' % ( self.reverts.get_absolute_url(), self.reverts.id ) if self.reverted: text += '(reverted in <a href="%s">%s</a>)<br/>' % ( self.reverted.get_absolute_url(), self.reverted.id ) return text _status.allow_tags = True def get_absolute_url(self): return urlresolvers.reverse( "admin:discipline_action_change", args = (self.id,) ) def __summary(self): """A plaintext summary of the Action, useful for debugging.""" text = "Time: %s\n" % self.when text += "Comitter: %s\n" % self.editor inst = self.timemachine.presently if self.action_type == "dl": text += "Deleted %s\n" % inst._object_type_text() elif self.action_type == "cr": text += "Created %s\n" % inst._object_type_text() else: text += "Modified %s\n" % inst._object_type_text() text += self._details(nohtml=True) return text summary = property(__summary) def _details(self, nohtml=False): """Return the html representation of the Action.""" text = "" inst = self.timemachine # If deleted or created, show every field, otherwise only # the modified if self.action_type in ("dl","cr",): fields = inst.fields + inst.foreignkeys else: fields = [i.key for i in self.modification_commits.all()] for field in fields: if not nohtml: text += "<strong>%s</strong>: " % field else: text += "%s: " % field # If modified, show what it was like one step earlier if self.action_type == "md": if not nohtml: text += "%s &#8594; " % \ inst.at_previous_action._field_value_html(field) else: text += "%s -> " % \ inst.at_previous_action._field_value_text(field) if not nohtml: text += "%s<br/>" % inst._field_value_html(field) else: text += "%s\n" % inst._field_value_text(field) return text _details.allow_tags = True
boronine/discipline
discipline/models.py
Action.undo
python
def undo(self, editor): inst = self.timemachine if not self.is_revertible: raise DisciplineException("You tried to undo a non-revertible action! " "Check action.is_revertible and action.undo_errors" " before trying to undo.") if self.action_type == "dl": obj = inst.restore() self.reverted = save_object(obj, editor) self.save() elif self.action_type == "md": # Restore as it was *before* the modification obj = inst.at_previous_action.restore() self.reverted = save_object(obj, editor) self.save() else: editor.delete_object(inst.get_object()) # This is safe from race conditions but still a pretty inelegant # solution. I can't figure out a different way to find the last action # for now self.reverted = DeletionCommit.objects.filter( object_uid = self.object_uid ).order_by("-action__id")[0].action self.save()
Create a new Action that undos the effects of this one, or, more accurately, reverts the object of this Action to the state at which it was right before the Action took place.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L342-L369
[ "def save_object(instance, editor):\n\n fields = []\n fks = []\n mods = []\n\n for field in instance.__class__._meta.fields:\n if field.name == \"uid\": continue\n fields.append(field.name)\n if field.__class__.__name__ == \"ForeignKey\":\n fks.append(field.name)\n\n #...
class Action(Model): """Represents a unit of change at a specific point in time by a specific editor.""" editor = ForeignKey( "Editor", related_name = "commits", db_index = True, ) when = DateTimeField( auto_now_add = True, verbose_name = "commit time", db_index = True, ) reverted = OneToOneField( "Action", related_name = "reverts", db_index = True, null = True, ) object_uid = CharField( max_length = 32, db_index = True, ) action_type = CharField( max_length = 2, db_index = True, ) class Meta: # Most of the time you will need most recent ordering = ["-when"] get_latest_by = "id" def __unicode__(self): return "%s: %s" % (unicode(self.editor), unicode(self.when)) def _description(self): """A concise html explanation of this Action.""" inst = self.timemachine.presently if self.action_type == "dl": return "Deleted %s" % inst.content_type.name elif self.action_type == "cr": return "Created %s" % inst._object_type_html() else: return "Modified %s" % inst._object_type_html() _description.allow_tags = True # To save database queries __timemachine = False def __get_timemachine(self): """Return a TimeMachine for the object on which this action was performed and at the time of this action.""" if not self.__timemachine: self.__timemachine = TimeMachine( self.object_uid, step = self.id, ) return self.__timemachine.at(self.id) timemachine = property(__get_timemachine) def __get_is_revertible(self): """Return a boolean representing whether this Action is revertible or not""" # If it was already reverted if self.reverted: return False errors = [] inst = self.timemachine if inst.fields != inst.presently.fields or \ inst.foreignkeys != inst.presently.foreignkeys: self.__undo_errors = [ "Cannot undo action %s. The database schema" " for %s has changed" % (self.id, inst.content_type.name,)] return False if self.action_type in ["dl", "md"]: # If undoing deletion, make sure it actually doesn't exist if self.action_type == "dl" and inst.presently.exists: errors.append( "Cannot undo action %d: the %s you are trying to" " recreate already exists" % (self.id, inst.content_type.name,)) # The only problem we can have by reversing this action # is that some of its foreignkeys could be pointing to # objects that have since been deleted. check_here = inst.at_previous_action for field in inst.foreignkeys: fk = check_here.get_timemachine_instance(field) # If the ForeignKey doesn't have a value if not fk: continue if not fk.exists: errors.append( "Cannot undo action %s: the %s used to link to" " a %s that has since been deleted" % (self.id, inst.content_type.name, fk.content_type.name,)) else: # self.action_type == "cr" # Make sure it actually exists if not self.timemachine.presently.exists: errors.append( "Cannot undo action %s: the %s you are trying" " to delete doesn't currently exist" % (self.id, inst.content_type.name,)) # The only problem we can have by undoing this action is # that it could have foreignkeys pointed to it, so deleting # it will cause deletion of other objects else: links = [rel.get_accessor_name() for rel in \ inst.get_object()._meta.get_all_related_objects()] for link in links: objects = getattr(inst.get_object(), link).all() for rel in objects: errors.append( "Cannot undo action %s: you are trying to" " delete a %s that has a %s pointing to it" % (self.id, inst.content_type.name, ContentType.objects.get_for_model(rel.__class__),)) self.__undo_errors = errors return (len(errors) == 0) is_revertible = property(__get_is_revertible) def __get__undo_errors(self): if self.__undo_errors == None: self._get__is_revertible() return self.__undo_errors undo_errors = property(__get__undo_errors) def _status(self): """Return html saying whether this Action is reverted by another one or reverts another one.""" text = "" # Turns out that is related field in null, Django # doesn't even make it a property of the object # http://code.djangoproject.com/ticket/11920 if hasattr(self, "reverts"): text += '(reverts <a href="%s">%s</a>)<br/>' % ( self.reverts.get_absolute_url(), self.reverts.id ) if self.reverted: text += '(reverted in <a href="%s">%s</a>)<br/>' % ( self.reverted.get_absolute_url(), self.reverted.id ) return text _status.allow_tags = True def get_absolute_url(self): return urlresolvers.reverse( "admin:discipline_action_change", args = (self.id,) ) def __summary(self): """A plaintext summary of the Action, useful for debugging.""" text = "Time: %s\n" % self.when text += "Comitter: %s\n" % self.editor inst = self.timemachine.presently if self.action_type == "dl": text += "Deleted %s\n" % inst._object_type_text() elif self.action_type == "cr": text += "Created %s\n" % inst._object_type_text() else: text += "Modified %s\n" % inst._object_type_text() text += self._details(nohtml=True) return text summary = property(__summary) def _details(self, nohtml=False): """Return the html representation of the Action.""" text = "" inst = self.timemachine # If deleted or created, show every field, otherwise only # the modified if self.action_type in ("dl","cr",): fields = inst.fields + inst.foreignkeys else: fields = [i.key for i in self.modification_commits.all()] for field in fields: if not nohtml: text += "<strong>%s</strong>: " % field else: text += "%s: " % field # If modified, show what it was like one step earlier if self.action_type == "md": if not nohtml: text += "%s &#8594; " % \ inst.at_previous_action._field_value_html(field) else: text += "%s -> " % \ inst.at_previous_action._field_value_text(field) if not nohtml: text += "%s<br/>" % inst._field_value_html(field) else: text += "%s\n" % inst._field_value_text(field) return text _details.allow_tags = True
boronine/discipline
discipline/models.py
Action._status
python
def _status(self): text = "" # Turns out that is related field in null, Django # doesn't even make it a property of the object # http://code.djangoproject.com/ticket/11920 if hasattr(self, "reverts"): text += '(reverts <a href="%s">%s</a>)<br/>' % ( self.reverts.get_absolute_url(), self.reverts.id ) if self.reverted: text += '(reverted in <a href="%s">%s</a>)<br/>' % ( self.reverted.get_absolute_url(), self.reverted.id ) return text
Return html saying whether this Action is reverted by another one or reverts another one.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L371-L388
null
class Action(Model): """Represents a unit of change at a specific point in time by a specific editor.""" editor = ForeignKey( "Editor", related_name = "commits", db_index = True, ) when = DateTimeField( auto_now_add = True, verbose_name = "commit time", db_index = True, ) reverted = OneToOneField( "Action", related_name = "reverts", db_index = True, null = True, ) object_uid = CharField( max_length = 32, db_index = True, ) action_type = CharField( max_length = 2, db_index = True, ) class Meta: # Most of the time you will need most recent ordering = ["-when"] get_latest_by = "id" def __unicode__(self): return "%s: %s" % (unicode(self.editor), unicode(self.when)) def _description(self): """A concise html explanation of this Action.""" inst = self.timemachine.presently if self.action_type == "dl": return "Deleted %s" % inst.content_type.name elif self.action_type == "cr": return "Created %s" % inst._object_type_html() else: return "Modified %s" % inst._object_type_html() _description.allow_tags = True # To save database queries __timemachine = False def __get_timemachine(self): """Return a TimeMachine for the object on which this action was performed and at the time of this action.""" if not self.__timemachine: self.__timemachine = TimeMachine( self.object_uid, step = self.id, ) return self.__timemachine.at(self.id) timemachine = property(__get_timemachine) def __get_is_revertible(self): """Return a boolean representing whether this Action is revertible or not""" # If it was already reverted if self.reverted: return False errors = [] inst = self.timemachine if inst.fields != inst.presently.fields or \ inst.foreignkeys != inst.presently.foreignkeys: self.__undo_errors = [ "Cannot undo action %s. The database schema" " for %s has changed" % (self.id, inst.content_type.name,)] return False if self.action_type in ["dl", "md"]: # If undoing deletion, make sure it actually doesn't exist if self.action_type == "dl" and inst.presently.exists: errors.append( "Cannot undo action %d: the %s you are trying to" " recreate already exists" % (self.id, inst.content_type.name,)) # The only problem we can have by reversing this action # is that some of its foreignkeys could be pointing to # objects that have since been deleted. check_here = inst.at_previous_action for field in inst.foreignkeys: fk = check_here.get_timemachine_instance(field) # If the ForeignKey doesn't have a value if not fk: continue if not fk.exists: errors.append( "Cannot undo action %s: the %s used to link to" " a %s that has since been deleted" % (self.id, inst.content_type.name, fk.content_type.name,)) else: # self.action_type == "cr" # Make sure it actually exists if not self.timemachine.presently.exists: errors.append( "Cannot undo action %s: the %s you are trying" " to delete doesn't currently exist" % (self.id, inst.content_type.name,)) # The only problem we can have by undoing this action is # that it could have foreignkeys pointed to it, so deleting # it will cause deletion of other objects else: links = [rel.get_accessor_name() for rel in \ inst.get_object()._meta.get_all_related_objects()] for link in links: objects = getattr(inst.get_object(), link).all() for rel in objects: errors.append( "Cannot undo action %s: you are trying to" " delete a %s that has a %s pointing to it" % (self.id, inst.content_type.name, ContentType.objects.get_for_model(rel.__class__),)) self.__undo_errors = errors return (len(errors) == 0) is_revertible = property(__get_is_revertible) def __get__undo_errors(self): if self.__undo_errors == None: self._get__is_revertible() return self.__undo_errors undo_errors = property(__get__undo_errors) def undo(self, editor): """Create a new Action that undos the effects of this one, or, more accurately, reverts the object of this Action to the state at which it was right before the Action took place.""" inst = self.timemachine if not self.is_revertible: raise DisciplineException("You tried to undo a non-revertible action! " "Check action.is_revertible and action.undo_errors" " before trying to undo.") if self.action_type == "dl": obj = inst.restore() self.reverted = save_object(obj, editor) self.save() elif self.action_type == "md": # Restore as it was *before* the modification obj = inst.at_previous_action.restore() self.reverted = save_object(obj, editor) self.save() else: editor.delete_object(inst.get_object()) # This is safe from race conditions but still a pretty inelegant # solution. I can't figure out a different way to find the last action # for now self.reverted = DeletionCommit.objects.filter( object_uid = self.object_uid ).order_by("-action__id")[0].action self.save() _status.allow_tags = True def get_absolute_url(self): return urlresolvers.reverse( "admin:discipline_action_change", args = (self.id,) ) def __summary(self): """A plaintext summary of the Action, useful for debugging.""" text = "Time: %s\n" % self.when text += "Comitter: %s\n" % self.editor inst = self.timemachine.presently if self.action_type == "dl": text += "Deleted %s\n" % inst._object_type_text() elif self.action_type == "cr": text += "Created %s\n" % inst._object_type_text() else: text += "Modified %s\n" % inst._object_type_text() text += self._details(nohtml=True) return text summary = property(__summary) def _details(self, nohtml=False): """Return the html representation of the Action.""" text = "" inst = self.timemachine # If deleted or created, show every field, otherwise only # the modified if self.action_type in ("dl","cr",): fields = inst.fields + inst.foreignkeys else: fields = [i.key for i in self.modification_commits.all()] for field in fields: if not nohtml: text += "<strong>%s</strong>: " % field else: text += "%s: " % field # If modified, show what it was like one step earlier if self.action_type == "md": if not nohtml: text += "%s &#8594; " % \ inst.at_previous_action._field_value_html(field) else: text += "%s -> " % \ inst.at_previous_action._field_value_text(field) if not nohtml: text += "%s<br/>" % inst._field_value_html(field) else: text += "%s\n" % inst._field_value_text(field) return text _details.allow_tags = True
boronine/discipline
discipline/models.py
Action.__summary
python
def __summary(self): text = "Time: %s\n" % self.when text += "Comitter: %s\n" % self.editor inst = self.timemachine.presently if self.action_type == "dl": text += "Deleted %s\n" % inst._object_type_text() elif self.action_type == "cr": text += "Created %s\n" % inst._object_type_text() else: text += "Modified %s\n" % inst._object_type_text() text += self._details(nohtml=True) return text
A plaintext summary of the Action, useful for debugging.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L398-L412
null
class Action(Model): """Represents a unit of change at a specific point in time by a specific editor.""" editor = ForeignKey( "Editor", related_name = "commits", db_index = True, ) when = DateTimeField( auto_now_add = True, verbose_name = "commit time", db_index = True, ) reverted = OneToOneField( "Action", related_name = "reverts", db_index = True, null = True, ) object_uid = CharField( max_length = 32, db_index = True, ) action_type = CharField( max_length = 2, db_index = True, ) class Meta: # Most of the time you will need most recent ordering = ["-when"] get_latest_by = "id" def __unicode__(self): return "%s: %s" % (unicode(self.editor), unicode(self.when)) def _description(self): """A concise html explanation of this Action.""" inst = self.timemachine.presently if self.action_type == "dl": return "Deleted %s" % inst.content_type.name elif self.action_type == "cr": return "Created %s" % inst._object_type_html() else: return "Modified %s" % inst._object_type_html() _description.allow_tags = True # To save database queries __timemachine = False def __get_timemachine(self): """Return a TimeMachine for the object on which this action was performed and at the time of this action.""" if not self.__timemachine: self.__timemachine = TimeMachine( self.object_uid, step = self.id, ) return self.__timemachine.at(self.id) timemachine = property(__get_timemachine) def __get_is_revertible(self): """Return a boolean representing whether this Action is revertible or not""" # If it was already reverted if self.reverted: return False errors = [] inst = self.timemachine if inst.fields != inst.presently.fields or \ inst.foreignkeys != inst.presently.foreignkeys: self.__undo_errors = [ "Cannot undo action %s. The database schema" " for %s has changed" % (self.id, inst.content_type.name,)] return False if self.action_type in ["dl", "md"]: # If undoing deletion, make sure it actually doesn't exist if self.action_type == "dl" and inst.presently.exists: errors.append( "Cannot undo action %d: the %s you are trying to" " recreate already exists" % (self.id, inst.content_type.name,)) # The only problem we can have by reversing this action # is that some of its foreignkeys could be pointing to # objects that have since been deleted. check_here = inst.at_previous_action for field in inst.foreignkeys: fk = check_here.get_timemachine_instance(field) # If the ForeignKey doesn't have a value if not fk: continue if not fk.exists: errors.append( "Cannot undo action %s: the %s used to link to" " a %s that has since been deleted" % (self.id, inst.content_type.name, fk.content_type.name,)) else: # self.action_type == "cr" # Make sure it actually exists if not self.timemachine.presently.exists: errors.append( "Cannot undo action %s: the %s you are trying" " to delete doesn't currently exist" % (self.id, inst.content_type.name,)) # The only problem we can have by undoing this action is # that it could have foreignkeys pointed to it, so deleting # it will cause deletion of other objects else: links = [rel.get_accessor_name() for rel in \ inst.get_object()._meta.get_all_related_objects()] for link in links: objects = getattr(inst.get_object(), link).all() for rel in objects: errors.append( "Cannot undo action %s: you are trying to" " delete a %s that has a %s pointing to it" % (self.id, inst.content_type.name, ContentType.objects.get_for_model(rel.__class__),)) self.__undo_errors = errors return (len(errors) == 0) is_revertible = property(__get_is_revertible) def __get__undo_errors(self): if self.__undo_errors == None: self._get__is_revertible() return self.__undo_errors undo_errors = property(__get__undo_errors) def undo(self, editor): """Create a new Action that undos the effects of this one, or, more accurately, reverts the object of this Action to the state at which it was right before the Action took place.""" inst = self.timemachine if not self.is_revertible: raise DisciplineException("You tried to undo a non-revertible action! " "Check action.is_revertible and action.undo_errors" " before trying to undo.") if self.action_type == "dl": obj = inst.restore() self.reverted = save_object(obj, editor) self.save() elif self.action_type == "md": # Restore as it was *before* the modification obj = inst.at_previous_action.restore() self.reverted = save_object(obj, editor) self.save() else: editor.delete_object(inst.get_object()) # This is safe from race conditions but still a pretty inelegant # solution. I can't figure out a different way to find the last action # for now self.reverted = DeletionCommit.objects.filter( object_uid = self.object_uid ).order_by("-action__id")[0].action self.save() def _status(self): """Return html saying whether this Action is reverted by another one or reverts another one.""" text = "" # Turns out that is related field in null, Django # doesn't even make it a property of the object # http://code.djangoproject.com/ticket/11920 if hasattr(self, "reverts"): text += '(reverts <a href="%s">%s</a>)<br/>' % ( self.reverts.get_absolute_url(), self.reverts.id ) if self.reverted: text += '(reverted in <a href="%s">%s</a>)<br/>' % ( self.reverted.get_absolute_url(), self.reverted.id ) return text _status.allow_tags = True def get_absolute_url(self): return urlresolvers.reverse( "admin:discipline_action_change", args = (self.id,) ) summary = property(__summary) def _details(self, nohtml=False): """Return the html representation of the Action.""" text = "" inst = self.timemachine # If deleted or created, show every field, otherwise only # the modified if self.action_type in ("dl","cr",): fields = inst.fields + inst.foreignkeys else: fields = [i.key for i in self.modification_commits.all()] for field in fields: if not nohtml: text += "<strong>%s</strong>: " % field else: text += "%s: " % field # If modified, show what it was like one step earlier if self.action_type == "md": if not nohtml: text += "%s &#8594; " % \ inst.at_previous_action._field_value_html(field) else: text += "%s -> " % \ inst.at_previous_action._field_value_text(field) if not nohtml: text += "%s<br/>" % inst._field_value_html(field) else: text += "%s\n" % inst._field_value_text(field) return text _details.allow_tags = True
boronine/discipline
discipline/models.py
Action._details
python
def _details(self, nohtml=False): text = "" inst = self.timemachine # If deleted or created, show every field, otherwise only # the modified if self.action_type in ("dl","cr",): fields = inst.fields + inst.foreignkeys else: fields = [i.key for i in self.modification_commits.all()] for field in fields: if not nohtml: text += "<strong>%s</strong>: " % field else: text += "%s: " % field # If modified, show what it was like one step earlier if self.action_type == "md": if not nohtml: text += "%s &#8594; " % \ inst.at_previous_action._field_value_html(field) else: text += "%s -> " % \ inst.at_previous_action._field_value_text(field) if not nohtml: text += "%s<br/>" % inst._field_value_html(field) else: text += "%s\n" % inst._field_value_text(field) return text
Return the html representation of the Action.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L416-L447
null
class Action(Model): """Represents a unit of change at a specific point in time by a specific editor.""" editor = ForeignKey( "Editor", related_name = "commits", db_index = True, ) when = DateTimeField( auto_now_add = True, verbose_name = "commit time", db_index = True, ) reverted = OneToOneField( "Action", related_name = "reverts", db_index = True, null = True, ) object_uid = CharField( max_length = 32, db_index = True, ) action_type = CharField( max_length = 2, db_index = True, ) class Meta: # Most of the time you will need most recent ordering = ["-when"] get_latest_by = "id" def __unicode__(self): return "%s: %s" % (unicode(self.editor), unicode(self.when)) def _description(self): """A concise html explanation of this Action.""" inst = self.timemachine.presently if self.action_type == "dl": return "Deleted %s" % inst.content_type.name elif self.action_type == "cr": return "Created %s" % inst._object_type_html() else: return "Modified %s" % inst._object_type_html() _description.allow_tags = True # To save database queries __timemachine = False def __get_timemachine(self): """Return a TimeMachine for the object on which this action was performed and at the time of this action.""" if not self.__timemachine: self.__timemachine = TimeMachine( self.object_uid, step = self.id, ) return self.__timemachine.at(self.id) timemachine = property(__get_timemachine) def __get_is_revertible(self): """Return a boolean representing whether this Action is revertible or not""" # If it was already reverted if self.reverted: return False errors = [] inst = self.timemachine if inst.fields != inst.presently.fields or \ inst.foreignkeys != inst.presently.foreignkeys: self.__undo_errors = [ "Cannot undo action %s. The database schema" " for %s has changed" % (self.id, inst.content_type.name,)] return False if self.action_type in ["dl", "md"]: # If undoing deletion, make sure it actually doesn't exist if self.action_type == "dl" and inst.presently.exists: errors.append( "Cannot undo action %d: the %s you are trying to" " recreate already exists" % (self.id, inst.content_type.name,)) # The only problem we can have by reversing this action # is that some of its foreignkeys could be pointing to # objects that have since been deleted. check_here = inst.at_previous_action for field in inst.foreignkeys: fk = check_here.get_timemachine_instance(field) # If the ForeignKey doesn't have a value if not fk: continue if not fk.exists: errors.append( "Cannot undo action %s: the %s used to link to" " a %s that has since been deleted" % (self.id, inst.content_type.name, fk.content_type.name,)) else: # self.action_type == "cr" # Make sure it actually exists if not self.timemachine.presently.exists: errors.append( "Cannot undo action %s: the %s you are trying" " to delete doesn't currently exist" % (self.id, inst.content_type.name,)) # The only problem we can have by undoing this action is # that it could have foreignkeys pointed to it, so deleting # it will cause deletion of other objects else: links = [rel.get_accessor_name() for rel in \ inst.get_object()._meta.get_all_related_objects()] for link in links: objects = getattr(inst.get_object(), link).all() for rel in objects: errors.append( "Cannot undo action %s: you are trying to" " delete a %s that has a %s pointing to it" % (self.id, inst.content_type.name, ContentType.objects.get_for_model(rel.__class__),)) self.__undo_errors = errors return (len(errors) == 0) is_revertible = property(__get_is_revertible) def __get__undo_errors(self): if self.__undo_errors == None: self._get__is_revertible() return self.__undo_errors undo_errors = property(__get__undo_errors) def undo(self, editor): """Create a new Action that undos the effects of this one, or, more accurately, reverts the object of this Action to the state at which it was right before the Action took place.""" inst = self.timemachine if not self.is_revertible: raise DisciplineException("You tried to undo a non-revertible action! " "Check action.is_revertible and action.undo_errors" " before trying to undo.") if self.action_type == "dl": obj = inst.restore() self.reverted = save_object(obj, editor) self.save() elif self.action_type == "md": # Restore as it was *before* the modification obj = inst.at_previous_action.restore() self.reverted = save_object(obj, editor) self.save() else: editor.delete_object(inst.get_object()) # This is safe from race conditions but still a pretty inelegant # solution. I can't figure out a different way to find the last action # for now self.reverted = DeletionCommit.objects.filter( object_uid = self.object_uid ).order_by("-action__id")[0].action self.save() def _status(self): """Return html saying whether this Action is reverted by another one or reverts another one.""" text = "" # Turns out that is related field in null, Django # doesn't even make it a property of the object # http://code.djangoproject.com/ticket/11920 if hasattr(self, "reverts"): text += '(reverts <a href="%s">%s</a>)<br/>' % ( self.reverts.get_absolute_url(), self.reverts.id ) if self.reverted: text += '(reverted in <a href="%s">%s</a>)<br/>' % ( self.reverted.get_absolute_url(), self.reverted.id ) return text _status.allow_tags = True def get_absolute_url(self): return urlresolvers.reverse( "admin:discipline_action_change", args = (self.id,) ) def __summary(self): """A plaintext summary of the Action, useful for debugging.""" text = "Time: %s\n" % self.when text += "Comitter: %s\n" % self.editor inst = self.timemachine.presently if self.action_type == "dl": text += "Deleted %s\n" % inst._object_type_text() elif self.action_type == "cr": text += "Created %s\n" % inst._object_type_text() else: text += "Modified %s\n" % inst._object_type_text() text += self._details(nohtml=True) return text summary = property(__summary) _details.allow_tags = True
boronine/discipline
discipline/models.py
TimeMachine.__update_information
python
def __update_information(self): info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key])
Gether information that doesn't change at different points in time
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L563-L595
null
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
TimeMachine.at
python
def at(self, step): return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) )
Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L597-L609
null
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
TimeMachine._get_modcommit
python
def _get_modcommit(self, key): try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None
Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L621-L633
null
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
TimeMachine.get
python
def get(self, key): modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid))
Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L635-L654
[ "def _get_modcommit(self, key):\n \"\"\"Return the last modcommit of the given field. If no\n modcommit exists (for example after a migration that created\n new fields) returns None.\n \"\"\"\n try:\n return ModificationCommit.objects.filter(\n object_uid = self.uid,\n ke...
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
TimeMachine.get_timemachine_instance
python
def get_timemachine_instance(self, key): modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value)
Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L656-L667
[ "def _get_modcommit(self, key):\n \"\"\"Return the last modcommit of the given field. If no\n modcommit exists (for example after a migration that created\n new fields) returns None.\n \"\"\"\n try:\n return ModificationCommit.objects.filter(\n object_uid = self.uid,\n ke...
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
TimeMachine.get_object
python
def get_object(self): return self.content_type.model_class().objects.get(uid = self.uid)
Return the object of this TimeMachine
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L669-L671
null
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
TimeMachine.restore
python
def restore(self, nosave=False): if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj
Restore all of the object attributes to the attributes. Return the Django object.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L711-L722
[ "def get(self, key):\n \"\"\"Return the value of a field.\n\n Take a string argument representing a field name, return the value of\n that field at the time of this TimeMachine. When restoring a \n ForeignKey-pointer object that doesn't exist, raise \n DisciplineException\n\n \"\"\"\n modcommit...
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
TimeMachine.url
python
def url(self): return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,))
Return the admin url of the object.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L727-L732
[ "def get_object(self):\n \"\"\"Return the object of this TimeMachine\"\"\"\n return self.content_type.model_class().objects.get(uid = self.uid)\n" ]
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
TimeMachine._object_type_html
python
def _object_type_html(self): if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name
Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L735-L744
null
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
TimeMachine._object_name_html
python
def _object_name_html(self): if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)"
Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)".
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L746-L755
null
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
TimeMachine._field_value_html
python
def _field_value_html(self, field): if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html()
Return the html representation of the value of the given field
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L757-L762
null
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
TimeMachine._field_value_text
python
def _field_value_text(self, field): if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text()
Return the html representation of the value of the given field
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L764-L769
null
class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name
boronine/discipline
discipline/models.py
SchemaState.get_for_content_type
python
def get_for_content_type(self, ct): try: return json.loads(self.state)[ct.app_label][ct.model] except KeyError: return None
Return the schema for the model of the given ContentType object
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L798-L803
null
class SchemaState(Model): """Record the state of each relevant model's fields at a point in time. Fields: when -- BooleanField representing the time of this snapshot state -- TextField holding the json representation of the schema state. Do not use this field, use public methods. """ when = DateTimeField(auto_now_add=True, verbose_name="Saved") state = TextField() class Meta: ordering = ["-when"] def html_state(self): """Display state in HTML format for the admin form.""" ret = "" state = json.loads(self.state) for (app, appstate) in state.items(): for (model, modelstate) in appstate.items(): ret += "<p>%s.models.%s</p>" % (app, model,) ret += "<ul>" for field in modelstate["fields"] + ["uid"]: ret += "<li>%s</li>" % field for fk in modelstate["foreignkeys"]: ret += "<li>%s (foreign key)</li>" % fk ret += "</ul>" return ret html_state.allow_tags = True html_state.short_description = "State"
boronine/discipline
discipline/models.py
SchemaState.html_state
python
def html_state(self): ret = "" state = json.loads(self.state) for (app, appstate) in state.items(): for (model, modelstate) in appstate.items(): ret += "<p>%s.models.%s</p>" % (app, model,) ret += "<ul>" for field in modelstate["fields"] + ["uid"]: ret += "<li>%s</li>" % field for fk in modelstate["foreignkeys"]: ret += "<li>%s (foreign key)</li>" % fk ret += "</ul>" return ret
Display state in HTML format for the admin form.
train
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L808-L821
null
class SchemaState(Model): """Record the state of each relevant model's fields at a point in time. Fields: when -- BooleanField representing the time of this snapshot state -- TextField holding the json representation of the schema state. Do not use this field, use public methods. """ when = DateTimeField(auto_now_add=True, verbose_name="Saved") state = TextField() def get_for_content_type(self, ct): """Return the schema for the model of the given ContentType object""" try: return json.loads(self.state)[ct.app_label][ct.model] except KeyError: return None class Meta: ordering = ["-when"] html_state.allow_tags = True html_state.short_description = "State"
bmweiner/skillful
skillful/validate.py
timestamp
python
def timestamp(stamp, tolerance=150): try: tolerance = datetime.timedelta(0, tolerance) timestamp_low = dateutil.parser.parse(stamp) timestamp_high = timestamp_low + tolerance now = datetime.datetime.now(timestamp_low.tzinfo) except ValueError: return False return now >= timestamp_low and now <= timestamp_high
Validate timestamp specified by request. See `validate.request` for additional info. Args: stamp: str. Time request was made as ISO 8601 timestamp. tolerance: int. Number of seconds request remains valid from timestamp. Returns bool: True if valid, False otherwise.
train
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L21-L41
null
"""Handler for request validation""" import warnings import os import sys import datetime import base64 import six from six.moves.urllib_parse import urlparse from six.moves.urllib.request import urlopen from six.moves.urllib_error import HTTPError from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.exceptions import InvalidSignature import dateutil.parser def signature_cert_chain_url(url): """Validate URL specified by SignatureCertChainUrl. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: bool: True if valid, False otherwise. """ r = urlparse(url) if not r.scheme.lower() == 'https': warnings.warn('Certificate URL scheme is invalid.') return False if not r.hostname.lower() == 's3.amazonaws.com': warnings.warn('Certificate URL hostname is invalid.') return False if not os.path.normpath(r.path).startswith('/echo.api/'): warnings.warn('Certificate URL path is invalid.') return False if r.port and not r.port == 443: warnings.warn('Certificate URL port is invalid.') return False return True def retrieve(url): """Retrieve and parse PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ try: pem_data = urlopen(url).read() except (ValueError, HTTPError): warnings.warn('Certificate URL is invalid.') return False if sys.version >= '3': try: pem_data = pem_data.decode() except(UnicodeDecodeError): warnings.warn('Certificate encoding is not utf-8.') return False return _parse_pem_data(pem_data) def _parse_pem_data(pem_data): """Parse PEM-encoded X.509 certificate chain. Args: pem_data: str. PEM file retrieved from SignatureCertChainUrl. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ sep = '-----BEGIN CERTIFICATE-----' cert_chain = [six.b(sep + s) for s in pem_data.split(sep)[1:]] certs = [] load_cert = x509.load_pem_x509_certificate for cert in cert_chain: try: certs.append(load_cert(cert, default_backend())) except ValueError: warnings.warn('Certificate is invalid.') return False return certs def cert_chain(certs): """Validate PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: certs: list. The certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates. See `validate.retrieve` to create certs obj. Returns: bool: True if valid, False otherwise. """ if len(certs) < 2: warnings.warn('Certificate chain contains < 3 certificates.') return False cert = certs[0] today = datetime.datetime.today() if not today > cert.not_valid_before: warnings.warn('Certificate Not Before date is invalid.') return False if not today < cert.not_valid_after: warnings.warn('Certificate Not After date is invalid.') return False oid_san = x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME ext = cert.extensions.get_extension_for_oid(oid_san) sans = ext.value.get_values_for_type(x509.DNSName) if not 'echo-api.amazon.com' in sans: return False for i in range(len(certs) - 1): if not certs[i].issuer == certs[i + 1].subject: return False return True def signature(cert, sig, body): """Validate data request signature. See `validate.request` for additional info. Args: cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. sig: str. Signature header value sent by request. body: str. HTTPS request body. Returns: bool: True if valid, False otherwise. """ body = six.b(body) sig = base64.decodestring(sig) padder = padding.PKCS1v15() public_key = cert.public_key() try: public_key.verify(sig, body, padder, hashes.SHA1()) return True except InvalidSignature: warnings.warn('Signature verification failed.') return False class Valid(object): """Alexa request validator. Attributes: app_id: str. Skill application ID. url: str. SignatureCertChainUrl header value sent by request. PEM-encoded X.509 certificate chain that Alexa used to sign the message. Used to cache valid url. cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. Used to cache valid cert. """ def __init__(self, app_id=None): """Init validator.""" self.app_id = app_id self.url = None self.cert = None def application_id(self, app_id): """Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise. """ if self.app_id != app_id: warnings.warn('Application ID is invalid.') return False return True def sender(self, body, stamp, url, sig): """Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. stamp: str. Value of timestamp within request object of HTTPS request body. url: str. SignatureCertChainUrl header value sent by request. sig: str. Signature header value sent by request. Returns: bool: True if valid, False otherwise. """ if not timestamp(stamp): return False if self.url != url: if not signature_cert_chain_url(url): return False certs = retrieve(url) if not certs: return False if not cert_chain(certs): return False self.url = url self.cert = certs[0] if not signature(self.cert, sig, body): return False return True def request(self, app_id=None, body=None, stamp=None, url=None, sig=None): """Validate application ID and request is from Alexa.""" if self.app_id: if not self.application_id(app_id): return False if (url or sig): if not (body and stamp and url and sig): raise ValueError('Unable to validate sender, check arguments.') else: if not self.sender(body, stamp, url, sig): return False return True
bmweiner/skillful
skillful/validate.py
signature_cert_chain_url
python
def signature_cert_chain_url(url): r = urlparse(url) if not r.scheme.lower() == 'https': warnings.warn('Certificate URL scheme is invalid.') return False if not r.hostname.lower() == 's3.amazonaws.com': warnings.warn('Certificate URL hostname is invalid.') return False if not os.path.normpath(r.path).startswith('/echo.api/'): warnings.warn('Certificate URL path is invalid.') return False if r.port and not r.port == 443: warnings.warn('Certificate URL port is invalid.') return False return True
Validate URL specified by SignatureCertChainUrl. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: bool: True if valid, False otherwise.
train
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L43-L67
null
"""Handler for request validation""" import warnings import os import sys import datetime import base64 import six from six.moves.urllib_parse import urlparse from six.moves.urllib.request import urlopen from six.moves.urllib_error import HTTPError from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.exceptions import InvalidSignature import dateutil.parser def timestamp(stamp, tolerance=150): """Validate timestamp specified by request. See `validate.request` for additional info. Args: stamp: str. Time request was made as ISO 8601 timestamp. tolerance: int. Number of seconds request remains valid from timestamp. Returns bool: True if valid, False otherwise. """ try: tolerance = datetime.timedelta(0, tolerance) timestamp_low = dateutil.parser.parse(stamp) timestamp_high = timestamp_low + tolerance now = datetime.datetime.now(timestamp_low.tzinfo) except ValueError: return False return now >= timestamp_low and now <= timestamp_high def retrieve(url): """Retrieve and parse PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ try: pem_data = urlopen(url).read() except (ValueError, HTTPError): warnings.warn('Certificate URL is invalid.') return False if sys.version >= '3': try: pem_data = pem_data.decode() except(UnicodeDecodeError): warnings.warn('Certificate encoding is not utf-8.') return False return _parse_pem_data(pem_data) def _parse_pem_data(pem_data): """Parse PEM-encoded X.509 certificate chain. Args: pem_data: str. PEM file retrieved from SignatureCertChainUrl. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ sep = '-----BEGIN CERTIFICATE-----' cert_chain = [six.b(sep + s) for s in pem_data.split(sep)[1:]] certs = [] load_cert = x509.load_pem_x509_certificate for cert in cert_chain: try: certs.append(load_cert(cert, default_backend())) except ValueError: warnings.warn('Certificate is invalid.') return False return certs def cert_chain(certs): """Validate PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: certs: list. The certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates. See `validate.retrieve` to create certs obj. Returns: bool: True if valid, False otherwise. """ if len(certs) < 2: warnings.warn('Certificate chain contains < 3 certificates.') return False cert = certs[0] today = datetime.datetime.today() if not today > cert.not_valid_before: warnings.warn('Certificate Not Before date is invalid.') return False if not today < cert.not_valid_after: warnings.warn('Certificate Not After date is invalid.') return False oid_san = x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME ext = cert.extensions.get_extension_for_oid(oid_san) sans = ext.value.get_values_for_type(x509.DNSName) if not 'echo-api.amazon.com' in sans: return False for i in range(len(certs) - 1): if not certs[i].issuer == certs[i + 1].subject: return False return True def signature(cert, sig, body): """Validate data request signature. See `validate.request` for additional info. Args: cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. sig: str. Signature header value sent by request. body: str. HTTPS request body. Returns: bool: True if valid, False otherwise. """ body = six.b(body) sig = base64.decodestring(sig) padder = padding.PKCS1v15() public_key = cert.public_key() try: public_key.verify(sig, body, padder, hashes.SHA1()) return True except InvalidSignature: warnings.warn('Signature verification failed.') return False class Valid(object): """Alexa request validator. Attributes: app_id: str. Skill application ID. url: str. SignatureCertChainUrl header value sent by request. PEM-encoded X.509 certificate chain that Alexa used to sign the message. Used to cache valid url. cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. Used to cache valid cert. """ def __init__(self, app_id=None): """Init validator.""" self.app_id = app_id self.url = None self.cert = None def application_id(self, app_id): """Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise. """ if self.app_id != app_id: warnings.warn('Application ID is invalid.') return False return True def sender(self, body, stamp, url, sig): """Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. stamp: str. Value of timestamp within request object of HTTPS request body. url: str. SignatureCertChainUrl header value sent by request. sig: str. Signature header value sent by request. Returns: bool: True if valid, False otherwise. """ if not timestamp(stamp): return False if self.url != url: if not signature_cert_chain_url(url): return False certs = retrieve(url) if not certs: return False if not cert_chain(certs): return False self.url = url self.cert = certs[0] if not signature(self.cert, sig, body): return False return True def request(self, app_id=None, body=None, stamp=None, url=None, sig=None): """Validate application ID and request is from Alexa.""" if self.app_id: if not self.application_id(app_id): return False if (url or sig): if not (body and stamp and url and sig): raise ValueError('Unable to validate sender, check arguments.') else: if not self.sender(body, stamp, url, sig): return False return True
bmweiner/skillful
skillful/validate.py
retrieve
python
def retrieve(url): try: pem_data = urlopen(url).read() except (ValueError, HTTPError): warnings.warn('Certificate URL is invalid.') return False if sys.version >= '3': try: pem_data = pem_data.decode() except(UnicodeDecodeError): warnings.warn('Certificate encoding is not utf-8.') return False return _parse_pem_data(pem_data)
Retrieve and parse PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False.
train
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L69-L96
[ "def _parse_pem_data(pem_data):\n \"\"\"Parse PEM-encoded X.509 certificate chain.\n\n Args:\n pem_data: str. PEM file retrieved from SignatureCertChainUrl.\n\n Returns:\n list or bool: If url is valid, returns the certificate chain as a list\n of cryptography.hazmat.backends.opens...
"""Handler for request validation""" import warnings import os import sys import datetime import base64 import six from six.moves.urllib_parse import urlparse from six.moves.urllib.request import urlopen from six.moves.urllib_error import HTTPError from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.exceptions import InvalidSignature import dateutil.parser def timestamp(stamp, tolerance=150): """Validate timestamp specified by request. See `validate.request` for additional info. Args: stamp: str. Time request was made as ISO 8601 timestamp. tolerance: int. Number of seconds request remains valid from timestamp. Returns bool: True if valid, False otherwise. """ try: tolerance = datetime.timedelta(0, tolerance) timestamp_low = dateutil.parser.parse(stamp) timestamp_high = timestamp_low + tolerance now = datetime.datetime.now(timestamp_low.tzinfo) except ValueError: return False return now >= timestamp_low and now <= timestamp_high def signature_cert_chain_url(url): """Validate URL specified by SignatureCertChainUrl. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: bool: True if valid, False otherwise. """ r = urlparse(url) if not r.scheme.lower() == 'https': warnings.warn('Certificate URL scheme is invalid.') return False if not r.hostname.lower() == 's3.amazonaws.com': warnings.warn('Certificate URL hostname is invalid.') return False if not os.path.normpath(r.path).startswith('/echo.api/'): warnings.warn('Certificate URL path is invalid.') return False if r.port and not r.port == 443: warnings.warn('Certificate URL port is invalid.') return False return True def _parse_pem_data(pem_data): """Parse PEM-encoded X.509 certificate chain. Args: pem_data: str. PEM file retrieved from SignatureCertChainUrl. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ sep = '-----BEGIN CERTIFICATE-----' cert_chain = [six.b(sep + s) for s in pem_data.split(sep)[1:]] certs = [] load_cert = x509.load_pem_x509_certificate for cert in cert_chain: try: certs.append(load_cert(cert, default_backend())) except ValueError: warnings.warn('Certificate is invalid.') return False return certs def cert_chain(certs): """Validate PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: certs: list. The certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates. See `validate.retrieve` to create certs obj. Returns: bool: True if valid, False otherwise. """ if len(certs) < 2: warnings.warn('Certificate chain contains < 3 certificates.') return False cert = certs[0] today = datetime.datetime.today() if not today > cert.not_valid_before: warnings.warn('Certificate Not Before date is invalid.') return False if not today < cert.not_valid_after: warnings.warn('Certificate Not After date is invalid.') return False oid_san = x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME ext = cert.extensions.get_extension_for_oid(oid_san) sans = ext.value.get_values_for_type(x509.DNSName) if not 'echo-api.amazon.com' in sans: return False for i in range(len(certs) - 1): if not certs[i].issuer == certs[i + 1].subject: return False return True def signature(cert, sig, body): """Validate data request signature. See `validate.request` for additional info. Args: cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. sig: str. Signature header value sent by request. body: str. HTTPS request body. Returns: bool: True if valid, False otherwise. """ body = six.b(body) sig = base64.decodestring(sig) padder = padding.PKCS1v15() public_key = cert.public_key() try: public_key.verify(sig, body, padder, hashes.SHA1()) return True except InvalidSignature: warnings.warn('Signature verification failed.') return False class Valid(object): """Alexa request validator. Attributes: app_id: str. Skill application ID. url: str. SignatureCertChainUrl header value sent by request. PEM-encoded X.509 certificate chain that Alexa used to sign the message. Used to cache valid url. cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. Used to cache valid cert. """ def __init__(self, app_id=None): """Init validator.""" self.app_id = app_id self.url = None self.cert = None def application_id(self, app_id): """Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise. """ if self.app_id != app_id: warnings.warn('Application ID is invalid.') return False return True def sender(self, body, stamp, url, sig): """Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. stamp: str. Value of timestamp within request object of HTTPS request body. url: str. SignatureCertChainUrl header value sent by request. sig: str. Signature header value sent by request. Returns: bool: True if valid, False otherwise. """ if not timestamp(stamp): return False if self.url != url: if not signature_cert_chain_url(url): return False certs = retrieve(url) if not certs: return False if not cert_chain(certs): return False self.url = url self.cert = certs[0] if not signature(self.cert, sig, body): return False return True def request(self, app_id=None, body=None, stamp=None, url=None, sig=None): """Validate application ID and request is from Alexa.""" if self.app_id: if not self.application_id(app_id): return False if (url or sig): if not (body and stamp and url and sig): raise ValueError('Unable to validate sender, check arguments.') else: if not self.sender(body, stamp, url, sig): return False return True
bmweiner/skillful
skillful/validate.py
_parse_pem_data
python
def _parse_pem_data(pem_data): sep = '-----BEGIN CERTIFICATE-----' cert_chain = [six.b(sep + s) for s in pem_data.split(sep)[1:]] certs = [] load_cert = x509.load_pem_x509_certificate for cert in cert_chain: try: certs.append(load_cert(cert, default_backend())) except ValueError: warnings.warn('Certificate is invalid.') return False return certs
Parse PEM-encoded X.509 certificate chain. Args: pem_data: str. PEM file retrieved from SignatureCertChainUrl. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False.
train
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L98-L121
null
"""Handler for request validation""" import warnings import os import sys import datetime import base64 import six from six.moves.urllib_parse import urlparse from six.moves.urllib.request import urlopen from six.moves.urllib_error import HTTPError from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.exceptions import InvalidSignature import dateutil.parser def timestamp(stamp, tolerance=150): """Validate timestamp specified by request. See `validate.request` for additional info. Args: stamp: str. Time request was made as ISO 8601 timestamp. tolerance: int. Number of seconds request remains valid from timestamp. Returns bool: True if valid, False otherwise. """ try: tolerance = datetime.timedelta(0, tolerance) timestamp_low = dateutil.parser.parse(stamp) timestamp_high = timestamp_low + tolerance now = datetime.datetime.now(timestamp_low.tzinfo) except ValueError: return False return now >= timestamp_low and now <= timestamp_high def signature_cert_chain_url(url): """Validate URL specified by SignatureCertChainUrl. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: bool: True if valid, False otherwise. """ r = urlparse(url) if not r.scheme.lower() == 'https': warnings.warn('Certificate URL scheme is invalid.') return False if not r.hostname.lower() == 's3.amazonaws.com': warnings.warn('Certificate URL hostname is invalid.') return False if not os.path.normpath(r.path).startswith('/echo.api/'): warnings.warn('Certificate URL path is invalid.') return False if r.port and not r.port == 443: warnings.warn('Certificate URL port is invalid.') return False return True def retrieve(url): """Retrieve and parse PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ try: pem_data = urlopen(url).read() except (ValueError, HTTPError): warnings.warn('Certificate URL is invalid.') return False if sys.version >= '3': try: pem_data = pem_data.decode() except(UnicodeDecodeError): warnings.warn('Certificate encoding is not utf-8.') return False return _parse_pem_data(pem_data) def cert_chain(certs): """Validate PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: certs: list. The certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates. See `validate.retrieve` to create certs obj. Returns: bool: True if valid, False otherwise. """ if len(certs) < 2: warnings.warn('Certificate chain contains < 3 certificates.') return False cert = certs[0] today = datetime.datetime.today() if not today > cert.not_valid_before: warnings.warn('Certificate Not Before date is invalid.') return False if not today < cert.not_valid_after: warnings.warn('Certificate Not After date is invalid.') return False oid_san = x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME ext = cert.extensions.get_extension_for_oid(oid_san) sans = ext.value.get_values_for_type(x509.DNSName) if not 'echo-api.amazon.com' in sans: return False for i in range(len(certs) - 1): if not certs[i].issuer == certs[i + 1].subject: return False return True def signature(cert, sig, body): """Validate data request signature. See `validate.request` for additional info. Args: cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. sig: str. Signature header value sent by request. body: str. HTTPS request body. Returns: bool: True if valid, False otherwise. """ body = six.b(body) sig = base64.decodestring(sig) padder = padding.PKCS1v15() public_key = cert.public_key() try: public_key.verify(sig, body, padder, hashes.SHA1()) return True except InvalidSignature: warnings.warn('Signature verification failed.') return False class Valid(object): """Alexa request validator. Attributes: app_id: str. Skill application ID. url: str. SignatureCertChainUrl header value sent by request. PEM-encoded X.509 certificate chain that Alexa used to sign the message. Used to cache valid url. cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. Used to cache valid cert. """ def __init__(self, app_id=None): """Init validator.""" self.app_id = app_id self.url = None self.cert = None def application_id(self, app_id): """Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise. """ if self.app_id != app_id: warnings.warn('Application ID is invalid.') return False return True def sender(self, body, stamp, url, sig): """Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. stamp: str. Value of timestamp within request object of HTTPS request body. url: str. SignatureCertChainUrl header value sent by request. sig: str. Signature header value sent by request. Returns: bool: True if valid, False otherwise. """ if not timestamp(stamp): return False if self.url != url: if not signature_cert_chain_url(url): return False certs = retrieve(url) if not certs: return False if not cert_chain(certs): return False self.url = url self.cert = certs[0] if not signature(self.cert, sig, body): return False return True def request(self, app_id=None, body=None, stamp=None, url=None, sig=None): """Validate application ID and request is from Alexa.""" if self.app_id: if not self.application_id(app_id): return False if (url or sig): if not (body and stamp and url and sig): raise ValueError('Unable to validate sender, check arguments.') else: if not self.sender(body, stamp, url, sig): return False return True
bmweiner/skillful
skillful/validate.py
cert_chain
python
def cert_chain(certs): if len(certs) < 2: warnings.warn('Certificate chain contains < 3 certificates.') return False cert = certs[0] today = datetime.datetime.today() if not today > cert.not_valid_before: warnings.warn('Certificate Not Before date is invalid.') return False if not today < cert.not_valid_after: warnings.warn('Certificate Not After date is invalid.') return False oid_san = x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME ext = cert.extensions.get_extension_for_oid(oid_san) sans = ext.value.get_values_for_type(x509.DNSName) if not 'echo-api.amazon.com' in sans: return False for i in range(len(certs) - 1): if not certs[i].issuer == certs[i + 1].subject: return False return True
Validate PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: certs: list. The certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates. See `validate.retrieve` to create certs obj. Returns: bool: True if valid, False otherwise.
train
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L123-L159
null
"""Handler for request validation""" import warnings import os import sys import datetime import base64 import six from six.moves.urllib_parse import urlparse from six.moves.urllib.request import urlopen from six.moves.urllib_error import HTTPError from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.exceptions import InvalidSignature import dateutil.parser def timestamp(stamp, tolerance=150): """Validate timestamp specified by request. See `validate.request` for additional info. Args: stamp: str. Time request was made as ISO 8601 timestamp. tolerance: int. Number of seconds request remains valid from timestamp. Returns bool: True if valid, False otherwise. """ try: tolerance = datetime.timedelta(0, tolerance) timestamp_low = dateutil.parser.parse(stamp) timestamp_high = timestamp_low + tolerance now = datetime.datetime.now(timestamp_low.tzinfo) except ValueError: return False return now >= timestamp_low and now <= timestamp_high def signature_cert_chain_url(url): """Validate URL specified by SignatureCertChainUrl. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: bool: True if valid, False otherwise. """ r = urlparse(url) if not r.scheme.lower() == 'https': warnings.warn('Certificate URL scheme is invalid.') return False if not r.hostname.lower() == 's3.amazonaws.com': warnings.warn('Certificate URL hostname is invalid.') return False if not os.path.normpath(r.path).startswith('/echo.api/'): warnings.warn('Certificate URL path is invalid.') return False if r.port and not r.port == 443: warnings.warn('Certificate URL port is invalid.') return False return True def retrieve(url): """Retrieve and parse PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ try: pem_data = urlopen(url).read() except (ValueError, HTTPError): warnings.warn('Certificate URL is invalid.') return False if sys.version >= '3': try: pem_data = pem_data.decode() except(UnicodeDecodeError): warnings.warn('Certificate encoding is not utf-8.') return False return _parse_pem_data(pem_data) def _parse_pem_data(pem_data): """Parse PEM-encoded X.509 certificate chain. Args: pem_data: str. PEM file retrieved from SignatureCertChainUrl. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ sep = '-----BEGIN CERTIFICATE-----' cert_chain = [six.b(sep + s) for s in pem_data.split(sep)[1:]] certs = [] load_cert = x509.load_pem_x509_certificate for cert in cert_chain: try: certs.append(load_cert(cert, default_backend())) except ValueError: warnings.warn('Certificate is invalid.') return False return certs def signature(cert, sig, body): """Validate data request signature. See `validate.request` for additional info. Args: cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. sig: str. Signature header value sent by request. body: str. HTTPS request body. Returns: bool: True if valid, False otherwise. """ body = six.b(body) sig = base64.decodestring(sig) padder = padding.PKCS1v15() public_key = cert.public_key() try: public_key.verify(sig, body, padder, hashes.SHA1()) return True except InvalidSignature: warnings.warn('Signature verification failed.') return False class Valid(object): """Alexa request validator. Attributes: app_id: str. Skill application ID. url: str. SignatureCertChainUrl header value sent by request. PEM-encoded X.509 certificate chain that Alexa used to sign the message. Used to cache valid url. cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. Used to cache valid cert. """ def __init__(self, app_id=None): """Init validator.""" self.app_id = app_id self.url = None self.cert = None def application_id(self, app_id): """Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise. """ if self.app_id != app_id: warnings.warn('Application ID is invalid.') return False return True def sender(self, body, stamp, url, sig): """Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. stamp: str. Value of timestamp within request object of HTTPS request body. url: str. SignatureCertChainUrl header value sent by request. sig: str. Signature header value sent by request. Returns: bool: True if valid, False otherwise. """ if not timestamp(stamp): return False if self.url != url: if not signature_cert_chain_url(url): return False certs = retrieve(url) if not certs: return False if not cert_chain(certs): return False self.url = url self.cert = certs[0] if not signature(self.cert, sig, body): return False return True def request(self, app_id=None, body=None, stamp=None, url=None, sig=None): """Validate application ID and request is from Alexa.""" if self.app_id: if not self.application_id(app_id): return False if (url or sig): if not (body and stamp and url and sig): raise ValueError('Unable to validate sender, check arguments.') else: if not self.sender(body, stamp, url, sig): return False return True
bmweiner/skillful
skillful/validate.py
signature
python
def signature(cert, sig, body): body = six.b(body) sig = base64.decodestring(sig) padder = padding.PKCS1v15() public_key = cert.public_key() try: public_key.verify(sig, body, padder, hashes.SHA1()) return True except InvalidSignature: warnings.warn('Signature verification failed.') return False
Validate data request signature. See `validate.request` for additional info. Args: cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. sig: str. Signature header value sent by request. body: str. HTTPS request body. Returns: bool: True if valid, False otherwise.
train
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L161-L185
null
"""Handler for request validation""" import warnings import os import sys import datetime import base64 import six from six.moves.urllib_parse import urlparse from six.moves.urllib.request import urlopen from six.moves.urllib_error import HTTPError from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.exceptions import InvalidSignature import dateutil.parser def timestamp(stamp, tolerance=150): """Validate timestamp specified by request. See `validate.request` for additional info. Args: stamp: str. Time request was made as ISO 8601 timestamp. tolerance: int. Number of seconds request remains valid from timestamp. Returns bool: True if valid, False otherwise. """ try: tolerance = datetime.timedelta(0, tolerance) timestamp_low = dateutil.parser.parse(stamp) timestamp_high = timestamp_low + tolerance now = datetime.datetime.now(timestamp_low.tzinfo) except ValueError: return False return now >= timestamp_low and now <= timestamp_high def signature_cert_chain_url(url): """Validate URL specified by SignatureCertChainUrl. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: bool: True if valid, False otherwise. """ r = urlparse(url) if not r.scheme.lower() == 'https': warnings.warn('Certificate URL scheme is invalid.') return False if not r.hostname.lower() == 's3.amazonaws.com': warnings.warn('Certificate URL hostname is invalid.') return False if not os.path.normpath(r.path).startswith('/echo.api/'): warnings.warn('Certificate URL path is invalid.') return False if r.port and not r.port == 443: warnings.warn('Certificate URL port is invalid.') return False return True def retrieve(url): """Retrieve and parse PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ try: pem_data = urlopen(url).read() except (ValueError, HTTPError): warnings.warn('Certificate URL is invalid.') return False if sys.version >= '3': try: pem_data = pem_data.decode() except(UnicodeDecodeError): warnings.warn('Certificate encoding is not utf-8.') return False return _parse_pem_data(pem_data) def _parse_pem_data(pem_data): """Parse PEM-encoded X.509 certificate chain. Args: pem_data: str. PEM file retrieved from SignatureCertChainUrl. Returns: list or bool: If url is valid, returns the certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates where certs[0] is the first certificate in the file; if url is invalid, returns False. """ sep = '-----BEGIN CERTIFICATE-----' cert_chain = [six.b(sep + s) for s in pem_data.split(sep)[1:]] certs = [] load_cert = x509.load_pem_x509_certificate for cert in cert_chain: try: certs.append(load_cert(cert, default_backend())) except ValueError: warnings.warn('Certificate is invalid.') return False return certs def cert_chain(certs): """Validate PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: certs: list. The certificate chain as a list of cryptography.hazmat.backends.openssl.x509._Certificate certificates. See `validate.retrieve` to create certs obj. Returns: bool: True if valid, False otherwise. """ if len(certs) < 2: warnings.warn('Certificate chain contains < 3 certificates.') return False cert = certs[0] today = datetime.datetime.today() if not today > cert.not_valid_before: warnings.warn('Certificate Not Before date is invalid.') return False if not today < cert.not_valid_after: warnings.warn('Certificate Not After date is invalid.') return False oid_san = x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME ext = cert.extensions.get_extension_for_oid(oid_san) sans = ext.value.get_values_for_type(x509.DNSName) if not 'echo-api.amazon.com' in sans: return False for i in range(len(certs) - 1): if not certs[i].issuer == certs[i + 1].subject: return False return True class Valid(object): """Alexa request validator. Attributes: app_id: str. Skill application ID. url: str. SignatureCertChainUrl header value sent by request. PEM-encoded X.509 certificate chain that Alexa used to sign the message. Used to cache valid url. cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. Used to cache valid cert. """ def __init__(self, app_id=None): """Init validator.""" self.app_id = app_id self.url = None self.cert = None def application_id(self, app_id): """Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise. """ if self.app_id != app_id: warnings.warn('Application ID is invalid.') return False return True def sender(self, body, stamp, url, sig): """Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. stamp: str. Value of timestamp within request object of HTTPS request body. url: str. SignatureCertChainUrl header value sent by request. sig: str. Signature header value sent by request. Returns: bool: True if valid, False otherwise. """ if not timestamp(stamp): return False if self.url != url: if not signature_cert_chain_url(url): return False certs = retrieve(url) if not certs: return False if not cert_chain(certs): return False self.url = url self.cert = certs[0] if not signature(self.cert, sig, body): return False return True def request(self, app_id=None, body=None, stamp=None, url=None, sig=None): """Validate application ID and request is from Alexa.""" if self.app_id: if not self.application_id(app_id): return False if (url or sig): if not (body and stamp and url and sig): raise ValueError('Unable to validate sender, check arguments.') else: if not self.sender(body, stamp, url, sig): return False return True
bmweiner/skillful
skillful/validate.py
Valid.application_id
python
def application_id(self, app_id): if self.app_id != app_id: warnings.warn('Application ID is invalid.') return False return True
Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise.
train
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L204-L218
null
class Valid(object): """Alexa request validator. Attributes: app_id: str. Skill application ID. url: str. SignatureCertChainUrl header value sent by request. PEM-encoded X.509 certificate chain that Alexa used to sign the message. Used to cache valid url. cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. Used to cache valid cert. """ def __init__(self, app_id=None): """Init validator.""" self.app_id = app_id self.url = None self.cert = None def sender(self, body, stamp, url, sig): """Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. stamp: str. Value of timestamp within request object of HTTPS request body. url: str. SignatureCertChainUrl header value sent by request. sig: str. Signature header value sent by request. Returns: bool: True if valid, False otherwise. """ if not timestamp(stamp): return False if self.url != url: if not signature_cert_chain_url(url): return False certs = retrieve(url) if not certs: return False if not cert_chain(certs): return False self.url = url self.cert = certs[0] if not signature(self.cert, sig, body): return False return True def request(self, app_id=None, body=None, stamp=None, url=None, sig=None): """Validate application ID and request is from Alexa.""" if self.app_id: if not self.application_id(app_id): return False if (url or sig): if not (body and stamp and url and sig): raise ValueError('Unable to validate sender, check arguments.') else: if not self.sender(body, stamp, url, sig): return False return True
bmweiner/skillful
skillful/validate.py
Valid.sender
python
def sender(self, body, stamp, url, sig): if not timestamp(stamp): return False if self.url != url: if not signature_cert_chain_url(url): return False certs = retrieve(url) if not certs: return False if not cert_chain(certs): return False self.url = url self.cert = certs[0] if not signature(self.cert, sig, body): return False return True
Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. stamp: str. Value of timestamp within request object of HTTPS request body. url: str. SignatureCertChainUrl header value sent by request. sig: str. Signature header value sent by request. Returns: bool: True if valid, False otherwise.
train
https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L220-L258
[ "def signature(cert, sig, body):\n \"\"\"Validate data request signature.\n\n See `validate.request` for additional info.\n\n Args:\n cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon\n signing certificate.\n sig: str. Signature header value sent by request.\...
class Valid(object): """Alexa request validator. Attributes: app_id: str. Skill application ID. url: str. SignatureCertChainUrl header value sent by request. PEM-encoded X.509 certificate chain that Alexa used to sign the message. Used to cache valid url. cert: cryptography.hazmat.backends.openssl.x509._Certificate. The Amazon signing certificate. Used to cache valid cert. """ def __init__(self, app_id=None): """Init validator.""" self.app_id = app_id self.url = None self.cert = None def application_id(self, app_id): """Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise. """ if self.app_id != app_id: warnings.warn('Application ID is invalid.') return False return True def request(self, app_id=None, body=None, stamp=None, url=None, sig=None): """Validate application ID and request is from Alexa.""" if self.app_id: if not self.application_id(app_id): return False if (url or sig): if not (body and stamp and url and sig): raise ValueError('Unable to validate sender, check arguments.') else: if not self.sender(body, stamp, url, sig): return False return True