<commit_before>import sublime
import sublime_plugin
import re
import subprocess
from collections import defaultdict
import os
import threading
import tempfile

PACKAGE_SETTINGS = sublime.load_settings('tidy.sublime-settings')

MY_BLAME_REGION_KEY = 'sublime_tidy_regions_mine'
OTHERS_BLAME_REGION_KEY = 'sublime_tidy_regions_others'
STATUS_KEY = 'sublime_tidy_status'

PEP8_REX = re.compile(r'\w+:(\d+):(\d+):\s(\w+)\s(.+)$', re.MULTILINE)
PYLINT_REX = re.compile(r'^(\w):\s+(\d+),\s*(\d+):\s(.+)$', re.MULTILINE)
PYFLAKES_REX = re.compile(r'\w+:(\d+):\s(.+)$', re.MULTILINE)
JSHINT_REX = re.compile(r'\w+: line (\d+), col (\d+),\s(.+)$', re.MULTILINE)
BLAME_NAME_REX = re.compile(r'\(([\w\s]+)\d{4}')

MY_NAME_REX = re.compile(
    r'{}|Not Committed Yet'.format(PACKAGE_SETTINGS.get('my_name_rex')),
    re.I
)

# TODO: Provide report of all modified files
# TODO: Make executable paths configurable
# TODO: Deal with changing views: only one view's data can be stored at a time

class Issue(object):
    """Represents a single linter issue."""
    def __init__(self, line, column, code, message, reporter):
        self.line = int(line)
        if column:
            self.column = int(column)
        else:
            self.column = column
        self.code = code
        self.message = message
        self.reporter = reporter
        self.region = None

    def __str__(self):
        reporter = '[{}]'.format(self.reporter)
        location = '{}:{}'.format(self.line, self.column)

        return '{:<5} {:<10} {}'.format(
            location,
            reporter,
            self.message
        )

    def blamed_str(self, blame_name):
        reporter = '[{}]'.format(self.reporter)
        location = '{}:{}'.format(self.line, self.column)
        blame_str = '[{}]'.format(blame_name)

        return '{:<5} {:<10} {} {}'.format(
            location,
            reporter,
            blame_str,
            self.message
        )

    def set_region(self, region):
        self.region = region

def run(cmd):
    proc = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True
    )
    out, err = proc.communicate()
    return out.decode('utf-8') + err.decode('utf-8')

def pylint(path):
    """Pylint issues."""
    cmd = "/usr/local/bin/pylint --output-format=text '{}'".format(path)
    output = run(cmd)
    hits = PYLINT_REX.findall(output)
    results = []
    for hit in hits:
        results.append(
            Issue(
                line=hit[1],
                column=hit[2],
                message=hit[3],
                code=hit[0],
                reporter='Pylint'
            )
        )
    return results

def pep8(path):
    """PEP8 issues."""
    output = run("/usr/local/bin/pep8 '{}'".format(path))
    hits = PEP8_REX.findall(output)
    results = []
    for hit in hits:
        results.append(
            Issue(
                line=hit[0],
                column=hit[1],
                code=hit[2],
                message=hit[3],
                reporter='PEP8'
            )
        )
    return results

def pyflakes(path):
    """PyFlakes issues."""
    cmd = "/usr/local/bin/pyflakes '{}'".format(path)
    output = run(cmd)
    hits = PYFLAKES_REX.findall(output)
    results = []
    for hit in hits:
        results.append(
            Issue(
                line=hit[0],
                column='',
                code='',
                message=hit[1],
                reporter='Pyflakes'
            )
        )
    return results

def jshint(path):
    """JsHint issues."""
    cmd = 'jshint {}'.format(path)
    output = run(cmd)
    hits = JSHINT_REX.findall(output)
    results = []
    for hit in hits:
        results.append(
            Issue(
                line=hit[0],
                column=hit[1],
                code='',
                message=hit[2],
                reporter='JSHint'
            )
        )
    return results

def diff_files():
    output = (
        subprocess.check_output(['git', 'diff', '--name-only', 'master..']) +
        subprocess.check_output(['git', 'diff', '--name-only'])
    )
    return [i.decode('utf-8') for i in output.splitlines() if i]

def git_name():
    return subprocess.check_output(['git', 'config', 'user.name']).strip()

def blame(path):
    working_dir = os.path.split(path)[0]
    proc = subprocess.Popen(
        ['git', 'blame', path],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        cwd=working_dir
    )
    out, err = proc.communicate()
    blame_lines = (out + err).splitlines()
    result = {}
    for i, line in enumerate(blame_lines):
        match = BLAME_NAME_REX.search(line.decode('utf-8'))
        if match:
            result[i + 1] = match.group(1).strip()
        else:
            result[i + 1] = None
    return result

def run_and_apply_tidy(view, use_buffer=False, force=False):
    if not view.is_dirty() and not force:
        return

    view.run_command('clear_tidy')
    view.set_status(STATUS_KEY, 'Tidy: Evaluating...')

    current_file = view.file_name()
    if not current_file:
        return

    print('current_file: {0}'.format(current_file))
    if use_buffer:
        root, ext = os.path.splitext(current_file)
        tf = tempfile.NamedTemporaryFile(mode='w', suffix=ext)
        text = view.substr(sublime.Region(0, view.size()))
        tf.write(text)
        issues.set_path(current_file, lint_override_target=tf.name)
        tf.close()
    else:
        issues.set_path(current_file)

    lines = view.lines(sublime.Region(0, view.size()))

    my_regions = []
    others_regions = []
    for issue in issues.issues:
        line_region = lines[issue.line - 1]
        issue_region = sublime.Region(
            line_region.begin(),
            line_region.begin()
        )
        issue.set_region(issue_region)
        if MY_NAME_REX.search(issues.blame(issue)):
            my_regions.append(issue_region)
        else:
            others_regions.append(issue_region)

    view.add_regions(
        MY_BLAME_REGION_KEY,
        my_regions,
        'keyword',
        'dot'
    )
    view.add_regions(
        OTHERS_BLAME_REGION_KEY,
        others_regions,
        'string',
        'dot'
    )

    count = len(issues.issues)
    if count:
        msg = 'Untidy ({})'.format(count)
    else:
        msg = 'Tidy!'
    view.set_status(STATUS_KEY, msg)

class Issues(object):
    """Collection that holds all lint issues."""
    def __init__(self):
        self.path = None
        self.issues = []
        self.set_out_of_date(True)

    def set_path(self, path, lint_override_target=None):
        self.update_issues(lint_override_target or path)
        self.blame_by_line = blame(path)

    def _append_issues(self, issues_func, path):
        self.issues += issues_func(path)

    def update_issues(self, path):
        """Run linters and save results."""
        self.issues = []

        root, ext = os.path.splitext(path)
        if ext == '.py':
            issue_funcs = [pep8, pylint, pyflakes]
        elif ext in ['.js', '.json', '.sublime-settings']:
            issue_funcs = [jshint]

        threads = []
        for func in issue_funcs:
            t = threading.Thread(
                target=self._append_issues,
                args=[func, path]
            )
            threads.append(t)
            t.start()

        for t in threads:
            t.join(10)

        self.set_out_of_date(False)

    def issues_by_line(self):
        d = defaultdict(list)
        for issue in self.issues:
            d[issue.line].append(issue)
        return d

    def issues_by_region(self):
        d = defaultdict(list)
        for issue in self.issues:
            d[issue.region].append(issue)
        return d

    def blame(self, issue):
        return self.blame_by_line.get(issue.line, None)

    @property
    def out_of_date(self):
        return self._out_of_date

    def set_out_of_date(self, out_of_date=True):
        self._out_of_date = out_of_date

issues = Issues()

class TidyBaseTextCommand(sublime_plugin.TextCommand):
    def _prompt_refresh(self):
        if sublime.ok_cancel_dialog('Tidy needs to refresh itself.'):
            # TODO: This doesn't work right because threads.
            self.view.run_command('run_tidy')
            return True
        return False

    def _confirm_up_to_date(self):
        if issues.out_of_date:
            return self._prompt_refresh()
        else:
            return True

class ShowTidyIssuesCommand(TidyBaseTextCommand):
    def run(self, edit):
        if not self._confirm_up_to_date():
            return

        line_regions = self.view.lines(
            sublime.Region(0, self.view.sel()[0].begin() + 1)
        )
        line_no = len(line_regions)
        issue_strs = [
            i.blamed_str(issues.blame(i)) for i in issues.issues
            if i.line == line_no
        ]
        w = sublime.active_window()
        panel = w.create_output_panel('tidy_issues_panel')
        panel.replace(
            edit,
            sublime.Region(0, panel.size()),
            '\n'.join(issue_strs)
        )
        w.run_command('show_panel', {'panel': 'output.tidy_issues_panel'})

        sel = self.view.sel()
        sel.clear()
        sel.add(line_regions[-1])

class JumpToNextUntidyCommand(TidyBaseTextCommand):
    def run(self, edit):
        if not self._confirm_up_to_date():
            return

        if not issues.issues:
            return

        current_line = len(
            self.view.lines(sublime.Region(0, self.view.sel()[0].begin() + 1))
        )
        issues_by_line = issues.issues_by_line()
        issues_line_nos = sorted(issues_by_line.keys())
        remainder_line_nos = [l for l in issues_line_nos if l > current_line]
        try:
            if remainder_line_nos:
                target_line = remainder_line_nos[0]
            else:
                target_line = issues_line_nos[0]
        except IndexError as e:
            print(
                'Failed to find target_line {} in:\n{}\n{}'.format(
                    0,
                    remainder_line_nos,
                    issues_line_nos
                )
            )
            raise e

        line_regions = self.view.lines(sublime.Region(0, self.view.size()))
        line_region = line_regions[target_line - 1]
        self.view.show_at_center(line_region.begin())
        sel = self.view.sel()
        sel.clear()
        sel.add(line_region)
        self.view.run_command('show_tidy_issues')

class ClearTidyCommand(sublime_plugin.TextCommand):
    """Clear all regions and status."""
    def run(self, edit):
        self.view.erase_regions(MY_BLAME_REGION_KEY)
        self.view.erase_regions(OTHERS_BLAME_REGION_KEY)
        self.view.erase_status(STATUS_KEY)

class RunTidyDiffCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        print('diff_files(): {0}'.format(diff_files()))

class RunTidyCommand(sublime_plugin.TextCommand):
    """Run all linters and apply results."""
    def run(self, edit):
        try:
            if self.run_thread.is_alive():
                return
        except AttributeError:
            pass
        self.run_thread = threading.Thread(
            target=run_and_apply_tidy,
            kwargs=dict(
                view=self.view,
                force=True,
            )
        )
        self.run_thread.start()

class TidyListener(sublime_plugin.EventListener):
    """Determines when to update/clear results."""

    @property
    def active_file(self):
        return sublime.active_window().active_view().file_name()

    def clear(self, view):
        view.run_command('clear_tidy')

    def cancel_run_thread(self):
        try:
            self.delayed_run.cancel()
        except AttributeError:
            pass

    def on_post_save_async(self, view):
        self.cancel_run_thread()
        run_and_apply_tidy(view)

    def on_load_async(self, view):
        run_and_apply_tidy(view, force=True)

    # Enable this if we want to save the buffer into a temp file.
    # Otherwise it's pointless.
    def on_modified_async(self, view):
        self.cancel_run_thread()
        self.delayed_run = threading.Timer(
            5,
            run_and_apply_tidy,
            kwargs={
                'view': view,
                'use_buffer': True,
            }
        )
        self.delayed_run.start()
        view.set_status(STATUS_KEY, 'Tidy: Waiting...')
<commit_msg>A bit of grooming to the event listener. About to experiment with a queue.<commit_after>import sublime
import sublime_plugin
import re
import subprocess
from collections import defaultdict
import os
import threading
import tempfile
import queue

PACKAGE_SETTINGS = sublime.load_settings('tidy.sublime-settings')

MY_BLAME_REGION_KEY = 'sublime_tidy_regions_mine'
OTHERS_BLAME_REGION_KEY = 'sublime_tidy_regions_others'
STATUS_KEY = 'sublime_tidy_status'

PEP8_REX = re.compile(r'\w+:(\d+):(\d+):\s(\w+)\s(.+)$', re.MULTILINE)
PYLINT_REX = re.compile(r'^(\w):\s+(\d+),\s*(\d+):\s(.+)$', re.MULTILINE)
PYFLAKES_REX = re.compile(r'\w+:(\d+):\s(.+)$', re.MULTILINE)
JSHINT_REX = re.compile(r'\w+: line (\d+), col (\d+),\s(.+)$', re.MULTILINE)
BLAME_NAME_REX = re.compile(r'\(([\w\s]+)\d{4}')

MY_NAME_REX = re.compile(
    r'{}|Not Committed Yet'.format(PACKAGE_SETTINGS.get('my_name_rex')),
    re.I
)

# TODO: Provide report of all modified files
# TODO: Make executable paths configurable
# TODO: Deal with changing views: only one view's data can be stored at a time
# TODO: If panel is up during update, update panel contents

class Issue(object):
    """Represents a single linter issue."""
    def __init__(self, line, column, code, message, reporter):
        self.line = int(line)
        if column:
            self.column = int(column)
        else:
            self.column = column
        self.code = code
        self.message = message
        self.reporter = reporter
        self.region = None

    def __str__(self):
        reporter = '[{}]'.format(self.reporter)
        location = '{}:{}'.format(self.line, self.column)

        return '{:<5} {:<10} {}'.format(
            location,
            reporter,
            self.message
        )

    def blamed_str(self, blame_name):
        reporter = '[{}]'.format(self.reporter)
        location = '{}:{}'.format(self.line, self.column)
        blame_str = '[{}]'.format(blame_name)

        return '{:<5} {:<10} {} {}'.format(
            location,
            reporter,
            blame_str,
            self.message
        )

    def set_region(self, region):
        self.region = region

def run(cmd):
    proc = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True
    )
    out, err = proc.communicate()
    return out.decode('utf-8') + err.decode('utf-8')

def pylint(path):
    """Pylint issues."""
    cmd = "/usr/local/bin/pylint --output-format=text '{}'".format(path)
    output = run(cmd)
    hits = PYLINT_REX.findall(output)
    results = []
    for hit in hits:
        results.append(
            Issue(
                line=hit[1],
                column=hit[2],
                message=hit[3],
                code=hit[0],
                reporter='Pylint'
            )
        )
    return results

def pep8(path):
    """PEP8 issues."""
    output = run("/usr/local/bin/pep8 '{}'".format(path))
    hits = PEP8_REX.findall(output)
    results = []
    for hit in hits:
        results.append(
            Issue(
                line=hit[0],
                column=hit[1],
                code=hit[2],
                message=hit[3],
                reporter='PEP8'
            )
        )
    return results

def pyflakes(path):
    """PyFlakes issues."""
    cmd = "/usr/local/bin/pyflakes '{}'".format(path)
    output = run(cmd)
    hits = PYFLAKES_REX.findall(output)
    results = []
    for hit in hits:
        results.append(
            Issue(
                line=hit[0],
                column='',
                code='',
                message=hit[1],
                reporter='Pyflakes'
            )
        )
    return results

def jshint(path):
    """JsHint issues."""
    cmd = 'jshint {}'.format(path)
    output = run(cmd)
    hits = JSHINT_REX.findall(output)
    results = []
    for hit in hits:
        results.append(
            Issue(
                line=hit[0],
                column=hit[1],
                code='',
                message=hit[2],
                reporter='JSHint'
            )
        )
    return results

def diff_files():
    output = (
        subprocess.check_output(['git', 'diff', '--name-only', 'master..']) +
        subprocess.check_output(['git', 'diff', '--name-only'])
    )
    return [i.decode('utf-8') for i in output.splitlines() if i]

def git_name():
    return subprocess.check_output(['git', 'config', 'user.name']).strip()

def blame(path):
    working_dir = os.path.split(path)[0]
    proc = subprocess.Popen(
        ['git', 'blame', path],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        cwd=working_dir
    )
    out, err = proc.communicate()
    blame_lines = (out + err).splitlines()
    result = {}
    for i, line in enumerate(blame_lines):
        match = BLAME_NAME_REX.search(line.decode('utf-8'))
        if match:
            result[i + 1] = match.group(1).strip()
        else:
            result[i + 1] = None
    return result

class Issues(object):
    """Collection that holds all lint issues."""
    def __init__(self):
        self.path = None
        self.issues = []
        self.set_out_of_date(True)
        self.queue = queue.Queue()

    def set_path(self, path, lint_override_target=None):
        self.update_issues(lint_override_target or path)
        self.blame_by_line = blame(path)

    def _append_issues(self, issues_func, path):
        self.issues += issues_func(path)

    def update_issues(self, path):
        """Run linters and save results."""
        self.issues = []

        root, ext = os.path.splitext(path)
        if ext == '.py':
            issue_funcs = [pep8, pylint, pyflakes]
        elif ext in ['.js', '.json', '.sublime-settings']:
            issue_funcs = [jshint]

        threads = []
        for func in issue_funcs:
            t = threading.Thread(
                target=self._append_issues,
                args=[func, path]
            )
            threads.append(t)
            t.start()

        for t in threads:
            t.join(10)

        self.set_out_of_date(False)

    def issues_by_line(self):
        d = defaultdict(list)
        for issue in self.issues:
            d[issue.line].append(issue)
        return d

    def issues_by_region(self):
        d = defaultdict(list)
        for issue in self.issues:
            d[issue.region].append(issue)
        return d

    def blame(self, issue):
        return self.blame_by_line.get(issue.line, None)

    @property
    def out_of_date(self):
        return self._out_of_date

    def set_out_of_date(self, out_of_date=True):
        self._out_of_date = out_of_date

issues = Issues()

def run_and_apply_tidy(view, use_buffer=False, force=False):
    if not view.is_dirty() and not force:
        print('Tidy: Clean and unforced. Aborting.')
        return

    view.run_command('clear_tidy')
    view.set_status(STATUS_KEY, 'Tidy: Evaluating...')

    current_file = view.file_name()
    if not current_file:
        return

    if use_buffer:
        root, ext = os.path.splitext(current_file)
        tf = tempfile.NamedTemporaryFile(mode='w', suffix=ext)
        text = view.substr(sublime.Region(0, view.size()))
        tf.write(text)
        issues.set_path(current_file, lint_override_target=tf.name)
        tf.close()
    else:
        issues.set_path(current_file)

    lines = view.lines(sublime.Region(0, view.size()))

    my_regions = []
    others_regions = []
    for issue in issues.issues:
        line_region = lines[issue.line - 1]
        issue_region = sublime.Region(
            line_region.begin(),
            line_region.begin()
        )
        issue.set_region(issue_region)
        if MY_NAME_REX.search(issues.blame(issue)):
            my_regions.append(issue_region)
        else:
            others_regions.append(issue_region)

    view.add_regions(
        MY_BLAME_REGION_KEY,
        my_regions,
        'keyword',
        'dot'
    )
    view.add_regions(
        OTHERS_BLAME_REGION_KEY,
        others_regions,
        'string',
        'dot'
    )

    count = len(issues.issues)
    if count:
        msg = 'Untidy ({})'.format(count)
    else:
        msg = 'Tidy!'
    view.set_status(STATUS_KEY, msg)

class TidyBaseTextCommand(sublime_plugin.TextCommand):
    def _prompt_refresh(self):
        if sublime.ok_cancel_dialog('Tidy needs to refresh itself.'):
            # TODO: This doesn't work right because threads.
            self.view.run_command('run_tidy')
            return True
        return False

    def _confirm_up_to_date(self):
        if issues.out_of_date:
            return self._prompt_refresh()
        else:
            return True

class ShowTidyIssuesCommand(TidyBaseTextCommand):
    def run(self, edit):
        if not self._confirm_up_to_date():
            return

        line_regions = self.view.lines(
            sublime.Region(0, self.view.sel()[0].begin() + 1)
        )
        line_no = len(line_regions)
        issue_strs = [
            i.blamed_str(issues.blame(i)) for i in issues.issues
            if i.line == line_no
        ]
        w = sublime.active_window()
        panel = w.create_output_panel('tidy_issues_panel')
        panel.replace(
            edit,
            sublime.Region(0, panel.size()),
            '\n'.join(issue_strs)
        )
        w.run_command('show_panel', {'panel': 'output.tidy_issues_panel'})

        sel = self.view.sel()
        sel.clear()
        sel.add(line_regions[-1])

class JumpToNextUntidyCommand(TidyBaseTextCommand):
    def run(self, edit):
        # TODO: Run tidy if necessary
        if not issues.issues:
            return

        current_line = len(
            self.view.lines(sublime.Region(0, self.view.sel()[0].begin() + 1))
        )
        issues_by_line = issues.issues_by_line()
        issues_line_nos = sorted(issues_by_line.keys())
        remainder_line_nos = [l for l in issues_line_nos if l > current_line]
        try:
            if remainder_line_nos:
                target_line = remainder_line_nos[0]
            else:
                target_line = issues_line_nos[0]
        except IndexError as e:
            print(
                'Failed to find target_line {} in:\n{}\n{}'.format(
                    0,
                    remainder_line_nos,
                    issues_line_nos
                )
            )
            raise e

        line_regions = self.view.lines(sublime.Region(0, self.view.size()))
        line_region = line_regions[target_line - 1]
        self.view.show_at_center(line_region.begin())
        sel = self.view.sel()
        sel.clear()
        sel.add(line_region)
        self.view.run_command('show_tidy_issues')

class ClearTidyCommand(sublime_plugin.TextCommand):
    """Clear all regions and status."""
    def run(self, edit):
        self.view.erase_regions(MY_BLAME_REGION_KEY)
        self.view.erase_regions(OTHERS_BLAME_REGION_KEY)
        self.view.erase_status(STATUS_KEY)

class RunTidyDiffCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        print('diff_files(): {0}'.format(diff_files()))

class RunTidyCommand(sublime_plugin.TextCommand):
    """Run all linters and apply results."""
    def run(self, edit):
        try:
            if self.run_thread.is_alive():
                return
        except AttributeError:
            pass
        self.run_thread = threading.Thread(
            target=run_and_apply_tidy,
            kwargs=dict(
                view=self.view,
                force=True,
            )
        )
        self.run_thread.start()

class TidyListener(sublime_plugin.EventListener):
    """Determines when to update/clear results."""

    @property
    def active_file(self):
        return sublime.active_window().active_view().file_name()

    def clear(self, view):
        view.run_command('clear_tidy')

    @property
    def is_running(self):
        try:
            return self.run_thread.is_alive()
        except AttributeError:
            return False

    def cancel_delayed_run_thread(self):
        try:
            self.delayed_run_thread.cancel()
        except AttributeError:
            pass

    def on_post_save_async(self, view):
        if self.is_running:
            return

        self.cancel_delayed_run_thread()
        self.run_thread = threading.Thread(
            target=run_and_apply_tidy,
            kwargs={
                'view': view,
                'force': True,
            }
        )
        self.run_thread.start()

    def on_load_async(self, view):
        run_and_apply_tidy(view, force=True)

    def on_modified_async(self, view):
        self.cancel_delayed_run_thread()
        self.delayed_run_thread = threading.Timer(
            5,
            run_and_apply_tidy,
            kwargs={
                'view': view,
                'use_buffer': True,
            }
        )
        self.delayed_run_thread.start()
        view.set_status(STATUS_KEY, 'Tidy: Waiting...')

    def on_deactivated_async(self, view):
        issues.set_out_of_date(True)
<|endoftext|>


<commit_before>#!/usr/bin/env python
#Copyright (c) 2007-8, Playful Invention Company
#Copyright (c) 2008-10, Walter Bender

#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:

#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.

#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.

import pygtk
pygtk.require('2.0')
import gtk
import gobject
import os
import os.path
import locale
from gettext import gettext as _
from taconstants import OVERLAY_LAYER
from tautils import data_to_string, data_from_string
from tawindow import TurtleArtWindow

"""
Make a path if it doesn't previously exist
"""
def makepath(path):

    from os import makedirs
    from os.path import normpath, dirname, exists

    dpath = normpath(dirname(path))
    if not exists(dpath): makedirs(dpath)

"""
Launch Turtle Art from outside of Sugar
$ python turtleart.py

Caveats:
    * no Sugar toolbars
    * no Sugar Journal access
    * no Sugar sharing
"""
class TurtleMain():
    def __init__(self):
        self.i = 0
        self.scale=2.0
        tw = None
        # make sure Sugar paths are present
        tapath = os.path.join(os.environ['HOME'],'.sugar','default', \
                              'org.laptop.TurtleArtActivity')
        map (makepath, (os.path.join(tapath,'data/'), \
                        os.path.join(tapath,'instance/')))

        """
        Find closest match for the user's $LANG
        """
        lang = locale.getdefaultlocale()[0]
        if not lang:
            lang = 'en'
        lang = lang[0:2]

        win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        win.maximize()
        win.set_title(_("Turtle Art"))
        win.connect("delete_event", lambda w,e: gtk.main_quit())

        menu = gtk.Menu()

        menu_items = gtk.MenuItem(_("Open"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_open_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Save"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_save_cb)
        menu_items.show()

        activity_menu = gtk.MenuItem(_("File"))
        activity_menu.show()
        activity_menu.set_submenu(menu)

        menu = gtk.Menu()

        menu_items = gtk.MenuItem(_("Cartesian coordinates"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_cartesian_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Polar coordinates"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_polar_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_('Rescale coordinates'))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_rescale_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Grow blocks"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_resize_cb, 1.5)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Shrink blocks"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_resize_cb, 0.667)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Reset block size"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_resize_cb, -1)
        menu_items.show()

        view_menu = gtk.MenuItem(_("View"))
        view_menu.show()
        view_menu.set_submenu(menu)

        menu = gtk.Menu()

        menu_items = gtk.MenuItem(_("Copy"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_copy_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Paste"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_paste_cb)
        menu_items.show()

        edit_menu = gtk.MenuItem(_("Edit"))
        edit_menu.show()
        edit_menu.set_submenu(menu)

        menu = gtk.Menu()

        menu_items = gtk.MenuItem(_("Show palette"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_palette_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Hide palette"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_hide_palette_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Show/hide blocks"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_hideshow_cb)
        menu_items.show()

        tool_menu = gtk.MenuItem(_("Tools"))
        tool_menu.show()
        tool_menu.set_submenu(menu)

        menu = gtk.Menu()

        menu_items = gtk.MenuItem(_("Clean"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_eraser_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Run"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_run_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Step"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_step_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Debug"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_trace_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Stop"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_stop_cb)
        menu_items.show()

        turtle_menu = gtk.MenuItem(_("Turtle"))
        turtle_menu.show()
        turtle_menu.set_submenu(menu)

        vbox = gtk.VBox(False, 0)
        win.add(vbox)
        vbox.show()

        menu_bar = gtk.MenuBar()
        vbox.pack_start(menu_bar, False, False, 2)
        menu_bar.show()

        canvas = gtk.DrawingArea()
        vbox.pack_end(canvas, True, True)
        canvas.show()

        menu_bar.append(activity_menu)
        menu_bar.append(edit_menu)
        menu_bar.append(view_menu)
        menu_bar.append(tool_menu)
        menu_bar.append(turtle_menu)

        win.show_all()
        self.tw = TurtleArtWindow(canvas, os.path.abspath('.'), lang)
        self.tw.win = win

    def _do_open_cb(self, widget):
        self.tw.load_file(True)

    def _do_save_cb(self, widget):
        self.tw.save_file()

    def _do_resize_cb(self, widget, factor):
        if factor == -1:
            self.tw.block_scale = 2.0
        else:
            self.tw.block_scale *= factor
        self.tw.resize_blocks()

    def _do_cartesian_cb(self, button):
        if self.tw.cartesian is True:
            if self.tw.coord_scale == 1:
                self.tw.overlay_shapes['Cartesian_labeled'].hide()
            else:
                self.tw.overlay_shapes['Cartesian'].hide()
            self.tw.cartesian = False
        else:
            if self.tw.coord_scale == 1:
                self.tw.overlay_shapes['Cartesian_labeled'].set_layer(
                                                              OVERLAY_LAYER)
            else:
                self.tw.overlay_shapes['Cartesian'].set_layer(OVERLAY_LAYER)
            self.tw.cartesian = True

    def _do_polar_cb(self, button):
        if self.tw.polar is True:
            self.tw.overlay_shapes['polar'].hide()
            self.tw.polar = False
        else:
            self.tw.overlay_shapes['polar'].set_layer(OVERLAY_LAYER)
            self.tw.polar = True

    def _do_rescale_cb(self, button):
        if self.tw.coord_scale == 1:
            self.tw.coord_scale = self.tw.height/200
            self.tw.eraser_button()
            if self.tw.cartesian is True:
                self.tw.overlay_shapes['Cartesian_labeled'].hide()
                self.tw.overlay_shapes['Cartesian'].set_layer(OVERLAY_LAYER)
        else:
            self.tw.coord_scale = 1
            self.tw.eraser_button()
            if self.tw.cartesian is True:
                self.tw.overlay_shapes['Cartesian'].hide()
                self.tw.overlay_shapes['Cartesian_labeled'].set_layer(
                                                              OVERLAY_LAYER)

    def _do_palette_cb(self, widget):
        self.tw.show_palette(self.i)
        self.i += 1
        if self.i == len(self.tw.palettes):
            self.i = 0

    def _do_hide_palette_cb(self, widget):
        self.tw.hide_palette()

    def _do_hideshow_cb(self, widget):
        self.tw.hideshow_button()

    def _do_eraser_cb(self, widget):
        self.tw.eraser_button()
        return

    def _do_run_cb(self, widget):
        self.tw.lc.trace = 0
        self.tw.run_button(0)
        return

    def _do_step_cb(self, widget):
        self.tw.lc.trace = 0
        self.tw.run_button(3)
        return

    def _do_trace_cb(self, widget):
        self.tw.lc.trace = 1
        self.tw.run_button(6)
        return

    def _do_stop_cb(self, widget):
        self.tw.lc.trace = 0
        self.tw.stop_button()
        return

    def _do_copy_cb(self, button):
        clipBoard = gtk.Clipboard()
        data = self.tw.assemble_data_to_save(False, False)
        if data is not []:
            text = data_to_string(data)
            clipBoard.set_text(text)

    def _do_paste_cb(self, button):
        clipBoard = gtk.Clipboard()
        text = clipBoard.wait_for_text()
        if text is not None:
            self.tw.process_data(data_from_string(text))

def main():
    gtk.main()
    return 0

if __name__ == "__main__":
    TurtleMain()
    main()

<commit_msg>adding start block on load<commit_after>#!/usr/bin/env python
#Copyright (c) 2007-8, Playful Invention Company
#Copyright (c) 2008-10, Walter Bender

#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:

#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.

#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.

import pygtk
pygtk.require('2.0')
import gtk
import gobject
import os
import os.path
import locale
from gettext import gettext as _
from taconstants import OVERLAY_LAYER
from tautils import data_to_string, data_from_string
from tawindow import TurtleArtWindow

"""
Make a path if it doesn't previously exist
"""
def makepath(path):

    from os import makedirs
    from os.path import normpath, dirname, exists

    dpath = normpath(dirname(path))
    if not exists(dpath): makedirs(dpath)

"""
Launch Turtle Art from outside of Sugar
$ python turtleart.py

Caveats:
    * no Sugar toolbars
    * no Sugar Journal access
    * no Sugar sharing
"""
class TurtleMain():
    def __init__(self):
        self.i = 0
        self.scale=2.0
        tw = None
        # make sure Sugar paths are present
        tapath = os.path.join(os.environ['HOME'],'.sugar','default', \
                              'org.laptop.TurtleArtActivity')
        map (makepath, (os.path.join(tapath,'data/'), \
                        os.path.join(tapath,'instance/')))

        """
        Find closest match for the user's $LANG
        """
        lang = locale.getdefaultlocale()[0]
        if not lang:
            lang = 'en'
        lang = lang[0:2]

        win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        win.maximize()
        win.set_title(_("Turtle Art"))
        win.connect("delete_event", lambda w,e: gtk.main_quit())

        menu = gtk.Menu()

        menu_items = gtk.MenuItem(_("Open"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_open_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Save"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_save_cb)
        menu_items.show()

        activity_menu = gtk.MenuItem(_("File"))
        activity_menu.show()
        activity_menu.set_submenu(menu)

        menu = gtk.Menu()

        menu_items = gtk.MenuItem(_("Cartesian coordinates"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_cartesian_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Polar coordinates"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_polar_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_('Rescale coordinates'))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_rescale_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Grow blocks"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_resize_cb, 1.5)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Shrink blocks"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_resize_cb, 0.667)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Reset block size"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_resize_cb, -1)
        menu_items.show()

        view_menu = gtk.MenuItem(_("View"))
        view_menu.show()
        view_menu.set_submenu(menu)

        menu = gtk.Menu()

        menu_items = gtk.MenuItem(_("Copy"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_copy_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Paste"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_paste_cb)
        menu_items.show()

        edit_menu = gtk.MenuItem(_("Edit"))
        edit_menu.show()
        edit_menu.set_submenu(menu)

        menu = gtk.Menu()

        menu_items = gtk.MenuItem(_("Show palette"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_palette_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Hide palette"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_hide_palette_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Show/hide blocks"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_hideshow_cb)
        menu_items.show()

        tool_menu = gtk.MenuItem(_("Tools"))
        tool_menu.show()
        tool_menu.set_submenu(menu)

        menu = gtk.Menu()

        menu_items = gtk.MenuItem(_("Clean"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_eraser_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Run"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_run_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Step"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_step_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Debug"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_trace_cb)
        menu_items.show()
        menu_items = gtk.MenuItem(_("Stop"))
        menu.append(menu_items)
        menu_items.connect("activate", self._do_stop_cb)
        menu_items.show()

        turtle_menu = gtk.MenuItem(_("Turtle"))
        turtle_menu.show()
        turtle_menu.set_submenu(menu)

        vbox = gtk.VBox(False, 0)
        win.add(vbox)
        vbox.show()

        menu_bar = gtk.MenuBar()
        vbox.pack_start(menu_bar, False, False, 2)
        menu_bar.show()

        canvas = gtk.DrawingArea()
        vbox.pack_end(canvas, True, True)
        canvas.show()

        menu_bar.append(activity_menu)
        menu_bar.append(edit_menu)
        menu_bar.append(view_menu)
        menu_bar.append(tool_menu)
        menu_bar.append(turtle_menu)

        win.show_all()
        self.tw = TurtleArtWindow(canvas, os.path.abspath('.'), lang)
        self.tw.win = win
        self.tw.load_start()

    def _do_open_cb(self, widget):
        self.tw.load_file(True)

    def _do_save_cb(self, widget):
        self.tw.save_file()

    def _do_resize_cb(self, widget, factor):
        if factor == -1:
            self.tw.block_scale = 2.0
        else:
            self.tw.block_scale *= factor
        self.tw.resize_blocks()

    def _do_cartesian_cb(self, button):
        if self.tw.cartesian is True:
            if self.tw.coord_scale == 1:
                self.tw.overlay_shapes['Cartesian_labeled'].hide()
            else:
                self.tw.overlay_shapes['Cartesian'].hide()
            self.tw.cartesian = False
        else:
            if self.tw.coord_scale == 1:
                self.tw.overlay_shapes['Cartesian_labeled'].set_layer(
                                                              OVERLAY_LAYER)
            else:
                self.tw.overlay_shapes['Cartesian'].set_layer(OVERLAY_LAYER)
            self.tw.cartesian = True

    def _do_polar_cb(self, button):
        if self.tw.polar is True:
            self.tw.overlay_shapes['polar'].hide()
            self.tw.polar = False
        else:
            self.tw.overlay_shapes['polar'].set_layer(OVERLAY_LAYER)
            self.tw.polar = True

    def _do_rescale_cb(self, button):
        if self.tw.coord_scale == 1:
            self.tw.coord_scale = self.tw.height/200
            self.tw.eraser_button()
            if self.tw.cartesian is True:
                self.tw.overlay_shapes['Cartesian_labeled'].hide()
                self.tw.overlay_shapes['Cartesian'].set_layer(OVERLAY_LAYER)
        else:
            self.tw.coord_scale = 1
            self.tw.eraser_button()
            if self.tw.cartesian is True:
                self.tw.overlay_shapes['Cartesian'].hide()
                self.tw.overlay_shapes['Cartesian_labeled'].set_layer(
                                                              OVERLAY_LAYER)

    def _do_palette_cb(self, widget):
        self.tw.show_palette(self.i)
        self.i += 1
        if self.i == len(self.tw.palettes):
            self.i = 0

    def _do_hide_palette_cb(self, widget):
        self.tw.hide_palette()

    def _do_hideshow_cb(self, widget):
        self.tw.hideshow_button()

    def _do_eraser_cb(self, widget):
        self.tw.eraser_button()
        return

    def _do_run_cb(self, widget):
        self.tw.lc.trace = 0
        self.tw.run_button(0)
        return

    def _do_step_cb(self, widget):
        self.tw.lc.trace = 0
        self.tw.run_button(3)
        return

    def _do_trace_cb(self, widget):
        self.tw.lc.trace = 1
        self.tw.run_button(6)
        return

    def _do_stop_cb(self, widget):
        self.tw.lc.trace = 0
        self.tw.stop_button()
        return

    def _do_copy_cb(self, button):
        clipBoard = gtk.Clipboard()
        data = self.tw.assemble_data_to_save(False, False)
        if data is not []:
            text = data_to_string(data)
            clipBoard.set_text(text)

    def _do_paste_cb(self, button):
        clipBoard = gtk.Clipboard()
        text = clipBoard.wait_for_text()
        if text is not None:
            self.tw.process_data(data_from_string(text))

def main():
    gtk.main()
    return 0

if __name__ == "__main__":
    TurtleMain()
    main()

<|endoftext|>


<commit_before>from ggame import App, Color, LineStyle, Sprite
from ggame import RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset

# Three primary colors with no transparency (alpha = 1.0)
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)

# Define a line style that is a thin (1 pixel) wide black line
thinline = LineStyle(1, black)
noline = LineStyle(1, red)
# A graphics asset that represents a rectangle
rectangle = RectangleAsset(500, 500, thinline, blue)
circle = EllipseAsset(200, 200, thinline, red)
scircle = EllipseAsset(50, 40, thinline, Color(0x073d91, 1.0))
mouth = EllipseAsset(100, 50, thinline, Color(0x008000, 1.0))
mouth2 = EllipseAsset(100, 40, noline, red)
ImageAsset("http://a1.mzstatic.com/us/r30/Purple5/v4/5a/2e/e9/5a2ee9b3-8f0e-4f8b-4043-dd3e3ea29766/icon256.png", frame=None, qty=1, direction='horizontal', margin=0)
# Now display a rectangle
Sprite(rectangle, (100,50))
Sprite(circle, (300, 250))
Sprite(scircle, (240, 200))
Sprite(scircle, (370, 200))
Sprite(mouth, (300, 320))
Sprite(mouth2, (300, 305))

myapp = App()
myapp.run()
<commit_msg>Updated from Brython Server: September 10, 2015 2:06:14 PM GMT-4<commit_after>from ggame import App, Color, LineStyle, Sprite
from ggame import RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset

# Three primary colors with no transparency (alpha = 1.0)
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)

# Define a line style that is a thin (1 pixel) wide black line
thinline = LineStyle(1, black)
noline = LineStyle(1, red)
# A graphics asset that represents a rectangle
rectangle = RectangleAsset(500, 500, thinline, blue)
circle = EllipseAsset(200, 200, thinline, red)
scircle = EllipseAsset(50, 40, thinline, Color(0x073d91, 1.0))
mouth = EllipseAsset(100, 50, thinline, Color(0x008000, 1.0))
mouth2 = EllipseAsset(100, 40, noline, red)
pic = ImageAsset("http://a1.mzstatic.com/us/r30/Purple5/v4/5a/2e/e9/5a2ee9b3-8f0e-4f8b-4043-dd3e3ea29766/icon256.png", frame=None, qty=1, direction='horizontal', margin=0)
# Now display a rectangle
Sprite(rectangle, (100,50))
Sprite(circle, (300, 250))
Sprite(scircle, (240, 200))
Sprite(scircle, (370, 200))
Sprite(mouth, (300, 320))
Sprite(mouth2, (300, 305))

myapp = App()
myapp.run()
<|endoftext|>


<commit_before>from ggame import App
myapp = App()
myapp.run()
from ggame import App, Color, LineStyle, Sprite
from ggame import RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset

# Three primary colors with no transparency (alpha = 1.0)
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)

# Define a line style that is a thin (1 pixel) wide black line
thinline = LineStyle(5, black)
thicc = LineStyle(20, red)
# A graphics asset that represents a rectangle
rectangle = RectangleAsset(1000, 500, thinline, blue)
Circle2 = CircleAsset(300, thinline,black)
Circle = CircleAsset(100, thinline,red)
Ellipse = EllipseAsset(230,35, thinline, green)
Ellipse2 = EllipseAsset(230,35, thinline, black)
Polygon = PolygonAsset(((10,70,), (30,50),(60,60)), thicc, red)
rectangle2 = RectangleAsset(100, 300, thicc, red)
Polygon2 = PolygonAsset(((100,70,), (300,50),(90,60)), thicc, blue)
# Now display a rectangle
Sprite(rectangle)
Sprite(Circle2)
Sprite(Circle)
Sprite(Ellipse2, (320,320))
Sprite(Ellipse, (300,300))
Sprite(Polygon)
Sprite(rectangle2, (400,400))
Sprite(Polygon2, (500,500))

myapp = App()
myapp.run()
<commit_msg>Updated from Brython Server: February 1, 2017 1:37:12 PM EST<commit_after>from ggame import App
myapp = App()
myapp.run()
from ggame import App, Color, LineStyle, Sprite
from ggame import RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset

# Three primary colors with no transparency (alpha = 1.0)
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)

# Define a line style that is a thin (1 pixel) wide black line
thinline = LineStyle(5, black)
thicc = LineStyle(20, red)
# A graphics asset that represents a rectangle
rectangle = RectangleAsset(1000, 500, thinline, blue)
Circle2 = CircleAsset(300, thinline,black)
Circle = CircleAsset(100, thinline,red)
Ellipse = EllipseAsset(230,35, thinline, green)
Ellipse2 = EllipseAsset(230,35, thinline, black)
Polygon = PolygonAsset(((10,70,), (30,50),(60,60)), thicc, red)
rectangle2 = RectangleAsset(100, 300, thicc, red)
Polygon2 = PolygonAsset(((100,70,), (300,50),(90,60)), thicc, blue)
# Now display a rectangle
Sprite(rectangle)
Sprite(Circle2)
Sprite(Circle)
Sprite(Ellipse2, (320,320))
Sprite(Ellipse, (300,300))
Sprite(Polygon)
Sprite(rectangle2, (400,400))
Sprite(Polygon2, (300,500))

myapp = App()
myapp.run()
<|endoftext|>


<commit_before>from ggame import App
myapp = App()
myapp.run()

from ggame import App, Color, LineStyle, Sprite
from ggame import RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset

# Three primary colors with no transparency (alpha = 1.0)
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)

# Define a line style that is a thin (1 pixel) wide black line
thinline = LineStyle(1, black)
# A graphics asset that represents a rectangle
brectangle = RectangleAsset(50, 20, thinline, blue)
rrectangle = RectangleAsset(50, 20, thinline, red)
bellipse = EllipseAsset(500,250,thinline, blue)
rpolygon = PolygonAsset([(0,250),
                        (0,50),
                        (50,0),
                        (950,0),
                        (1000,50),
                        (1000,250),
                        (1000,450),
                        (950,50),
                        (50,500),
                        (0,250)],thinline, red)

# Now display a rectangle
Sprite(brectangle,(100,100))
Sprite(rrectangle,(110,110))
Sprite(bellipse,(0,0))
Sprite(rpolygon(500,250))

myapp = App()
myapp.run()<commit_msg>Updated from Brython Server: 5/8/2016 12:22:23 PM<commit_after>from ggame import App
myapp = App()
myapp.run()

from ggame import App, Color, LineStyle, Sprite
from ggame import RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset

# Three primary colors with no transparency (alpha = 1.0)
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)

# Define a line style that is a thin (1 pixel) wide black line
thinline = LineStyle(1, black)
# A graphics asset that represents a rectangle
brectangle = RectangleAsset(50, 20, thinline, blue)
rrectangle = RectangleAsset(50, 20, thinline, red)
bellipse = EllipseAsset(500,250,thinline, blue)
rpolygon = PolygonAsset([(0,250),
                        (0,50),
                        (50,0),
                        (950,0),
                        (1000,50),
                        (1000,250),
                        (1000,450),
                        (950,50),
                        (50,500),
                        (0,250)],thinline, red)

# Now display a rectangle
Sprite(brectangle,(100,100))
Sprite(rrectangle,(110,110))
Sprite(bellipse,(0,0))
Sprite(rpolygon,(-500,-250))

myapp = App()
myapp.run()<|endoftext|>


<commit_before>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
import math
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.rotateLeft)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.lrOff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.rotateRight)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.rrOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y -= self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1
        if 0 < self.rotation < -0.5:
            self.vx = math.sin(math.pi * abs(self.rotation))
            self.vy = math.cos(math.pi * abs(self.rotation))
        elif -0.5 <= self.rotation <= -1:
            self.vx = math.sin(math.pi * abs(self.rotation))
            self.vy = -1*math.cos(math.pi * abs(self.rotation))
        elif 0 <= self.rotation < 0.5:
            self.vx = -1*math.sin(math.pi * abs(self.rotation))
            self.vy = math.cos(math.pi * abs(self.rotation))
        elif 0.5 <= self.rotation <= 1:
            self.vx = -1*math.sin(math.pi * abs(self.rotation))
            self.vy = -1*math.cos(math.pi * abs(self.rotation))

    def thrustOff(self, event):
        self.thrust = 0
        self.vx = 0

    def rotateLeft(self, event):
        self.vr = 0.05

    def lrOff(self,  event):
        self.vr = 0

    def rotateRight(self, event):
        self.vr = -0.05

    def rrOff(self,  event):
        self.vr = 0
class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(SCREEN_WIDTH, SCREEN_HEIGHT, noline, black)
        bg = Sprite(bg_asset, (0,0,0))
        SpaceShip((100,100))
        SpaceShip((150,150))
        SpaceShip((200,50))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<commit_msg>Updated from Brython Server: 10/13/2015 3:16:03 PM<commit_after>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
import math
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.rotateLeft)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.lrOff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.rotateRight)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.rrOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1
        if 0 < self.rotation < -0.5:
            self.vx = math.sin(math.pi * abs(self.rotation))
            self.vy = math.cos(math.pi * abs(self.rotation))
        elif -0.5 <= self.rotation <= -1:
            self.vx = math.sin(math.pi * abs(self.rotation))
            self.vy = -1*math.cos(math.pi * abs(self.rotation))
        elif 0 <= self.rotation < 0.5:
            self.vx = -1*math.sin(math.pi * abs(self.rotation))
            self.vy = math.cos(math.pi * abs(self.rotation))
        elif 0.5 <= self.rotation <= 1:
            self.vx = -1*math.sin(math.pi * abs(self.rotation))
            self.vy = -1*math.cos(math.pi * abs(self.rotation))

    def thrustOff(self, event):
        self.thrust = 0
        self.vx = 0

    def rotateLeft(self, event):
        self.vr = 0.05

    def lrOff(self,  event):
        self.vr = 0

    def rotateRight(self, event):
        self.vr = -0.05

    def rrOff(self,  event):
        self.vr = 0
class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(SCREEN_WIDTH, SCREEN_HEIGHT, noline, black)
        bg = Sprite(bg_asset, (0,0,0))
        SpaceShip((100,100))
        SpaceShip((150,150))
        SpaceShip((200,50))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<|endoftext|>


<commit_before>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 1
        self.vy = 1
        self.vr = 0.01
        self.thrust = 0
        self.thrustframe = 1
        self.fxcenter = self.fycenter = 0.5
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.left)

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
        if self.thrustframe == 4:
            self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def left(self, event):
        self.rotation =1

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(SCREEN_WIDTH, SCREEN_HEIGHT, noline, black)
        bg = Sprite(bg_asset, (0,0))
        SpaceShip((100,100))
        SpaceShip((150,150))
        SpaceShip((200,50))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<commit_msg>Updated from Brython Server: 3/8/2016 2:22:16 PM<commit_after>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 1
        self.vy = 1
        self.vr = 0.1
        self.thrust = 0
        self.thrustframe = 1
        self.fxcenter = self.fycenter = 0.5
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.left)

    def step(self):

        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
        if self.thrustframe == 4:
            self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1
        self.x -= self.vx
        self.y -= self.vy

    def thrustOff(self, event):
        self.thrust = 0

    def left(self, event):
        self.rotation += self.vr

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(SCREEN_WIDTH, SCREEN_HEIGHT, noline, black)
        bg = Sprite(bg_asset, (0,0))
        SpaceShip((100,100))
        SpaceShip((150,150))
        SpaceShip((200,50))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<|endoftext|>


<commit_before>#!/usr/bin/env python

import simplejson
import pycurl
import tempfile
import fabulous.image
import fabulous.text
import fabulous.color
import urllib
import os
import re

of_interest = [
    {
        'attr': 'user_mentions',
        'symb': '@',
        'color': fabulous.color.green,
        'extract': 'screen_name',
    },
    {
        'attr': 'hashtags',
        'symb': '#',
        'color': fabulous.color.red,
        'extract': 'text',
    },
    {
        'attr': 'urls',
        'symb': '',
        'color': fabulous.color.yellow,
        'extract': 'url',
    },
]

def on_receive(data):
    obj = simplejson.loads(data)

    try:
        if not 'user' in obj:
            return
        lnk = obj['user']['profile_image_url']
        local_file = tempfile.mkstemp()[1]
        urllib.urlretrieve(lnk, local_file)
        print fabulous.image.Image(local_file)
        os.remove(local_file)
        if 'text' in obj:
            try:
                for lookup in of_interest:
                    things = obj['entities'][lookup['attr']]
                    things = [thing[lookup['extract']] for thing in things]

                    for thing in things:
                        item = lookup['symb'] + thing
                        toks = unicode(obj['text']).split(item)
                        obj['text'] = toks[0] + lookup['color'](item) + toks[1]

            except Exception as e:
                import traceback
                traceback.print_exc()
                print obj['entities']
                print fabulous.color.cyan("color failed..."), str(e)

            print unicode(obj['text'])

    except Exception as e:
        import traceback
        traceback.print_exc()
        print str(e), ':('

STREAM_URL = "https://stream.twitter.com/1/statuses/sample.json"
USER = "DevAccount7"
PASS = "blahah"

conn = pycurl.Curl()
conn.setopt(pycurl.USERPWD, "%s:%s" % (USER, PASS))
conn.setopt(pycurl.URL, STREAM_URL)
#FIXME: sometimes it just hangs... lets find out why and fix it someday
#conn.setopt(pycurl.SOCKET_TIMEOUT, 12)
conn.setopt(pycurl.WRITEFUNCTION, on_receive)
conn.perform()
<commit_msg>Added timestamps :) #juggalos<commit_after>#!/usr/bin/env python

import simplejson
import pycurl
import tempfile
import fabulous.image
import fabulous.text
import fabulous.color
import urllib
import os
import re

of_interest = [
    {
        'attr': 'user_mentions',
        'symb': '@',
        'color': fabulous.color.green,
        'extract': 'screen_name',
    },
    {
        'attr': 'hashtags',
        'symb': '#',
        'color': fabulous.color.red,
        'extract': 'text',
    },
    {
        'attr': 'urls',
        'symb': '',
        'color': fabulous.color.yellow,
        'extract': 'url',
    },
]

def on_receive(data):
    obj = simplejson.loads(data)

    try:
        if not 'user' in obj:
            return
        lnk = obj['user']['profile_image_url']
        tstamp = ' '.join(obj['created_at'].split(' ')[:4])
        tstamp = fabulous.color.magenta(tstamp)
        local_file = tempfile.mkstemp()[1]
        urllib.urlretrieve(lnk, local_file)
        print fabulous.image.Image(local_file)
        os.remove(local_file)
        if 'text' in obj:
            try:
                for lookup in of_interest:
                    things = obj['entities'][lookup['attr']]
                    things = [thing[lookup['extract']] for thing in things]

                    for thing in things:
                        item = lookup['symb'] + thing
                        toks = unicode(obj['text']).split(item)
                        obj['text'] = toks[0] + lookup['color'](item) + toks[1]

            except Exception as e:
                import traceback
                traceback.print_exc()
                print obj['entities']
                print fabulous.color.cyan("color failed..."), str(e)

            print tstamp,
            print unicode(obj['text'])

    except Exception as e:
        import traceback
        traceback.print_exc()
        print str(e), ':('

STREAM_URL = "https://stream.twitter.com/1/statuses/sample.json"
USER = "DevAccount7"
PASS = "blahah"

conn = pycurl.Curl()
conn.setopt(pycurl.USERPWD, "%s:%s" % (USER, PASS))
conn.setopt(pycurl.URL, STREAM_URL)
#FIXME: sometimes it just hangs... lets find out why and fix it someday
#conn.setopt(pycurl.SOCKET_TIMEOUT, 12)
conn.setopt(pycurl.WRITEFUNCTION, on_receive)
conn.perform()
<|endoftext|>


<commit_before>import json
import codecs
import oauth2 as oauth
import datetime
import time as t
from credentials import *

TWEET_URL = "https://api.twitter.com/1.1/statuses/update.json"

def initialize_client(consumer_key, consumer_secret, access_key, access_secret):
    global client
    consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)
    token = oauth.Token(key=access_key, secret=access_secret)
    client = oauth.Client(consumer, token)

class Bot:
    def __init__(self, tweets=[], counter=0, filename=None, interval=10):
        # If tweets list wasn't passed, open file and read everything but the first line
        # first line contains the counter
        if not tweets:
            try:
                with codecs.open(filename, 'r', 'utf-8') as f:
                    lines = f.readlines()
                    # For some reason a \ufeff sometimes appears in front of the number
                    lines[0] = lines[0].replace('\ufeff', '') # get rid of it
                    self.counter = int(lines[0])
                    self.tweets = lines[1:]
                    self.filename = filename
            except:
                print("Error opening the file")
                quit()
        else:
            self.tweets = tweets
            self.counter = counter
        self.interval = interval

    # may come in useful in later programs, hence static
    @staticmethod
    def oauth_req(client, url, post_body="", http_method="POST"):
    	response, data = client.request(url, method=http_method, body=post_body)
    	return response, data

    @staticmethod
    def tweet(client, msg):
        # encode message into URL format
        tweet_msg = oauth.urlencode({'status': msg})
        response, data = Bot.oauth_req(client, TWEET_URL, tweet_msg)
        print("Tweeting \"{}\", HTTP: {}".format(msg.strip(), response.status))

    def run(self):
        while True:
            time = datetime.datetime.now().time()
            minute = time.minute
            second = time.second

            # if the minute is a multiple of the interval and second == 0, send a tweet and increment the counter
            if not minute % self.interval and not second:
                # when the counter gets to the end, wrap around to the start using modulus
                __class__.tweet(client, self.tweets[self.counter % len(self.tweets)])
                self.counter += 1
                with codecs.open(self.filename, "w", "utf-8") as f:
                    tweets = "".join(self.tweets)
                    f.write(str(self.counter) + "\r\n" + tweets)

            t.sleep(1) # Sleep for a second to avoid posting multiple tweets

def main():
    initialize_client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
    bot = Bot(filename="transcript.txt")
    bot.run()

if __name__ == '__main__':
    main()
<commit_msg>Connection issue fix<commit_after>import json
import codecs
import oauth2 as oauth
import datetime
import time as t
from credentials import *

TWEET_URL = "https://api.twitter.com/1.1/statuses/update.json"

def initialize_client(consumer_key, consumer_secret, access_key, access_secret):
    consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)
    token = oauth.Token(key=access_key, secret=access_secret)
    client = oauth.Client(consumer, token)
    return client

class Bot:
    def __init__(self, tweets=[], counter=0, filename=None, interval=10):
        # If tweets list wasn't passed, open file and read everything but the first line
        # first line contains the counter
        if not tweets:
            try:
                with codecs.open(filename, 'r', 'utf-8') as f:
                    lines = f.readlines()
                    # For some reason a \ufeff sometimes appears in front of the number
                    lines[0] = lines[0].replace('\ufeff', '') # get rid of it
                    self.counter = int(lines[0])
                    self.tweets = lines[1:]
                    self.filename = filename
            except:
                print("Error opening the file")
                quit()
        else:
            self.tweets = tweets
            self.counter = counter
        self.interval = interval

    # may come in useful in later programs, hence static
    @staticmethod
    def oauth_req(client, url, post_body="", http_method="POST"):
    	response, data = client.request(url, method=http_method, body=post_body)
    	return response, data

    @staticmethod
    def tweet(client, msg):
        # encode message into URL format
        tweet_msg = oauth.urlencode({'status': msg})
        response, data = Bot.oauth_req(client, TWEET_URL, tweet_msg)
        print("Tweeting \"{}\", HTTP: {}".format(msg.strip(), response.status))

    def run(self):
        while True:
            time = datetime.datetime.now().time()
            minute = time.minute
            second = time.second

            # if the minute is a multiple of the interval and second == 0, send a tweet and increment the counter
            if not minute % self.interval and not second:
                # when the counter gets to the end, wrap around to the start using modulus
                client = initialize_client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
                __class__.tweet(client, self.tweets[self.counter % len(self.tweets)])
                self.counter += 1
                with codecs.open(self.filename, "w", "utf-8") as f:
                    tweets = "".join(self.tweets)
                    f.write(str(self.counter) + "\r\n" + tweets)

            t.sleep(1) # Sleep for a second to avoid posting multiple tweets

def main():
    bot = Bot(filename="transcript.txt")
    bot.run()

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>import numpy as np

def evaluate_voxel_prediction(preds, gt, thresh):
    preds_occupy = preds[:, 1, :, :] >= thresh
    diff = np.sum(np.logical_xor(preds_occupy, gt[:, 1, :, :]))
    intersection = np.sum(np.logical_and(preds_occupy, gt[:, 1, :, :]))
    union = np.sum(np.logical_or(preds_occupy, gt[:, 1, :, :]))
    num_fp = np.sum(np.logical_and(preds_occupy, gt[:, 0, :, :]))  # false positive
    num_fn = np.sum(np.logical_and(np.logical_not(preds_occupy), gt[:, 1, :, :]))  # false negative
    return np.array([diff, intersection, union, num_fp, num_fn])

def voxel2mesh(voxels, surface_view):
    cube_verts = [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0],
                  [1, 1, 1]]  # 8 points

    cube_faces = [[0, 1, 2], [1, 3, 2], [2, 3, 6], [3, 7, 6], [0, 2, 6], [0, 6, 4], [0, 5, 1],
                  [0, 4, 5], [6, 7, 5], [6, 5, 4], [1, 7, 3], [1, 5, 7]]  # 12 face

    cube_verts = np.array(cube_verts)
    cube_faces = np.array(cube_faces) + 1

    scale = 0.01
    cube_dist_scale = 1.1
    verts = []
    faces = []
    curr_vert = 0

    positions = np.where(voxels > 0.3)
    voxels[positions] = 1
    for i,j,k in zip(*positions):
        if not surface_view or np.sum(voxels[i-1:i+2,j-1:j+2,k-1:k+2])< 27: # identifies if current voxel has an exposed face
            verts.extend(scale * (cube_verts + cube_dist_scale * np.array([[i, j, k]])))
            faces.extend(cube_faces + curr_vert)
            curr_vert += len(cube_verts)

    return np.array(verts), np.array(faces)

def write_obj(filename, verts, faces):
    """ write the verts and faces on file."""
    with open(filename, 'w') as f:
        # write vertices
        f.write('g\n# %d vertex\n' % len(verts))
        for vert in verts:
            f.write('v %f %f %f\n' % tuple(vert))

        # write faces
        f.write('# %d faces\n' % len(faces))
        for face in faces:
            f.write('f %d %d %d\n' % tuple(face))

def voxel2obj(filename, pred, surface_view = True):
    verts, faces = voxel2mesh(pred, surface_view)
    write_obj(filename, verts, faces)
<commit_msg>Minor format changes<commit_after>import numpy as np

def evaluate_voxel_prediction(preds, gt, thresh):
    preds_occupy = preds[:, 1, :, :] >= thresh
    diff = np.sum(np.logical_xor(preds_occupy, gt[:, 1, :, :]))
    intersection = np.sum(np.logical_and(preds_occupy, gt[:, 1, :, :]))
    union = np.sum(np.logical_or(preds_occupy, gt[:, 1, :, :]))
    num_fp = np.sum(np.logical_and(preds_occupy, gt[:, 0, :, :]))  # false positive
    num_fn = np.sum(np.logical_and(np.logical_not(preds_occupy), gt[:, 1, :, :]))  # false negative
    return np.array([diff, intersection, union, num_fp, num_fn])

def voxel2mesh(voxels, surface_view):
    cube_verts = [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0],
                  [1, 1, 1]]  # 8 points

    cube_faces = [[0, 1, 2], [1, 3, 2], [2, 3, 6], [3, 7, 6], [0, 2, 6], [0, 6, 4], [0, 5, 1],
                  [0, 4, 5], [6, 7, 5], [6, 5, 4], [1, 7, 3], [1, 5, 7]]  # 12 face

    cube_verts = np.array(cube_verts)
    cube_faces = np.array(cube_faces) + 1

    scale = 0.01
    cube_dist_scale = 1.1
    verts = []
    faces = []
    curr_vert = 0

    positions = np.where(voxels > 0.3)
    voxels[positions] = 1
    for i, j, k in zip(*positions):
        # identifies if current voxel has an exposed face
        if not surface_view or np.sum(voxels[i-1:i+2, j-1:j+2, k-1:k+2]) < 27:
            verts.extend(scale * (cube_verts + cube_dist_scale * np.array([[i, j, k]])))
            faces.extend(cube_faces + curr_vert)
            curr_vert += len(cube_verts)

    return np.array(verts), np.array(faces)

def write_obj(filename, verts, faces):
    """ write the verts and faces on file."""
    with open(filename, 'w') as f:
        # write vertices
        f.write('g\n# %d vertex\n' % len(verts))
        for vert in verts:
            f.write('v %f %f %f\n' % tuple(vert))

        # write faces
        f.write('# %d faces\n' % len(faces))
        for face in faces:
            f.write('f %d %d %d\n' % tuple(face))

def voxel2obj(filename, pred, surface_view = True):
    verts, faces = voxel2mesh(pred, surface_view)
    write_obj(filename, verts, faces)
<|endoftext|>


<commit_before>from sqlalchemy import Column, Date, Integer, Float, String
from sqlalchemy import ForeignKeyConstraint, ForeignKey, Index, Text
from sqlalchemy.orm import deferred, relationship
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.ext.declarative import declarative_base

# Extend the Base >>>>>>
Base = declarative_base()

def init(self, *args, **kwargs):
    for i, arg in enumerate(args):
        self.__dict__[self.kw[i]] = arg
    for k, v in kwargs.iteritems():
        self.__dict__[k] = v
Base.__init__ = init
# <<<<<<

# PATENT ---------------------------

class Patent(Base):
    __tablename__ = "patent"
    uuid = Column(Integer, primary_key=True)
    type = Column(String(20))
    number = Column(String(20))
    country = Column(String(20))
    date = Column(Date)
    abstract = deferred(Column(Text))
    title = deferred(Column(Text))
    kind = Column(String(10))
    claims = Column(Integer)

    application = relationship("Application", uselist=False, backref="patent")
    classes = relationship("USPC", backref="patent")

    assignees = relationship("Assignee", backref="patent")
    inventors = relationship("Inventor", backref="patent")
    lawyers = relationship("Lawyer", backref="patent")

    citations = relationship(
        "Citation",
        primaryjoin="Patent.uuid == Citation.patent_uuid",
        backref="patent")
    citedby = relationship(
        "Citation",
        primaryjoin="Patent.uuid == Citation.citation_uuid",
        backref="citation")
    otherreferences = relationship("OtherReference", backref="patent")
    usreldocs = relationship("USRelDoc", backref="patent")

    kw = ["type", "number", "country", "date",
          "abstract", "title", "kind", "claims"]
    __table_args__ = (
        Index("pat_idx1", "type", "number", unique=True),
        Index("pat_idx2", "date"),
    )

class Application(Base):
    __tablename__ = "application"
    uuid = Column(Integer, primary_key=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    type = Column(String(20))
    number = Column(String(20))
    country = Column(String(20))
    date = Column(Date)
    kw = ["type", "number", "country", "date"]
    __table_args__ = (
        Index("app_idx1", "type", "number", unique=True),
        Index("app_idx2", "date"),
    )
#Index('pat_idx3', Patent.date__grant)

# SUPPORT --------------------------

class Location(Base):
    #TODO: Anyway we can consolidate to 1 PrimaryKey
    __tablename__ = "location"
    city = Column(String(128), primary_key=True)
    state = Column(String(10), index=True, primary_key=True)
    country = Column(String(10), index=True, primary_key=True)
    latitude = Column(Float)
    longitude = Column(Float)
    inventors = relationship("Inventor", backref="location")
    assignees = relationship("Assignee", backref="location")
    kw = ["city", "state", "country", "longitude", "latitude"]
    __table_args__ = (
        Index("loc_idx1", "latitude", "longitude"),
    )

    @hybrid_property
    def address(self):
        addy = []
        if self.city:
            addy.append(self.city)
        if self.state:
            addy.append(self.state)
        if self.country:
            addy.append(self.country)
        return ", ".join(addy)

# OBJECTS --------------------------

class Assignee(Base):
    __tablename__ = "assignee"
    uuid = Column(Integer, primary_key=True)
    #location_uuid = Column(Integer, ForeignKey("location.uuid"))
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    type = Column(String(10))
    organization = Column(String(256))
    name_first = Column(String(64))
    name_last = Column(String(64))
    location_city = Column(String(128))
    location_state = Column(String(10), index=True)
    location_country = Column(String(10), index=True)
    sequence = Column(Integer, index=True)
    kw = ["sequence"]
    __table_args__ = (
        ForeignKeyConstraint(
            [loc_city, loc_state, loc_country],
            [Location.city, Location.state, Location.country]
        ),
    )

    def asg(self, *args):
        self.organization = args[0]
        self.type = args[1]

    def person(self, *args):
        self.name_last = args[0]
        self.name_first = args[1]

class Inventor(Base):
    __tablename__ = "inventor"
    uuid = Column(Integer, primary_key=True)
    #location_uuid = Column(Integer, ForeignKey("location.uuid"))
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    name_last = Column(String(64))
    name_first = Column(String(64))
    location_city = Column(String(128))
    location_state = Column(String(10), index=True)
    location_country = Column(String(10), index=True)
    sequence = Column(Integer, index=True)
    kw = ["sequence", "name_last", "name_first", "nationality"]
    __table_args__ = (
        ForeignKeyConstraint(
            [loc_city, loc_state, loc_country],
            [Location.city, Location.state, Location.country]
        ),
    )

    @hybrid_property
    def name_full(self):
        return "{first} {last}".format(
            first=self.name_first,
            last=self.name_last)

class Lawyer(Base):
    __tablename__ = "lawyer"
    uuid = Column(Integer, primary_key=True)
    #location_uuid = Column(Integer, ForeignKey("location.uuid"))
    id = Column(String(64), index=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    name_last = Column(String(64))
    name_first = Column(String(64))
    organization = Column(String(64))
    country = Column(String(10))
    sequence = Column(Integer, index=True)
    kw = ["sequence", "name_last", "name_first", "organization", "country"]

    @hybrid_property
    def name_full(self):
        return "{first} {last}".format(
            first=self.name_first,
            last=self.name_last)

# REFERENCES -----------------------

class Citation(Base):
    """
    Two types of citations?
    """
    __tablename__ = "citation"
    uuid = Column(Integer, primary_key=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    citation_uuid = Column(Integer, ForeignKey("patent.uuid"))
    date = Column(Date, index=True)
    number = Column(String(20), index=True)
    name = Column(String(64))
    kind = Column(String(10))
    country = Column(String(10), index=True)
    category = Column(String(20), index=True)
    sequence = Column(Integer, index=True)
    kw = ["sequence", "date", "number", "name",
          "kind", "country", "category"]

class OtherReference(Base):
    __tablename__ = "otherreference"
    uuid = Column(Integer, primary_key=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    text = Column(Text)
    sequence = Column(Integer, index=True)
    kw = ["sequence", "text"]

class USRelDoc(Base):
    __tablename__ = "usreldoc"
    uuid = Column(Integer, primary_key=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))

# CLASSIFICATIONS ------------------

class USPC(Base):
    __tablename__ = "uspc"
    uuid = Column(Integer, primary_key=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    mainclass_id = Column(String(10), ForeignKey("mainclass.id"))
    subclass_id = Column(String(10), ForeignKey("subclass.id"))
    sequence = Column(Integer, index=True)
    kw = ["sequence"]

class MainClass(Base):
    __tablename__ = "mainclass"
    id = Column(String(20), primary_key=True)
    title = Column(String(256))
    text = Column(String(256))
    uspc = relationship("USPC", backref="mainclass")
    kw = ["id", "title", "text"]

class SubClass(Base):
    __tablename__ = "subclass"
    id = Column(String(20), primary_key=True)
    title = Column(String(256))
    text = Column(String(256))
    uspc = relationship("USPC", backref="subclass")
    kw = ["id", "title", "text"]
<commit_msg>remodified schema.py<commit_after>from sqlalchemy import Column, Date, Integer, Float, String
from sqlalchemy import ForeignKeyConstraint, ForeignKey, Index, Text
from sqlalchemy.orm import deferred, relationship
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.ext.declarative import declarative_base

# Extend the Base >>>>>>
Base = declarative_base()

def init(self, *args, **kwargs):
    for i, arg in enumerate(args):
        self.__dict__[self.kw[i]] = arg
    for k, v in kwargs.iteritems():
        self.__dict__[k] = v
Base.__init__ = init
# <<<<<<

# PATENT ---------------------------

class Patent(Base):
    __tablename__ = "patent"
    uuid = Column(Integer, primary_key=True)
    type = Column(String(20))
    number = Column(String(20))
    country = Column(String(20))
    date = Column(Date)
    abstract = deferred(Column(Text))
    title = deferred(Column(Text))
    kind = Column(String(10))
    claims = Column(Integer)

    application = relationship("Application", uselist=False, backref="patent")
    classes = relationship("USPC", backref="patent")

    assignees = relationship("Assignee", backref="patent")
    inventors = relationship("Inventor", backref="patent")
    lawyers = relationship("Lawyer", backref="patent")

    citations = relationship(
        "Citation",
        primaryjoin="Patent.uuid == Citation.patent_uuid",
        backref="patent")
    citedby = relationship(
        "Citation",
        primaryjoin="Patent.uuid == Citation.citation_uuid",
        backref="citation")
    otherreferences = relationship("OtherReference", backref="patent")
    usreldocs = relationship("USRelDoc", backref="patent")

    kw = ["type", "number", "country", "date",
          "abstract", "title", "kind", "claims"]
    __table_args__ = (
        Index("pat_idx1", "type", "number", unique=True),
        Index("pat_idx2", "date"),
    )

class Application(Base):
    __tablename__ = "application"
    uuid = Column(Integer, primary_key=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    type = Column(String(20))
    number = Column(String(20))
    country = Column(String(20))
    date = Column(Date)
    kw = ["type", "number", "country", "date"]
    __table_args__ = (
        Index("app_idx1", "type", "number", unique=True),
        Index("app_idx2", "date"),
    )
#Index('pat_idx3', Patent.date__grant)

# SUPPORT --------------------------

class Location(Base):
    #TODO: Anyway we can consolidate to 1 PrimaryKey
    __tablename__ = "location"
    city = Column(String(128), primary_key=True)
    state = Column(String(10), index=True, primary_key=True)
    country = Column(String(10), index=True, primary_key=True)
    latitude = Column(Float)
    longitude = Column(Float)
    inventors = relationship("Inventor", backref="location")
    assignees = relationship("Assignee", backref="location")
    kw = ["city", "state", "country", "longitude", "latitude"]
    __table_args__ = (
        Index("loc_idx1", "latitude", "longitude"),
    )

    @hybrid_property
    def address(self):
        addy = []
        if self.city:
            addy.append(self.city)
        if self.state:
            addy.append(self.state)
        if self.country:
            addy.append(self.country)
        return ", ".join(addy)

# OBJECTS --------------------------

class Assignee(Base):
    __tablename__ = "assignee"
    uuid = Column(Integer, primary_key=True)
    #location_uuid = Column(Integer, ForeignKey("location.uuid"))
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    type = Column(String(10))
    organization = Column(String(256))
    name_first = Column(String(64))
    name_last = Column(String(64))
    location_city = Column(String(128))
    location_state = Column(String(10), index=True)
    location_country = Column(String(10), index=True)
    sequence = Column(Integer, index=True)
    kw = ["sequence"]
    __table_args__ = (
        ForeignKeyConstraint(
            [location_city, location_state, location_country],
            [Location.city, Location.state, Location.country]
        ),
    )

    def asg(self, *args):
        self.organization = args[0]
        self.type = args[1]

    def person(self, *args):
        self.name_last = args[0]
        self.name_first = args[1]

class Inventor(Base):
    __tablename__ = "inventor"
    uuid = Column(Integer, primary_key=True)
    #location_uuid = Column(Integer, ForeignKey("location.uuid"))
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    name_last = Column(String(64))
    name_first = Column(String(64))
    location_city = Column(String(128))
    location_state = Column(String(10), index=True)
    location_country = Column(String(10), index=True)
    sequence = Column(Integer, index=True)
    kw = ["sequence", "name_last", "name_first", "nationality"]
    __table_args__ = (
        ForeignKeyConstraint(
            [location_city, location_state, location_country],
            [Location.city, Location.state, Location.country]
        ),
    )

    @hybrid_property
    def name_full(self):
        return "{first} {last}".format(
            first=self.name_first,
            last=self.name_last)

class Lawyer(Base):
    __tablename__ = "lawyer"
    uuid = Column(Integer, primary_key=True)
    #location_uuid = Column(Integer, ForeignKey("location.uuid"))
    id = Column(String(64), index=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    name_last = Column(String(64))
    name_first = Column(String(64))
    organization = Column(String(64))
    country = Column(String(10))
    sequence = Column(Integer, index=True)
    kw = ["sequence", "name_last", "name_first", "organization", "country"]

    @hybrid_property
    def name_full(self):
        return "{first} {last}".format(
            first=self.name_first,
            last=self.name_last)

# REFERENCES -----------------------

class Citation(Base):
    """
    Two types of citations?
    """
    __tablename__ = "citation"
    uuid = Column(Integer, primary_key=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    citation_uuid = Column(Integer, ForeignKey("patent.uuid"))
    date = Column(Date, index=True)
    number = Column(String(20), index=True)
    name = Column(String(64))
    kind = Column(String(10))
    country = Column(String(10), index=True)
    category = Column(String(20), index=True)
    sequence = Column(Integer, index=True)
    kw = ["sequence", "date", "number", "name",
          "kind", "country", "category"]

class OtherReference(Base):
    __tablename__ = "otherreference"
    uuid = Column(Integer, primary_key=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    text = Column(Text)
    sequence = Column(Integer, index=True)
    kw = ["sequence", "text"]

class USRelDoc(Base):
    __tablename__ = "usreldoc"
    uuid = Column(Integer, primary_key=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))

# CLASSIFICATIONS ------------------

class USPC(Base):
    __tablename__ = "uspc"
    uuid = Column(Integer, primary_key=True)
    patent_uuid = Column(Integer, ForeignKey("patent.uuid"))
    mainclass_id = Column(String(10), ForeignKey("mainclass.id"))
    subclass_id = Column(String(10), ForeignKey("subclass.id"))
    sequence = Column(Integer, index=True)
    kw = ["sequence"]

class MainClass(Base):
    __tablename__ = "mainclass"
    id = Column(String(20), primary_key=True)
    title = Column(String(256))
    text = Column(String(256))
    uspc = relationship("USPC", backref="mainclass")
    kw = ["id", "title", "text"]

class SubClass(Base):
    __tablename__ = "subclass"
    id = Column(String(20), primary_key=True)
    title = Column(String(256))
    text = Column(String(256))
    uspc = relationship("USPC", backref="subclass")
    kw = ["id", "title", "text"]
<|endoftext|>