<commit_before>'''
The following is from http://stackoverflow.com/a/2022629
Thanks to Longpoke
'''
import types

class Event(list):
    """Event subscription.

    A list of callable objects. Calling an instance of this will cause a
    call to each item in the list in ascending order by index.

    Example Usage:
    >>> def f(x):
    ...     print 'f(%s)' % x
    >>> def g(x):
    ...     print 'g(%s)' % x
    >>> e = Event()
    >>> e()
    >>> e.append(f)
    >>> e(123)
    f(123)
    >>> e.remove(f)
    >>> e()
    >>> e += (f, g)
    >>> e(10)
    f(10)
    # g(10)
    >>> del e[0]
    >>> e(2)
    g(2)

    """
    def __init__(self,repeat=True):
        super(Event,self).__init__()
        self.repeat = repeat

    def __call__(self, *args, **kwargs):
        for f in self:
            f(*args, **kwargs)
        if not self.repeat:
            map(lambda func: self.remove(func),self)

    def remove(self, func):
        if func in self:
            list.remove(self,func)

    def __repr__(self):
        items = []
        for item in self:
            if isinstance(item, types.FunctionType) or isinstance(item, types.MethodType): #make functions prettier
                items.append(item.__name__)
            else:
                items.append(item)
        return "Event %s" % list.__repr__(items)

class Listener(dict):
    def addSub(self, name, callback,repeat=True):
        '''sets self[name] to Event() if there is no key name.
           Either way self[name] is returned and callback is appended'''

        self.setdefault(name, Event(repeat)).append(callback)

    def removeSub(self, name, callback):
        if name in self:
            self[name].remove(callback)
            if len(self[name]) == 0:
                del self[name]

    def listen(self, event, repeat=True):
        def wrap(f):
            self.addSub(event, f,repeat)
            return f
        return wrap

    def trigger(self, event):
        def wrap(f):
            def newFunc(*args, **kwargs):
                res = f(*args, **kwargs)
                self(event, res)
                return res
            return newFunc
        return wrap

    def __call__(self, event, *args, **kwargs):
        if event in self:
            self[event](*args, **kwargs)
            if len(self[event])==0:
                self.removeSub(event,self[event])

        if "listeners" in self:
            self['listeners'](event, *args, **kwargs)

    def __add__(self, listener):
        self.addSub('listeners', listener)

    def __sub__(self, listener):
        self.removeSub('listeners', listener)

    def __repr__(self):
        return "Listener %s"% dict.__repr__(self)
<commit_msg>little shorting<commit_after>'''
The following is from http://stackoverflow.com/a/2022629
Thanks to Longpoke
'''
import types

class Event(list):
    """Event subscription.

    A list of callable objects. Calling an instance of this will cause a
    call to each item in the list in ascending order by index.

    Example Usage:
    >>> def f(x):
    ...     print 'f(%s)' % x
    >>> def g(x):
    ...     print 'g(%s)' % x
    >>> e = Event()
    >>> e()
    >>> e.append(f)
    >>> e(123)
    f(123)
    >>> e.remove(f)
    >>> e()
    >>> e += (f, g)
    >>> e(10)
    f(10)
    # g(10)
    >>> del e[0]
    >>> e(2)
    g(2)

    """
    def __init__(self,repeat=True):
        super(Event,self).__init__()
        self.repeat = repeat

    def __call__(self, *args, **kwargs):
        for f in self:
            f(*args, **kwargs)
        if not self.repeat:
            map(lambda func: self.remove(func),self)

    def remove(self, func):
        if func in self:
            list.remove(self,func)

    def __repr__(self):
        #Make function names look prettier
        items = [item.__name__ if isinstance(item, types.FunctionType) or isinstance(item, types.MethodType)
                else item
                for item in self]
        return "Event %s" % list.__repr__(items)

class Listener(dict):
    def addSub(self, name, callback,repeat=True):
        '''sets self[name] to Event() if there is no key name.
           Either way self[name] is returned and callback is appended'''
        self.setdefault(name, Event(repeat)).append(callback)

    def removeSub(self, name, callback):
        if name in self:
            self[name].remove(callback)
            if len(self[name]) == 0:
                del self[name]

    def listen(self, event, repeat=True):
        def wrap(f):
            self.addSub(event, f,repeat)
            return f
        return wrap

    def trigger(self, event):
        def wrap(f):
            def newFunc(*args, **kwargs):
                res = f(*args, **kwargs)
                self(event, res)
                return res
            return newFunc
        return wrap

    def __call__(self, event, *args, **kwargs):
        if event in self:
            self[event](*args, **kwargs)
            if len(self[event])==0:
                self.removeSub(event,self[event])

        if "listeners" in self:
            self['listeners'](event, *args, **kwargs)

    def __add__(self, listener):
        self.addSub('listeners', listener)

    def __sub__(self, listener):
        self.removeSub('listeners', listener)

    def __repr__(self):
        return "Listener %s"% dict.__repr__(self)

    def getListeners(self):
        if "listeners" in self:
            return self['listeners']
        return None

    def isListener(self, listener):
        return listener in self.getListeners()
<|endoftext|>


<commit_before>import sublime
import sublime_plugin
import re

try:
  from Statement import statement
  from Expression import expression
except ImportError:
  sublime.error_message("Dependency import failed; please read readme for " +
   "JoinAssignment plugin for installation instructions; to disable this " +
   "message remove this plugin")

def _get_parts(view, point):
  container = statement.get_root_statement(view, point)
  if container == None:
    return None

  assignment_match = expression.find_match(view, container[0], r'\s+=\s+',
    {'range': container})

  if assignment_match == None:
    return None

  part_1 = [container[0], container[0] + assignment_match.start(0)]
  part_2 = [container[0] + assignment_match.end(0), container[1]]

  return part_1, part_2

class JoinAssignment(sublime_plugin.TextCommand):
  def run(self, edit):
    for selection in self.view.sel():
      self._join(edit, selection)

  def _join(self, edit, selection):
    if not selection.empty():
      return

    first = _get_parts(self.view, selection.b)
    if first == None:
      return

    region = sublime.Region(first[1][1], self.view.size())
    match = re.search(r'\S', self.view.substr(region))
    if match == None:
      return

    second = _get_parts(self.view, region.a + match.start(0))
    if second == None:
      return

    second_part_1, second_part_2 = second

    value_1 = ', ' + self.view.substr(sublime.Region(*second_part_1))
    value_2 = ', ' + self.view.substr(sublime.Region(*second_part_2))

    if re.search(r';$', value_2):
      value_2 = value_2[:-1]

    erase_region = self.view.full_line(sublime.Region(second_part_1[0],
      second_part_2[1]))
    self.view.erase(edit, erase_region)

    self._insert(edit, first[0], first[1], value_1, value_2)

  def _insert(self, edit, region_1, region_2, value_1, value_2):
    region_1_value = self.view.substr(sublime.Region(*region_1))
    region_2_value = self.view.substr(sublime.Region(*region_2))

    if region_2_value.endswith(';'):
      region_2_value = region_2_value[:-1]
      region_2[1] -= 1

    is_php = 'php' in self.view.scope_name(region_1[1])

    # php hack 1
    if is_php:
      if region_1_value.startswith('list('):
        region_1_value = region_1_value[:-1]
        region_1[1] -= 1
        region_2_value = region_2_value[:-1]
        region_2[1] -= 1

    self.view.insert(edit, region_2[1], value_2)
    self.view.insert(edit, region_1[1], value_1)

    # php hack 2
    if not is_php:
      return

    info = _get_parts(self.view, region_1[1])
    if info == None:
      return

    part_1, part_2 = info

    part_1_region = sublime.Region(*part_1)
    part_1_value = self.view.substr(part_1_region)

    part_2_region = sublime.Region(part_2[0], part_2[1])
    part_2_value = self.view.substr(part_2_region)

    if part_2_value.endswith(';'):
      part_2_value = part_2_value[:-1]
      part_2_region.b -= 1

    append_array = (not part_2_value.startswith('array(') and
      not part_2_value.startswith('['))

    if append_array:
      self.view.replace(edit, part_2_region, '[' + part_2_value + ']')

    if not part_1_value.startswith('list('):
      self.view.replace(edit, part_1_region, 'list(' + part_1_value + ')')

class UnjoinAssignment(sublime_plugin.TextCommand):
  def run(self, edit):
    for selection in self.view.sel():
      self._unjoin(edit, selection)

  def _unjoin(self, edit, selection):
    is_php = 'php' in self.view.scope_name(selection.b)
    tokens = self._get_tokens(selection, is_php)
    if tokens == None:
      return

    point, semicolon, tokens_1, tokens_2, _, _ = tokens
    if len(tokens_1) <= 1 or len(tokens_2) <= 1:
      return

    token_1 = self.view.substr(sublime.Region(*tokens_1[-1]))
    token_2 = self.view.substr(sublime.Region(*tokens_2[-1]))

    new_statement = "\n"

    line_region = self.view.line(tokens_1[0][0])
    spaces = re.search(r'^\s+', self.view.substr(line_region))
    if spaces:
      new_statement += spaces.group(0)

    new_statement += token_1 + ' = ' + token_2
    if semicolon:
      new_statement += ';'

    self.view.insert(edit, point, new_statement)

    self.view.erase(edit, sublime.Region(tokens_2[-2][1], tokens_2[-1][1]))
    self.view.erase(edit, sublime.Region(tokens_1[-2][1], tokens_1[-1][1]))

    if not is_php:
      return

    self._finalize(edit, tokens_1[0][0], is_php)

  def _finalize(self, edit, point, is_php):
    tokens = self._get_tokens(sublime.Region(point, point), is_php)
    if tokens == None:
      return

    _, semicolon, tokens_1, tokens_2, part_1, part_2 = tokens
    if len(tokens_1) != 1 or len(tokens_2) != 1:
      return

    part_2_value = self.view.substr(sublime.Region(*part_2))
    remove = None
    if part_2_value.startswith('array('):
      remove = 6
    elif part_2_value.startswith('['):
      remove = 1
    else:
      return

    if semicolon:
      shift = 1
    else:
      shift = 0

    erase_region = sublime.Region(part_2[1] - shift - 1, part_2[1] - shift)
    self.view.erase(edit, erase_region)
    self.view.erase(edit, sublime.Region(part_2[0], part_2[0] + remove))

    part_1_value = self.view.substr(sublime.Region(*part_1))
    if not part_1_value.startswith('list('):
      return

    self.view.erase(edit, sublime.Region(part_1[1] - 1, part_1[1]))
    self.view.erase(edit, sublime.Region(part_1[0], part_1[0] + 5))

  def _get_tokens(self, selection, is_php):
    if not selection.empty():
      return None

    parts = _get_parts(self.view, selection.b)
    if parts == None:
      return None

    part_1, part_2 = parts[0].copy(), parts[1].copy()
    point = part_2[1]

    part_1_value = self.view.substr(sublime.Region(*part_1))
    part_2_value = self.view.substr(sublime.Region(*part_2))

    semicolon = False;
    if part_2_value.endswith(';'):
      part_2_value = part_2_value[:-1]
      part_2[1] -= 1
      semicolon = True

    # php hacks
    if is_php:
      if part_1_value.startswith('list('):
        part_1[0] += 5
        part_1[1] -= 1

      if part_2_value.startswith('array('):
        part_2[0] += 5
        part_2[1] -= 1
      elif part_2_value.startswith('['):
        part_2[0] += 1
        part_2[1] -= 1

    tokens_1 = statement.get_tokens(self.view, selection.b, part_1)
    tokens_2 = statement.get_tokens(self.view, selection.b, part_2)

    return point, semicolon, tokens_1, tokens_2, parts[0], parts[1]<commit_msg>error notification modified<commit_after>import sublime
import sublime_plugin
import re

try:
  from Statement import statement
  from Expression import expression
except ImportError as error:
  sublime.error_message("Dependency import failed; please read readme for " +
   "JoinAssignment plugin for installation instructions; to disable this " +
   "message remove this plugin; message: " + str(error))
  raise error

def _get_parts(view, point):
  container = statement.get_root_statement(view, point)
  if container == None:
    return None

  assignment_match = expression.find_match(view, container[0], r'\s+=\s+',
    {'range': container})

  if assignment_match == None:
    return None

  part_1 = [container[0], container[0] + assignment_match.start(0)]
  part_2 = [container[0] + assignment_match.end(0), container[1]]

  return part_1, part_2

class JoinAssignment(sublime_plugin.TextCommand):
  def run(self, edit):
    for selection in self.view.sel():
      self._join(edit, selection)

  def _join(self, edit, selection):
    if not selection.empty():
      return

    first = _get_parts(self.view, selection.b)
    if first == None:
      return

    region = sublime.Region(first[1][1], self.view.size())
    match = re.search(r'\S', self.view.substr(region))
    if match == None:
      return

    second = _get_parts(self.view, region.a + match.start(0))
    if second == None:
      return

    second_part_1, second_part_2 = second

    value_1 = ', ' + self.view.substr(sublime.Region(*second_part_1))
    value_2 = ', ' + self.view.substr(sublime.Region(*second_part_2))

    if re.search(r';$', value_2):
      value_2 = value_2[:-1]

    erase_region = self.view.full_line(sublime.Region(second_part_1[0],
      second_part_2[1]))
    self.view.erase(edit, erase_region)

    self._insert(edit, first[0], first[1], value_1, value_2)

  def _insert(self, edit, region_1, region_2, value_1, value_2):
    region_1_value = self.view.substr(sublime.Region(*region_1))
    region_2_value = self.view.substr(sublime.Region(*region_2))

    if region_2_value.endswith(';'):
      region_2_value = region_2_value[:-1]
      region_2[1] -= 1

    is_php = 'php' in self.view.scope_name(region_1[1])

    # php hack 1
    if is_php:
      if region_1_value.startswith('list('):
        region_1_value = region_1_value[:-1]
        region_1[1] -= 1
        region_2_value = region_2_value[:-1]
        region_2[1] -= 1

    self.view.insert(edit, region_2[1], value_2)
    self.view.insert(edit, region_1[1], value_1)

    # php hack 2
    if not is_php:
      return

    info = _get_parts(self.view, region_1[1])
    if info == None:
      return

    part_1, part_2 = info

    part_1_region = sublime.Region(*part_1)
    part_1_value = self.view.substr(part_1_region)

    part_2_region = sublime.Region(part_2[0], part_2[1])
    part_2_value = self.view.substr(part_2_region)

    if part_2_value.endswith(';'):
      part_2_value = part_2_value[:-1]
      part_2_region.b -= 1

    append_array = (not part_2_value.startswith('array(') and
      not part_2_value.startswith('['))

    if append_array:
      self.view.replace(edit, part_2_region, '[' + part_2_value + ']')

    if not part_1_value.startswith('list('):
      self.view.replace(edit, part_1_region, 'list(' + part_1_value + ')')

class UnjoinAssignment(sublime_plugin.TextCommand):
  def run(self, edit):
    for selection in self.view.sel():
      self._unjoin(edit, selection)

  def _unjoin(self, edit, selection):
    is_php = 'php' in self.view.scope_name(selection.b)
    tokens = self._get_tokens(selection, is_php)
    if tokens == None:
      return

    point, semicolon, tokens_1, tokens_2, _, _ = tokens
    if len(tokens_1) <= 1 or len(tokens_2) <= 1:
      return

    token_1 = self.view.substr(sublime.Region(*tokens_1[-1]))
    token_2 = self.view.substr(sublime.Region(*tokens_2[-1]))

    new_statement = "\n"

    line_region = self.view.line(tokens_1[0][0])
    spaces = re.search(r'^\s+', self.view.substr(line_region))
    if spaces:
      new_statement += spaces.group(0)

    new_statement += token_1 + ' = ' + token_2
    if semicolon:
      new_statement += ';'

    self.view.insert(edit, point, new_statement)

    self.view.erase(edit, sublime.Region(tokens_2[-2][1], tokens_2[-1][1]))
    self.view.erase(edit, sublime.Region(tokens_1[-2][1], tokens_1[-1][1]))

    if not is_php:
      return

    self._finalize(edit, tokens_1[0][0], is_php)

  def _finalize(self, edit, point, is_php):
    tokens = self._get_tokens(sublime.Region(point, point), is_php)
    if tokens == None:
      return

    _, semicolon, tokens_1, tokens_2, part_1, part_2 = tokens
    if len(tokens_1) != 1 or len(tokens_2) != 1:
      return

    part_2_value = self.view.substr(sublime.Region(*part_2))
    remove = None
    if part_2_value.startswith('array('):
      remove = 6
    elif part_2_value.startswith('['):
      remove = 1
    else:
      return

    if semicolon:
      shift = 1
    else:
      shift = 0

    erase_region = sublime.Region(part_2[1] - shift - 1, part_2[1] - shift)
    self.view.erase(edit, erase_region)
    self.view.erase(edit, sublime.Region(part_2[0], part_2[0] + remove))

    part_1_value = self.view.substr(sublime.Region(*part_1))
    if not part_1_value.startswith('list('):
      return

    self.view.erase(edit, sublime.Region(part_1[1] - 1, part_1[1]))
    self.view.erase(edit, sublime.Region(part_1[0], part_1[0] + 5))

  def _get_tokens(self, selection, is_php):
    if not selection.empty():
      return None

    parts = _get_parts(self.view, selection.b)
    if parts == None:
      return None

    part_1, part_2 = parts[0].copy(), parts[1].copy()
    point = part_2[1]

    part_1_value = self.view.substr(sublime.Region(*part_1))
    part_2_value = self.view.substr(sublime.Region(*part_2))

    semicolon = False;
    if part_2_value.endswith(';'):
      part_2_value = part_2_value[:-1]
      part_2[1] -= 1
      semicolon = True

    # php hacks
    if is_php:
      if part_1_value.startswith('list('):
        part_1[0] += 5
        part_1[1] -= 1

      if part_2_value.startswith('array('):
        part_2[0] += 5
        part_2[1] -= 1
      elif part_2_value.startswith('['):
        part_2[0] += 1
        part_2[1] -= 1

    tokens_1 = statement.get_tokens(self.view, selection.b, part_1)
    tokens_2 = statement.get_tokens(self.view, selection.b, part_2)

    return point, semicolon, tokens_1, tokens_2, parts[0], parts[1]<|endoftext|>


<commit_before>import picamera
import picamera.array
import cv2
import time
import numpy as np
import multiprocessing as mp
import queue
import signal

def capture(q, stop, resolution=(640,480), framerate=30):
    print('Start capturing...')
    with picamera.PiCamera(resolution=resolution, framerate=framerate) as camera:
        with picamera.array.PiRGBArray(camera, size=resolution) as raw:
            start = cv2.getTickCount()
            for frame in camera.capture_continuous(raw, format="bgr", use_video_port=True):
                raw.truncate(0)
                try:
                    q.put(frame.array, False)
                except queue.Full:
                    print('capture: full')
                fps = cv2.getTickFrequency() / (cv2.getTickCount() - start)
                print('capture: ' + str(fps))
                start = cv2.getTickCount()
                if stop.is_set():
                    return

def process(q, stop):
    print('Start processing...')
    while not stop.is_set():
        start = cv2.getTickCount()
        try:
            frame = q.get(False)
        except queue.Empty:
            print('process: empty')
            time.sleep(0.1)
        else:
            #cv2.imshow('video', frame)
            time.sleep(0.03) # simulate 30ms processing
            fps = cv2.getTickFrequency() / (cv2.getTickCount() - start)
            print('process: ' + str(fps))
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    cv2.destroyAllWindows()

def main():
    q = mp.Queue(10)
    stop = mp.Event()
    def sigint(signal, frame):
        stop.set()
    signal.signal(signal.SIGINT, sigint)

    p = mp.Process(target=capture, args=(q, stop))
    p.start()
    process(q, stop)

    print('Shutdown')
    stop.set()
    # p.join()

if __name__ == "__main__":
    main()
<commit_msg>Fixed multiprocessing teardown<commit_after>import picamera
import picamera.array
import cv2
import time
import numpy as np
import multiprocessing as mp
import queue
import signal

def capture(q, stop, resolution=(640,480), framerate=30):
    print('Start capturing...')
    with picamera.PiCamera(resolution=resolution, framerate=framerate) as camera:
        with picamera.array.PiRGBArray(camera, size=resolution) as raw:
            start = cv2.getTickCount()
            for frame in camera.capture_continuous(raw, format="bgr", use_video_port=True):
                print('got frame')
                try:
                    q.put(frame.array, False)
                except queue.Full:
                    print('capture: full')
                raw.truncate(0)
                fps = cv2.getTickFrequency() / (cv2.getTickCount() - start)
                print('capture: ' + str(fps))
                start = cv2.getTickCount()
                if stop.is_set():
                    break
                print('loop')
    print('Capturing done')

def process(q, stop):
    print('Start processing...')
    while not stop.is_set():
        start = cv2.getTickCount()
        try:
            frame = q.get(False)
        except queue.Empty:
            print('process: empty')
            time.sleep(0.1)
        else:
            #cv2.imshow('video', frame)
            # if cv2.waitKey(1) & 0xFF == ord('q'):
            #     break
            time.sleep(0.03) # simulate 30ms processing
            fps = cv2.getTickFrequency() / (cv2.getTickCount() - start)
            print('process: ' + str(fps))
    cv2.destroyAllWindows()
    print('Processing done')

def main():
    q = mp.Queue(10)
    stop = mp.Event()
    def sigint(signal, frame):
        stop.set()
    signal.signal(signal.SIGINT, sigint)

    p = mp.Process(target=capture, args=(q, stop))
    p.start()
    process(q, stop)

    print('Shutdown')
    stop.set()
    q.close()
    q.join_thread()
    p.join() # TODO locks up

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


<commit_before>#!/usr/bin/python

import argparse
import commands
import logging
import os
import random
import signal
import sys
import thread
import time

from apscheduler.scheduler import Scheduler
from apscheduler.threadpool import ThreadPool

from core.irlp import Irlp
from core.voicesynthetizer import VoiceSynthetizer
from core.wolfram import Wolfram

from learning.morseteacher import MorseTeacher

from modules.alive import Alive
from modules.assistant import Assistant
from modules.aprstt import Aprstt
from modules.command import Command
from modules.commandterminal import CommandTerminal
from modules.clock import Clock
from modules.identification import Identification
from modules.messages import Messages
from modules.meteorology import Meteorology
from modules.news import News
from modules.poctwitter import PoCTwitter
from modules.seismology import Seismology
from modules.tracker import Tracker
from modules.voicemail import VoiceMail
from modules.weather import Weather

class Cancun(object):

    def __init__(self, voicesynthetizer, irlp):

        self.irlp = irlp
        self.voicesynthetizer = voicesynthetizer
        self.pidfile = None
        self.scheduler_status = False
        self.pidfile = "/tmp/cancun.pid"

    def __del__(self):
        pass

    def modules_setup(self):

        self.alive = Alive()
        self.aprstt = Aprstt(self.voicesynthetizer)
        self.assistant = Assistant(self.voicesynthetizer)
        self.command = Command(self.voicesynthetizer)
        self.commandterminal = CommandTerminal(self.voicesynthetizer)
        self.clock = Clock(self.voicesynthetizer)
        self.identification = Identification(self.voicesynthetizer)
        self.messages = Messages(self.voicesynthetizer)
        self.meteorology = Meteorology(self.voicesynthetizer)
        self.morseteacher = MorseTeacher(self.voicesynthetizer)
        self.news = News(self.voicesynthetizer)
        self.tracker = Tracker(self.voicesynthetizer)
        self.poctwitter = PoCTwitter(self.voicesynthetizer)
        self.seismology = Seismology(self.voicesynthetizer)
        self.voicemail = VoiceMail(self.voicesynthetizer)
        self.weather = Weather(self.voicesynthetizer)
        self.wolfram = Wolfram(self.voicesynthetizer)

    def dtmf_setup(self,dtmf):
        dtmf_codes = {
        'P1': 'identification',
        'P2': 'date',
        'P3': 'hour',
        'P4': 'weather',
        'P5': 'seismology',
        'P6': 'stations'
        }
        return dtmf_codes.get(dtmf)

    def enabled(self):
        return os.path.isfile(self.pidfile)

    def enable(self):

        pid = str(os.getpid())
        file(self.pidfile, 'w').write(pid)

    def disable(self):

        if self.enabled():
            os.unlink(self.pidfile)
        if self.scheduler_status:
            self.scheduler.shutdown()

    def scheduler_mode(self):

        print "[" + time.ctime() + "] Scheduler Mode\n"
        self.voicesynthetizer.speechit("Modo Planificador")

        self.scheduler = Scheduler(misfire_grace_time=900, coalesce=True, threadpool=ThreadPool(max_threads=1))
        self.schedule()
        self.scheduler.start()
        self.schedule_print()
        self.scheduler_status = True

        while True:
            time.sleep(5)
            if self.irlp.active():
                time.sleep(5)
                self.irlp.busy()
                self.voicesynthetizer.speechit("Se ha activado el nodo, Proyecto Cancun se despide, hasta pronto!")
                break

        self.disable()

    def writing_mode(self):

        print "[" + time.ctime() + "] Writing Mode\n"
        self.voicesynthetizer.speechit("Modo Escritura")

        while True:
            print " Type any text to make use of Text to Speech infraestructure"
            x = raw_input(" Type 'e' for exit: ")
            if x.lower() == 'e':
                self.disable()
                break;
            else:
                self.voicesynthetizer.speechit(x)
            time.sleep(1)

    def module_mode(self, module, dtmf):

        print "[" + time.ctime() + "] Module Mode\n"

        if module == 'alive':
            self.alive.report()
        elif module == 'identification':
            self.identification.identify()
        elif module == 'hour':
            self.clock.hour()
        elif module == 'date':
            self.clock.date()
        elif module == 'weather':
            self.weather.report()
        elif module == 'seismology':
            self.seismology.SismologicoMX()
        elif module == 'meteorology':
            self.meteorology.conagua_clima()
        elif module == 'morselearn':
            self.morseteacher.learn()
        elif module == 'morsecontest'	:
            self.morseteacher.contest()
        elif module == 'news':
            self.news.getitems()
	elif module == 'regulations':
            self.messages.readfile('learning/reglamentos.1')
	elif module == 'radioclub':
            self.messages.readfile('learning/arej.radioclubs')
        elif module == 'stations':
            self.messages.stations()
        elif module == 'tracker':
            self.tracker.query()
        elif module == 'vm':
            self.voicemail.run(dtmf)
        elif module == 'wolfram':
            self.wolfram.question('how many grams in kilograms')
        elif module == 'aprstt':
            self.aprstt.query(dtmf)
        elif module == 'terminal':
            self.commandterminal.execute()
        elif module == 'assistant':
            self.assistant.demo1()
        elif module == 'command':
            self.command.execute()
        elif module == 'bc':
            self.command.background()
        elif module == 'poctwitter':
            self.poctwitter.execute()
        else:
            print 'Module not found! Please check its name...\n'

        self.disable()

    def random_mode(self):

        print "[" + time.ctime() + "] Random Mode\n"
        self.voicesynthetizer.speechit("Modo Aleatorio")

        while True:
            modules = ['identification','date','hour', 'weather', 'sismology', 'terminal']
            random_module = modules[int(random.random() * len(modules))]
            random_time = random.randint(240,300)

            for i in range(random_time, 0, -1):
                print i
                time.sleep(1)

            if self.irlp.active():
                time.sleep(5)
                self.irlp.busy()
                self.voicesynthetizer.speechit("Se ha activado el nodo, Proyecto Cancun se despide, hasta pronto!")
                break

            self.module_mode(random_module, 'None')

        self.disable()

    def schedule_print(self):
        self.scheduler.print_jobs()

    def schedule(self):

        # Production Modules
        self.scheduler.add_interval_job(self.commandterminal.execute, minutes=30)
        self.scheduler.add_interval_job(self.identification.identify, minutes=30)
        self.scheduler.add_interval_job(self.clock.date, minutes=30)
        self.scheduler.add_interval_job(self.clock.hour, minutes=30)
        self.scheduler.add_interval_job(self.seismology.SismologicoMX, minutes=60)
        self.scheduler.add_interval_job(self.news.getitems, minutes=60)
        self.scheduler.add_interval_job(self.meteorology.conagua_clima, minutes=60)
        self.scheduler.add_interval_job(self.commandterminal.execute, minutes=120)
        self.scheduler.add_interval_job(self.weather.report, minutes=120)
        self.scheduler.add_interval_job(self.messages.stations, minutes=240)

        self.scheduler.add_cron_job(self.alive.report,month='*',day_of_week='*',hour='8,20',minute ='00',second='0')
        self.scheduler.add_cron_job(self.poctwitter.execute,month='*',day_of_week='*',hour='8,20',minute ='00',second='0')

	# Learning Modules, AREJ
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/arej.radioclubs'],month='*',day_of_week='*',hour='7,11,17',minute ='00',second='0')

        # Learning Modules, Morse
        self.scheduler.add_cron_job(self.morseteacher.learn,month='*',day='*',hour='7,12,18',minute ='30',second='0')
        self.scheduler.add_cron_job(self.morseteacher.contest,month='*',day='*',hour='7,12,18',minute ='45',second='0')

        # Learning Modules, Reglamentos
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.1'],month='*',day_of_week='mon,sat,sun',hour='8,13,19',minute ='00',second='0')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.2'],month='*',day_of_week='tue,sat,sun',hour='8,13,19',minute ='00',second='0')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.3'],month='*',day_of_week='wed,sat,sun',hour='8,13,19',minute ='00',second='0')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.4'],month='*',day_of_week='thu,sat,sun',hour='8,13,19',minute ='00',second='0')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.5'],month='*',day_of_week='fri,sat,sun',hour='8,13,19',minute ='00',second='0')

def set_exit_handler(func):
    signal.signal(signal.SIGTERM, func)

def on_exit(sig, func=None):
    print "exit handler triggered"
    sys.exit(1)

def main(argv):

    logging.basicConfig(filename='output/cancun.log', level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')

    irlp = Irlp()
    voicesynthetizer = VoiceSynthetizer("google", "spanish")

    parser = argparse.ArgumentParser(description='Cancun Project, Voice Services Experimental Project')
    parser.add_argument('-m', '--module', help='Module Mode')
    parser.add_argument('-s', '--server', help='Server mode')
    parser.add_argument('-d', '--dtmf', help='DMTF Code')
    args = parser.parse_args()

    if irlp.active():
        print "Nodo activo, no podemos iniciar Proyecto Cancun"
        sys.exit(1)

    experimental = Cancun(voicesynthetizer, irlp)

    if (args.module or args.server) and experimental.enabled():
        voicesynthetizer.speechit("Proyecto Cancun ya habilitado, no podemos iniciar otra instancia")
        sys.exit(1)

    if args.server == 'stop' and not experimental.enabled():
        voicesynthetizer.speechit("Proyecto Cancun deshabilitado")
        status, output = commands.getstatusoutput('./cancun.sh stop')
        sys.exit(1)

    if args.server == 'stop' and experimental.enabled():
        voicesynthetizer.speechit("Deshabilitando Proyecto Cancun, hasta pronto!")
        status, output = commands.getstatusoutput('./cancun.sh stop')
        sys.exit(1)

    experimental.enable()
    experimental.modules_setup()

    if args.module:
        experimental.module_mode(args.module, args.dtmf)

    if args.server == 'scheduler':
        experimental.scheduler_mode()

    elif args.server == 'random':
        experimental.random_mode()

    elif args.server == 'writing':
        experimental.writing_mode()

    if args.dtmf:
        if len(args.dtmf) == 2:
            module = experimental.dtmf_setup(args.dtmf)
            experimental.module_mode(module, args.dtmf)
        else:
            experimental.module_mode('aprstt', args.dtmf)

    experimental.disable()

if __name__ == "__main__":

    main(sys.argv[1:])
<commit_msg>General: Cancun Module Refactoring<commit_after>#!/usr/bin/python

import argparse
import commands
import logging
import os
import random
import signal
import sys
import thread
import time

from apscheduler.scheduler import Scheduler
from apscheduler.threadpool import ThreadPool

from core.irlp import Irlp
from core.voicesynthetizer import VoiceSynthetizer
from core.wolfram import Wolfram

from learning.morseteacher import MorseTeacher

from modules.alive import Alive
from modules.assistant import Assistant
from modules.aprstt import Aprstt
from modules.command import Command
from modules.commandterminal import CommandTerminal
from modules.clock import Clock
from modules.identification import Identification
from modules.messages import Messages
from modules.meteorology import Meteorology
from modules.news import News
from modules.poctwitter import PoCTwitter
from modules.seismology import Seismology
from modules.tracker import Tracker
from modules.voicemail import VoiceMail
from modules.weather import Weather

class Cancun(object):

    def __init__(self, voicesynthetizer, irlp):

        self.irlp = irlp
        self.voicesynthetizer = voicesynthetizer
        self.pidfile = None
        self.scheduler_status = False
        self.pidfile = "/tmp/cancun.pid"

    def __del__(self):
        pass

    def modules_setup(self):

        # Production
        self.identification = Identification(self.voicesynthetizer)
        self.clock = Clock(self.voicesynthetizer)
        self.weather = Weather(self.voicesynthetizer)

        # Experimental
        self.alive = Alive()
        self.aprstt = Aprstt(self.voicesynthetizer)
        self.assistant = Assistant(self.voicesynthetizer)
        self.command = Command(self.voicesynthetizer)
        self.commandterminal = CommandTerminal(self.voicesynthetizer)
        self.messages = Messages(self.voicesynthetizer)
        self.meteorology = Meteorology(self.voicesynthetizer)
        self.morseteacher = MorseTeacher(self.voicesynthetizer)
        self.news = News(self.voicesynthetizer)
        self.tracker = Tracker(self.voicesynthetizer)
        self.poctwitter = PoCTwitter(self.voicesynthetizer)
        self.seismology = Seismology(self.voicesynthetizer)
        self.voicemail = VoiceMail(self.voicesynthetizer)
        self.wolfram = Wolfram(self.voicesynthetizer)

    def dtmf_setup(self,dtmf):
        dtmf_codes = {
        'S00': 'alive',
        'S01': 'identification',
        'S02': 'hour',
        'S03': 'date',
        'S04': 'weather',
        }
        return dtmf_codes.get(dtmf)

    def enabled(self):
        return os.path.isfile(self.pidfile)

    def enable(self):

        pid = str(os.getpid())
        file(self.pidfile, 'w').write(pid)

    def disable(self):

        if self.enabled():
            os.unlink(self.pidfile)
        if self.scheduler_status:
            self.scheduler.shutdown()

    def scheduler_mode(self):

        print "[" + time.ctime() + "] Scheduler Mode\n"
        self.voicesynthetizer.speechit("Modo Planificador")

        self.scheduler = Scheduler(misfire_grace_time=900, coalesce=True, threadpool=ThreadPool(max_threads=1))
        self.schedule()
        self.scheduler.start()
        self.schedule_print()
        self.scheduler_status = True

        while True:
            time.sleep(5)
            if self.irlp.active():
                time.sleep(5)
                self.irlp.busy()
                self.voicesynthetizer.speechit("Se ha activado el nodo, Proyecto Cancun se despide, hasta pronto!")
                break

        self.disable()

    def writing_mode(self):

        print "[" + time.ctime() + "] Writing Mode\n"
        self.voicesynthetizer.speechit("Modo Escritura")

        while True:
            print " Type any text to make use of Text to Speech infraestructure"
            x = raw_input(" Type 'e' for exit: ")
            if x.lower() == 'e':
                self.disable()
                break;
            else:
                self.voicesynthetizer.speechit(x)
            time.sleep(1)

    def module_mode(self, module, dtmf):

        print "[" + time.ctime() + "] Module Mode\n"

        if module == 'alive':
            self.alive.report()
        elif module == 'identification':
            self.identification.identify()
        elif module == 'hour':
            self.clock.hour()
        elif module == 'date':
            self.clock.date()
        elif module == 'weather':
            self.weather.report()
        elif module == 'seismology':
            self.seismology.SismologicoMX()
        elif module == 'meteorology':
            self.meteorology.conagua_clima()
        elif module == 'morselearn':
            self.morseteacher.learn()
        elif module == 'morsecontest'	:
            self.morseteacher.contest()
        elif module == 'news':
            self.news.getitems()
	elif module == 'regulations':
            self.messages.readfile('learning/reglamentos.1')
	elif module == 'radioclub':
            self.messages.readfile('learning/arej.radioclubs')
        elif module == 'stations':
            self.messages.stations()
        elif module == 'tracker':
            self.tracker.query()
        elif module == 'vm':
            self.voicemail.run(dtmf)
        elif module == 'wolfram':
            self.wolfram.question('how many grams in kilograms')
        elif module == 'aprstt':
            self.aprstt.query(dtmf)
        elif module == 'terminal':
            self.commandterminal.execute()
        elif module == 'assistant':
            self.assistant.demo1()
        elif module == 'command':
            self.command.execute()
        elif module == 'bc':
            self.command.background()
        elif module == 'poctwitter':
            self.poctwitter.execute()
        else:
            print 'Module not found! Please check its name...\n'

        self.disable()

    def random_mode(self):

        print "[" + time.ctime() + "] Random Mode\n"
        self.voicesynthetizer.speechit("Modo Aleatorio")

        while True:
            modules = ['identification','date','hour', 'weather', 'sismology', 'terminal']
            random_module = modules[int(random.random() * len(modules))]
            random_time = random.randint(240,300)

            for i in range(random_time, 0, -1):
                print i
                time.sleep(1)

            if self.irlp.active():
                time.sleep(5)
                self.irlp.busy()
                self.voicesynthetizer.speechit("Se ha activado el nodo, Proyecto Cancun se despide, hasta pronto!")
                break

            self.module_mode(random_module, 'None')

        self.disable()

    def schedule_print(self):
        self.scheduler.print_jobs()

    def schedule(self):

        # Production Modules
        self.scheduler.add_interval_job(self.commandterminal.execute, minutes=30)
        self.scheduler.add_interval_job(self.identification.identify, minutes=30)
        self.scheduler.add_interval_job(self.clock.date, minutes=30)
        self.scheduler.add_interval_job(self.clock.hour, minutes=30)
        self.scheduler.add_interval_job(self.seismology.SismologicoMX, minutes=60)
        self.scheduler.add_interval_job(self.news.getitems, minutes=60)
        self.scheduler.add_interval_job(self.meteorology.conagua_clima, minutes=60)
        self.scheduler.add_interval_job(self.commandterminal.execute, minutes=120)
        self.scheduler.add_interval_job(self.weather.report, minutes=120)
        self.scheduler.add_interval_job(self.messages.stations, minutes=240)

        self.scheduler.add_cron_job(self.alive.report,month='*',day_of_week='*',hour='8,20',minute ='00',second='0')
        self.scheduler.add_cron_job(self.poctwitter.execute,month='*',day_of_week='*',hour='8,20',minute ='00',second='0')

	# Learning Modules, AREJ
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/arej.radioclubs'],month='*',day_of_week='*',hour='7,11,17',minute ='00',second='0')

        # Learning Modules, Morse
        self.scheduler.add_cron_job(self.morseteacher.learn,month='*',day='*',hour='7,12,18',minute ='30',second='0')
        self.scheduler.add_cron_job(self.morseteacher.contest,month='*',day='*',hour='7,12,18',minute ='45',second='0')

        # Learning Modules, Reglamentos
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.1'],month='*',day_of_week='mon,sat,sun',hour='8,13,19',minute ='00',second='0')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.2'],month='*',day_of_week='tue,sat,sun',hour='8,13,19',minute ='00',second='0')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.3'],month='*',day_of_week='wed,sat,sun',hour='8,13,19',minute ='00',second='0')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.4'],month='*',day_of_week='thu,sat,sun',hour='8,13,19',minute ='00',second='0')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.5'],month='*',day_of_week='fri,sat,sun',hour='8,13,19',minute ='00',second='0')

def set_exit_handler(func):
    signal.signal(signal.SIGTERM, func)

def on_exit(sig, func=None):
    print "exit handler triggered"
    sys.exit(1)

def main(argv):

    logging.basicConfig(filename='output/cancun.log', level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')

    irlp = Irlp()
    voicesynthetizer = VoiceSynthetizer("google", "spanish")

    parser = argparse.ArgumentParser(description='Cancun Project, Voice Services Experimental Project')
    parser.add_argument('-m', '--module', help='Module Mode')
    parser.add_argument('-s', '--server', help='Server mode')
    parser.add_argument('-d', '--dtmf', help='DMTF Code')
    args = parser.parse_args()

    if irlp.active():
        print "Nodo activo, no podemos iniciar Proyecto Cancun"
        sys.exit(1)

    experimental = Cancun(voicesynthetizer, irlp)

    if (args.module or args.server) and experimental.enabled():
        voicesynthetizer.speechit("Proyecto Cancun ya habilitado, no podemos iniciar otra instancia")
        sys.exit(1)

    if args.server == 'stop' and not experimental.enabled():
        voicesynthetizer.speechit("Proyecto Cancun deshabilitado")
        status, output = commands.getstatusoutput('./cancun.sh stop')
        sys.exit(1)

    if args.server == 'stop' and experimental.enabled():
        voicesynthetizer.speechit("Deshabilitando Proyecto Cancun, hasta pronto!")
        status, output = commands.getstatusoutput('./cancun.sh stop')
        sys.exit(1)

    experimental.enable()
    experimental.modules_setup()

    if args.module:
        experimental.module_mode(args.module, args.dtmf)

    if args.server == 'scheduler':
        experimental.scheduler_mode()

    elif args.server == 'random':
        experimental.random_mode()

    elif args.server == 'writing':
        experimental.writing_mode()

    if args.dtmf:
        logging.info(args.dtmf)
        if len(args.dtmf) == 3:
            module = experimental.dtmf_setup(args.dtmf)
            experimental.module_mode(module, args.dtmf)
        elif len(args.dtmf) > 10:
            experimental.module_mode('aprstt', args.dtmf)

    experimental.disable()

if __name__ == "__main__":

    main(sys.argv[1:])
<|endoftext|>


<commit_before>"""
abuse.ch Zeus Config RSS feed bot.

Maintainer: Lari Huttunen <mit-code@huttu.net>
"""

from abusehelper.core import bot

from . import host_or_ip_from_url, split_description, AbuseCHFeedBot

class ZeusConfigBot(AbuseCHFeedBot):
    feed_malware = "ZeuS"
    feed_type = "malware configuration"

    feeds = bot.ListParam(default=["https://zeustracker.abuse.ch/monitor.php?urlfeed=configs"])

    def parse_description(self, description):
        for key, value in split_description(description):
            if key == ["status", "version"]:
                yield key, value
            elif key == "md5 hash":
                yield "md5", value
            elif key == "URL":
                yield "url", value
                yield host_or_ip_from_url(value)

if __name__ == "__main__":
    ZeusConfigBot.from_command_line().execute()
<commit_msg>abusehelper.contrib.abusech.zeusconfigbot: Fix issue #41.<commit_after>"""
abuse.ch Zeus Config RSS feed bot.

Maintainer: Lari Huttunen <mit-code@huttu.net>
"""

from abusehelper.core import bot

from . import host_or_ip_from_url, split_description, AbuseCHFeedBot

class ZeusConfigBot(AbuseCHFeedBot):
    feed_malware = "ZeuS"
    feed_type = "malware configuration"

    feeds = bot.ListParam(default=["https://zeustracker.abuse.ch/monitor.php?urlfeed=configs"])

    def parse_description(self, description):
        for key, value in split_description(description):
            if key in ["status", "version"]:
                yield key, value
            elif key == "md5 hash":
                yield "md5", value
            elif key == "URL":
                yield "url", value
                yield host_or_ip_from_url(value)

if __name__ == "__main__":
    ZeusConfigBot.from_command_line().execute()
<|endoftext|>


<commit_before>import sublime
import sublime_plugin

import re

try:
  from Statement import statement
  from Expression import expression
except ImportError:
  sublime.error_message("Dependency import failed; please read readme for " +
   "JoinChainCall plugin for installation instructions; to disable this " +
   "message remove this plugin")

def _get_token(view, selection):
  if not selection.empty():
    container = [selection.begin(), selection.end()]
  else:
    container = statement.get_root_statement(view, selection.b)

  tokens = container and statement.get_tokens(view, selection.b, container)

  _, token = tokens and statement.get_token(view, selection.b, tokens)
  return token

def join(view, edit, selection):
  token = _get_token(view, selection)
  if token == None:
    return

  delimeters = expression.find_matches(view, token[0], r'(\.|->)\s+',
    {'range': token})

  for delimeter in reversed(delimeters):
    region = sublime.Region(
      token[0] + delimeter.start(0),
      token[0] + delimeter.end(0)
    )

    view.replace(edit, region, delimeter.group(1))

def unjoin(view, edit, selection):
  token = _get_token(view, selection)
  if token == None:
    return

  line = view.substr(view.line(token[0]))
  indent = re.search(r'^(\s*)', line).group(1)
  delimeters = expression.find_matches(view, token[0], r'(\.|->)',
    {'range': token})

  for delimeter in reversed(delimeters):
    region = sublime.Region(
      token[0] + delimeter.start(0),
      token[0] + delimeter.end(0)
    )

    view.replace(edit, region, delimeter.group(1) + "\n" + indent + "\t")

def toggle(view, edit, selection):
  token = _get_token(view, selection)
  if token == None:
    return

  delimeter = expression.find_match(view, token[0], r'(?:\.|->)\s*',
    {'range': token})

  if delimeter == None:
    return

  if "\n" in delimeter.group(0):
    join(view, edit, selection)
  else:
    unjoin(view, edit, selection)<commit_msg>error notification modified<commit_after>import sublime
import sublime_plugin

import re

try:
  from Statement import statement
  from Expression import expression
except ImportError as error:
  sublime.error_message("Dependency import failed; please read readme for " +
   "JoinChainCall plugin for installation instructions; to disable this " +
   "message remove this plugin; message: " + str(error))
  raise error

def _get_token(view, selection):
  if not selection.empty():
    container = [selection.begin(), selection.end()]
  else:
    container = statement.get_root_statement(view, selection.b)

  tokens = container and statement.get_tokens(view, selection.b, container)

  _, token = tokens and statement.get_token(view, selection.b, tokens)
  return token

def join(view, edit, selection):
  token = _get_token(view, selection)
  if token == None:
    return

  delimeters = expression.find_matches(view, token[0], r'(\.|->)\s+',
    {'range': token})

  for delimeter in reversed(delimeters):
    region = sublime.Region(
      token[0] + delimeter.start(0),
      token[0] + delimeter.end(0)
    )

    view.replace(edit, region, delimeter.group(1))

def unjoin(view, edit, selection):
  token = _get_token(view, selection)
  if token == None:
    return

  line = view.substr(view.line(token[0]))
  indent = re.search(r'^(\s*)', line).group(1)
  delimeters = expression.find_matches(view, token[0], r'(\.|->)',
    {'range': token})

  for delimeter in reversed(delimeters):
    region = sublime.Region(
      token[0] + delimeter.start(0),
      token[0] + delimeter.end(0)
    )

    view.replace(edit, region, delimeter.group(1) + "\n" + indent + "\t")

def toggle(view, edit, selection):
  token = _get_token(view, selection)
  if token == None:
    return

  delimeter = expression.find_match(view, token[0], r'(?:\.|->)\s*',
    {'range': token})

  if delimeter == None:
    return

  if "\n" in delimeter.group(0):
    join(view, edit, selection)
  else:
    unjoin(view, edit, selection)<|endoftext|>


<commit_before># basinBump.py
# Rebuilds an elevation model with breaks (increase elevation), burns (decrease elevation)
# and drains (assigned nodata locations).  These forcings allow an accurate hydrological
# deliniation for the elevation surface.
#
# Author: scw <walbridge@nceas.ucsb.edu>
# Date: 3.27.2006
# Usage: basinBump <elevation> <breaks_shp> <burns_shp> <drains_shp> <output dir> <output prefix>

# Import system modules
import sys, string, os, win32com.client

# Geoprocessor configuration
gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") # Create the geoprocessor object
gp.CheckOutExtension("spatial")                                 # Check out the required license
gp.overwriteoutput = 1                                          # Overwrite existing files

if len(sys.argv) < 6:
	print "Usage: basinBump <elevation> <breaks_shp> <burns_shp> <drains_shp> <output dir> <output prefix>"
	sys.exit()

outputDir  = sys.argv[5]
outputName = sys.argv[6]
outputBase = outputDir + '\\' + outputName

inElem = { 'DEM'   : sys.argv[1], 'breaks' : sys.argv[2], \
           'burns' : sys.argv[3], 'drains' : sys.argv[4]}

for elemName, elemPath in inElem.items():
    (path, filename) = os.path.split(elemPath)
    if path == '':
        inElem[elemName] = outputDir + "\\" + filename

# Extent and cellsize should match input DEM
gp.extent   = inElem['DEM']
gp.cellsize = inElem['DEM']

'''print outputBase
print inElem
sys.exit()
'''

# output data
break_0 = outputBase + '_bk0'
burn_0  = outputBase + '_bn0'
drain_0 = outputBase + '_dn0'
drain_1 = outputBase + '_dn1'
drain_2 = outputBase + '_dn2'
drain_3 = outputBase + '_dn3'
combine = outputBase + '_dem'

try:
    print "F to R"
    # Process: Feature to Raster...
    gp.FeatureToRaster_conversion(inElem['breaks'], "Id", break_0, gp.cellsize)

    print "F to R2"
    # Process: Feature to Raster (2)...
    gp.FeatureToRaster_conversion(inElem['burns'], "Id", burn_0, gp.cellsize)

    print "F to R3"
    # Process: Feature to Raster (3)...
    gp.FeatureToRaster_conversion(inElem['drains'], "Id", drain_0, gp.cellsize)

    # Process: Is Null...
    gp.IsNull_sa(drain_0, drain_1)

    # Process: Con...
    gp.Con_sa(drain_1, '0', drain_2, '1', "")

    # Process: Set Null...
    gp.SetNull_sa(drain_2, '0', drain_3, "")

    print "At Map Algebra."
    # Process: Single Output Map Algebra...
    gp.SingleOutputMapAlgebra_sa("con(isnull(%s), 0, 200) + con(isnull(%s), 0, -400) + %s + %s" % (break_0, burn_0, drain_3, inElem['DEM']), combine)

    # Process: Build Pyramids...
    gp.BuildPyramids_management(combine)

except:
    # report geoprocessing errors
    print gp.GetMessages()
<commit_msg>Added infills to the basin bump process. Made some changes to debugging output and lazy argument handling.<commit_after># basinBump.py
# Rebuilds an elevation model with breaks (increase elevation), burns (decrease elevation)
# and drains (assigned nodata locations).  These forcings allow an accurate hydrological
# deliniation for the elevation surface.
#
# Author: scw <walbridge@nceas.ucsb.edu>
# Date: 3.27.2006
# Usage: basinBump <elevation> <breaks_shp> <burns_shp> <drains_shp> <output dir> <output prefix>

# Import system modules
import sys, string, os, win32com.client

# Geoprocessor configuration
gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") # Create the geoprocessor object
gp.CheckOutExtension("spatial")                                 # Check out the required license
gp.overwriteoutput = 1                                          # Overwrite existing files

# Load required toolboxes...
#gp.AddToolbox("F:/gis/a9/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
#gp.AddToolbox("F:/gis/a9/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
#gp.AddToolbox("F:/gis/a9/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")

#if len(sys.argv) < 6:
#	print "Usage: basinBump <elevation> <infill_shp> <breaks_shp> <burns_shp> <drains_shp> <output dir> <output prefix>"
#	sys.exit()

try:
    demarg = sys.argv[1]
    infillarg = sys.argv[2]
    breaksarg = sys.argv[3]
    burnsarg = sys.argv[4]
    drainsarg = sys.argv[5]
    outputDir  = sys.argv[6]
    outputName = sys.argv[7]
except:
    ########## EDIT THESE IF YOU'RE LAZY AND DONT WANT TO TYPE CL PARAMS #######
    outputName = "af"
    outputDir  = "C:\\WorkSpace\\srtm_basins\\af_basins\\build_try4"
    ### and to a lesser extent, these
    demarg = "C:\\WorkSpace\\srtm_basins\\af_basins\\af_ult_fix2"
    infillarg = "C:\\WorkSpace\\srtm_basins\\af_basins\\af_fills.shp"
    breaksarg = "C:\\WorkSpace\\srtm_basins\\af_basins\\af_breaks.shp"
    burnsarg = "C:\\WorkSpace\\srtm_basins\\af_basins\\af_burns.shp"
    drainsarg = "C:\\WorkSpace\\srtm_basins\\af_basins\\af_drains.shp"
    ###########

outputBase = outputDir + "\\" + outputName

inElem = { 'DEM'   : demarg, 'breaks' : breaksarg, \
           'burns' : burnsarg, 'drains' : drainsarg, 'infill': infillarg}

for elemName, elemPath in inElem.items():
    (path, filename) = os.path.split(elemPath)
    if path == '':
        inElem[elemName] = outputDir + "\\" + filename

# Extent and cellsize should match input DEM
gp.extent   = inElem['DEM']
gp.cellsize = inElem['DEM']

'''print outputBase
print inElem
sys.exit()
'''

# output data
infill_0 = outputBase + '_if0'
infill_1 = outputBase + '_if1'
break_0 = outputBase + '_bk0'
burn_0  = outputBase + '_bn0'
drain_0 = outputBase + '_dn0'
drain_1 = outputBase + '_dn1'
drain_2 = outputBase + '_dn2'
drain_3 = outputBase + '_dn3'
combine = outputBase + '_dem'

try:
    print "Infilling the DEM"
    # Process: Feature to Raster...
    gp.FeatureToRaster_conversion(inElem['infill'], "Id", infill_0, gp.cellsize)
    gp.SingleOutputMapAlgebra_sa("con( isnull( %s ), %s, %s )" \
                                 % (inElem['DEM'], infill_0, inElem['DEM']), infill_1)

    print "Rasterizing breaks"
    # Process: Feature to Raster...
    gp.FeatureToRaster_conversion(inElem['breaks'], "Id", break_0, gp.cellsize)

    print "Rasterizing burns"
    # Process: Feature to Raster (2)...
    gp.FeatureToRaster_conversion(inElem['burns'], "Id", burn_0, gp.cellsize)

    print "Rasterizing drains"
    # Process: Feature to Raster (3)...
    gp.FeatureToRaster_conversion(inElem['drains'], "Id", drain_0, gp.cellsize)

    # Process: Is Null...
    gp.IsNull_sa(drain_0, drain_1)

    # Process: Con...
    gp.Con_sa(drain_1, '0', drain_2, '1', "")

    # Process: Set Null...
    gp.SetNull_sa(drain_2, '0', drain_3, "")

    print "Combining layers into one modified DEM"
    # Process: Single Output Map Algebra...
    gp.SingleOutputMapAlgebra_sa("con(isnull(%s), 0, 200) + con(isnull(%s), 0, -400) + %s + %s" % (break_0, burn_0, drain_3, infill_1), combine)

    print "Building Pyrimids"
    # Process: Build Pyramids...
    gp.BuildPyramids_management(combine)

except:
    # report geoprocessing errors
    print gp.GetMessages()
<|endoftext|>


<commit_before># Copyright 2017 TensorHub, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division

import os
import re
import sys

import click

def print_info():
    _print_tensorflow_info()
    _print_tensorboard_info()

def _print_tensorflow_info():
    try:
        import tensorflow as tf
    except ImportError as e:
        msg = _normalize_import_error_msg(e)
        err = _warn("NOT INSTALLED (%s)" % msg)
        click.echo("tensorflow_version:        %s" % err)
        sys.exit(1)
    else:
        click.echo("tensorflow_version:        %s" % _tf_version(tf))
        click.echo("tensorflow_cuda_support:   %s" % _cuda_support(tf))
        click.echo("tensorflow_gpu_available:  %s" % _gpu_available(tf))
        _print_cuda_info()

def _tf_version(tf):
    return tf.__version__

def _cuda_support(tf):
    return "yes" if tf.test.is_built_with_cuda() else "no"

def _gpu_available(tf):
    return "yes" if tf.test.is_gpu_available() else "no"

def _print_cuda_info():
    proc_maps = "/proc/%s/maps" % os.getpid()
    if not os.path.exists(proc_maps):
        return
    raw = open(proc_maps, "r").read()
    version_patterns = [
        ("libcuda", "libcuda\\.so\\.([\\S]+)"),
        ("libcudnn", "libcudnn\\.so\\.([\\S]+)"),
    ]
    for name, pattern in version_patterns:
        m = re.search(pattern, raw)
        space = " " * (18 - len(name))
        if m:
            click.echo("%s_version:%s%s" % (name, space, m.group(1)))
        else:
            click.echo("%s_version:%snot loaded" % (name, space))

def _print_tensorboard_info():
    try:
        import tensorboard.version as version
    except ImportError as e:
        msg = _normalize_import_error_msg(e)
        click.echo("tensorboard_version:       %s" % _warn("NOT INSTALLED (%s)" % msg))
    else:
        click.echo("tensorboard_version:       %s" % version.VERSION)

def _normalize_import_error_msg(e):
    msg = str(e)
    m = re.match("No module named ([^']+)", msg)
    if m:
        return "No module named '%s'" % m.group(1)
    return msg

def _warn(msg):
    return click.style(msg, fg="red", bold=True)

if __name__ == "__main__":
    print_info()
<commit_msg>Reorder tensorflow check info<commit_after># Copyright 2017 TensorHub, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division

import os
import re
import sys

import click

def print_info():
    try:
        import tensorflow as tf
    except ImportError as e:
        msg = _normalize_import_error_msg(e)
        err = _warn("NOT INSTALLED (%s)" % msg)
        click.echo("tensorflow_version:        %s" % err)
        sys.exit(1)
    else:
        click.echo("tensorflow_version:        %s" % _tf_version(tf))
        click.echo("tensorflow_cuda_support:   %s" % _cuda_support(tf))
        click.echo("tensorflow_gpu_available:  %s" % _gpu_available(tf))
        _print_tensorboard_info()
        _print_cuda_info()

def _tf_version(tf):
    return tf.__version__

def _cuda_support(tf):
    return "yes" if tf.test.is_built_with_cuda() else "no"

def _gpu_available(tf):
    return "yes" if tf.test.is_gpu_available() else "no"

def _print_tensorboard_info():
    try:
        import tensorboard.version as version
    except ImportError as e:
        msg = _normalize_import_error_msg(e)
        click.echo("tensorboard_version:       %s" % _warn("NOT INSTALLED (%s)" % msg))
    else:
        click.echo("tensorboard_version:       %s" % version.VERSION)

def _print_cuda_info():
    proc_maps = "/proc/%s/maps" % os.getpid()
    if not os.path.exists(proc_maps):
        return
    raw = open(proc_maps, "r").read()
    version_patterns = [
        ("libcuda", "libcuda\\.so\\.([\\S]+)"),
        ("libcudnn", "libcudnn\\.so\\.([\\S]+)"),
    ]
    for name, pattern in version_patterns:
        m = re.search(pattern, raw)
        space = " " * (18 - len(name))
        if m:
            click.echo("%s_version:%s%s" % (name, space, m.group(1)))
        else:
            click.echo("%s_version:%snot loaded" % (name, space))

def _normalize_import_error_msg(e):
    msg = str(e)
    m = re.match("No module named ([^']+)", msg)
    if m:
        return "No module named '%s'" % m.group(1)
    return msg

def _warn(msg):
    return click.style(msg, fg="red", bold=True)

if __name__ == "__main__":
    print_info()
<|endoftext|>


<commit_before>#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.

from multiprocessing import Process, Queue, Manager, freeze_support
#from gtk.gdk import threads_enter, threads_leave

class ServerBuffer(Process):
    def __init__(self):
        super(ServerBuffer, self).__init__()
        self.op_queue = Queue()
    @property
    def server_connection(self):
        if hasattr(self, '_serverconnection'):
            return self._serverconnection
        else:
            return None
    @server_connection.setter
    def server_connection(self, connection):
        self._serverconnection = connection
    # ------------------- OVERIDE THESE -------------------
    def something_to_be_overridden(self):
        pass

class Composer(Process):
    def __init__(self, operation_queue):
        super(Composer, self).__init__()

class Transformer(Process):
    def __init__(self):
        super(Transformer, self).__init__()

class Initialiser:
    def __call__(self):
        pass
    def __init__(self):
        self.manager = Manager()

if __name__ == "__main__":
    freeze_support()

# ---------------------------- DESIGN INTENTIONS ------------------------------
#
# This module will contain the following:
#   * A 'server buffer', which will control the sending and recieving of
#       operations to and from the server.
#       The buffer will have it's own processes (2), so as the sending and
#       recieving  of operations will not make the rest of the app 'hang'.
#       The buffer will send and recieve operations to/from the transformer by
#       means of a Pipe.
#   * A 'composer' to combine operations.
#   * A 'transformer' to transform operations.
#   * A Manager class of some sort, to organise the whole shebang.
<commit_msg>Made NetworkTools.models.ot.ServerBuffer 's op_queue (multiprocessing.Queue) a name mangled attribute, and gave it a read only property.<commit_after>#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.

from multiprocessing import Process, Queue, Manager, freeze_support
#from gtk.gdk import threads_enter, threads_leave

class ServerBuffer(Process):
    def __init__(self):
        super(ServerBuffer, self).__init__()
        self.__op_queue = Queue()
    @property
    def op_queue(self):
        """As it is incredibly important that the Op Queue doesn't get
        replaced with anything else, the op_queue attribute has been stuck
        through Python name mangling."""
        return self.__op_queue
    def
    @property
    def server_connection(self):
        if hasattr(self, '_serverconnection'):
            return self._serverconnection
        else:
            return None
    @server_connection.setter
    def server_connection(self, connection):
        self._serverconnection = connection
    # ------------------- OVERIDE THESE -------------------
    def something_to_be_overridden(self):
        pass

class Composer(Process):
    def __init__(self, operation_queue):
        super(Composer, self).__init__()

class Transformer(Process):
    def __init__(self):
        super(Transformer, self).__init__()

class Initialiser:
    def __call__(self):
        pass
    def __init__(self):
        self.manager = Manager()

if __name__ == "__main__":
    freeze_support()

# ---------------------------- DESIGN INTENTIONS ------------------------------
#
# This module will contain the following:
#   * A 'server buffer', which will control the sending and recieving of
#       operations to and from the server.
#       The buffer will have it's own processes (2), so as the sending and
#       recieving  of operations will not make the rest of the app 'hang'.
#       The buffer will send and recieve operations to/from the transformer by
#       means of a Pipe.
#   * A 'composer' to combine operations.
#   * A 'transformer' to transform operations.
#   * A Manager class of some sort, to organise the whole shebang.
<|endoftext|>


<commit_before>#!/usr/bin/python
# _*_ coding: UTF-8 _*_

# create: 2016/10/18
# version: 0.0.1
# author: Junhg
# contribute:
#
__author__ = 'Junhg'

import os
from ViewObject.CommonObject import JHCommomObject
from ViewObject.ViewObject import JHViewObject
from ViewObject.BasicObject import JHBasicObject
from ViewObject.ActivityIndicatorObject import JHActivityIndicatorObject
from ViewObject.ButtonObject import JHButtonObject
from ViewObject.CollectionViewObject import JHCollectionViewObject
from ViewObject.DataPickerObject import JHDataPickerObject
from ViewObject.GLKViewObject import JHGLKViewObject
from ViewObject.ImageViewObject import JHImageViewObject
from ViewObject.LabelObject import JHLabelObject
from ViewObject.MapViewObject import JHMapViewObject
from ViewObject.MTKViewObject import JHMTKViewObject
from ViewObject.NavigationObject import JHNavigationObject
from ViewObject.PageControlObject import JHPageControlObject
from ViewObject.PickerViewObject import JHPickerViewObject
from ViewObject.ProgressObject import JHProgressObject
from ViewObject.SceneKitViewObject import JHSceneKitViewObject
from ViewObject.ScrollViewObject import JHScrollViewObject
from ViewObject.SearchBarObject import JHSearchBarObject
from ViewObject.SegmentedControlObject import JHSegmentedControlObject
from ViewObject.StackObject import JHStackObject
from ViewObject.StepperObject import JHStepperObject
from ViewObject.SwitchObject import JHSwitchObject
from ViewObject.TabBarObject import JHTabBarObject
from ViewObject.TableViewCellObject import JHTableViewCellObject
from ViewObject.TableViewObject import JHTableViewObject
from ViewObject.TableViewObject import JHTableViewObject
from ViewObject.TextFieldObject import JHTextFieldObject
from ViewObject.TextViewObject import JHTextViewObject
from ViewObject.ToolBarObject import JHToolBarObject
from ViewObject.VisualEffectViewObject import JHVisualEffectViewObject
from ViewObject.WebViewObject import JHWebViewObject

class JHBaseProcessor:
	'定义通用的接口'

	def __init__(self,nibParser):
		self.resouce_file_dir = nibParser.resourceFileDir()
		self.className = nibParser.className
		pass

	def __del__(self):
		pass

	def classFileDir(self):
		resource_file = self.resouce_file_dir+self.className+'.m'
		return resource_file
		pass

	def classTempFileDir(self):
		resource_Temp_file = self.resouce_file_dir+self.className+'Temp.m'
		return resource_Temp_file
		pass

	def readClassFile(self):
		read_Class_file = open(self.classFileDir(), "r")
		return read_Class_file
		pass

	def readTempClassFile(self):
		read_Temp_Class_file = open(self.classTempFileDir(), "w")
		return read_Temp_Class_file
		pass

	def viewObjectType(self, tag):
		viewObject = JHBasicObject()
		if tag == 'view':
			viewObject = JHViewObject()
			pass
		elif tag == 'label':
			viewObject = JHLabelObject()
			pass
		elif tag == 'segmentedControl':
			viewObject = JHSegmentedControlObject()
			pass
		elif tag == 'button':
			viewObject = JHButtonObject()
			pass
		elif tag == 'textField':
			viewObject = JHTextFieldObject()
			pass
		elif tag == 'slider':
			viewObject = JHSliderObject()
			pass
		elif tag == 'switch':
			viewObject = JHSwitchObject()
			pass
		elif tag == 'activityIndicatorView':
			viewObject = JHActivityIndicatorObject()
			pass
		elif tag == 'progressView':
			viewObject = JHProgressObject()
			pass
		elif tag == 'pageControl':
			viewObject = JHPageControlObject()
			pass
		elif tag == 'stepper':
			viewObject = JHStepperObject()
			pass
		elif tag == 'datePicker':
			viewObject = JHDataPickerObject()
			pass
		elif tag == 'pickerView':
			viewObject = JHPickerViewObject()
			pass
		elif tag == 'MTKView':
			viewObject = JHMTKViewObject()
			pass
		elif tag == 'searchBar':
			viewObject = JHSearchBarObject()
			pass
		elif tag == 'tabBar':
			viewObject = JHTabBarObject()
			pass
		elif tag == 'toolbar':
			viewObject = JHToolBarObject()
			pass
		elif tag == 'navigationBar':
			viewObject = JHNavigationObject()
			pass
		elif tag == 'stackView':
			viewObject = JHStackObject()
			pass
		elif tag == 'tableView':
			viewObject = JHTableViewObject()
			pass
		elif tag == 'tableViewCell':
			viewObject = JHTableViewCellObject()
			pass
		# elif tag == 'tableViewCellContentView':
		# 	className = ''
		# 	pass
		elif tag == 'imageView':
			viewObject = JHImageViewObject()
			pass
		elif tag == 'collectionView':
			viewObject = JHCollectionViewObject()
			pass
		elif tag == 'textView':
			viewObject = JHTextViewObject()
			pass
		elif tag == 'scrollView':
			viewObject = JHScrollViewObject()
			pass
		elif tag == 'visualEffectView':
			viewObject = JHVisualEffectViewObject()
			pass
		elif tag == 'webView':
			viewObject = JHWebViewObject()
			pass
		elif tag == 'glkView':
			viewObject = JHGLKViewObject()
			pass
		elif tag == 'mapView':
			viewObject = JHMapViewObject()
			pass
		elif tag == 'sceneKitView':
			viewObject = JHSceneKitViewObject()
			pass
		return viewObject

class JHObjcProcessor(JHBaseProcessor,JHCommomObject):
	'将parseResourceManager解析后的文件保存到实现文件中'
	def __init__(self, nibParser):
		JHBaseProcessor.__init__(self,nibParser)
		self.outletViews = nibParser.outletViews
		self.attribViews = nibParser.attribViews
		pass

	def __del__(self):
		pass

	def processing(self):
		analyseAttrib = self.analyseAttribView(self.attribViews)
		attribView = analyseAttrib[0]
		subView = analyseAttrib[1]
		# print 'attribView=', attribView, 'subView=',subView

		try:
			subMethodNames = []
			readFileHandle = self.readClassFile()
			writeFileHandle = self.readTempClassFile()
			line = readFileHandle.readline()
			while line !='':
				writeFileHandle.write(line)
				if line.find("@interface") != -1:
					self.loadIBOutletProperty(self.outletViews,writeFileHandle)
					pass
				elif line.find("@implementation") != -1:
					self.loadView(attribView, writeFileHandle)
					if len(subView) > 0:
						writeFileHandle.write("\n\
#pragma mark - loadAllSubViews\n")
						subMethodNames = self.loadAllSubView(subView, writeFileHandle)
						pass
					pass
				elif line.find("[super viewDidLoad]") != -1:
					if len(subMethodNames) > 0:
						self.loadAllSubViewOfView('self.view',subMethodNames,writeFileHandle)
						view = self.attribViewTagProperty(attribView)
						self.loadViewConstranit('self.view',view.get('id', ''),attribView.get('constraints', []),writeFileHandle)
						pass
					pass
				else:
					pass

				line = readFileHandle.readline()
				pass
		except Exception as e:
			print 'you has a Exception when read ', self.classFileDir(), 'file'
			os.remove(self.classTempFileDir())
			raise
		else:
			os.remove(self.classFileDir())
			os.rename(self.classTempFileDir(),self.classFileDir())
		finally:
			print 'finish parsor ',self.classFileDir(), 'file'
			readFileHandle.close()
			writeFileHandle.close()
			pass

	def loadIBOutletProperty(self, attribView, writeFileHandle):
		for attrib in attribView:
			tag = attrib.get('property','')
			if tag == 'view':
				pass
			else:
				className = self.objcClassNameType(tag)
				if len(className) > 0:
					writeFileHandle.write("@property (nonatomic, strong) "+className+" *"+tag+";\n")
					pass
				pass
		pass

	def loadView(self, attribView, writeFileHandle):
		viewName = self.attribViewTag(attribView)
		className = self.objcClassNameType(viewName)
		if len(className) > 0:
			viewObject = self.viewObjectType(viewName)
			writeFileHandle.write("\n#pragma mark - lifeCycle\n")
			writeFileHandle.write(viewObject.addSubview(attribView,True))
			pass
		pass

	def loadAllSubView(self, attribViews, writeFileHandle):
		methodNames = []
		subMethodNames = []
		for subAttribView in attribViews:
			attribView = {}
			subViews = []
			for (tag,attrib) in subAttribView.items():
				if tag == 'subviews':
					subViews = attrib
					pass
				else:
					attribView[tag] = attrib
					pass

			if len(subViews):
				subMethodNames = self.loadAllSubView(subViews, writeFileHandle)
				pass
			# print 'attribView=', attribView
			methodName = self.loadSubView(attribView, subMethodNames, writeFileHandle)
			methodNames.append(methodName);
			pass
		return methodNames

	def loadSubView(self, attribView, subMethodNames, writeFileHandle):
		classViewName = self.attribViewTag(attribView)
		viewObject = self.viewObjectType(classViewName)

		writeFileHandle.write(viewObject.addSubview(attribView,False))
		for subMethod in subMethodNames:
			writeFileHandle.write("\
	["+classViewName+" addSubview:[self "+subMethod+"]];\n")
			pass

		parentView = self.attribViewTag(attribView)
		viewId = self.attribViewNameID(attribView)
		self.loadViewConstranit(parentView,viewId,attribView.get('constraints', []),writeFileHandle)
		writeFileHandle.write("\
	return "+classViewName+";\n")
		writeFileHandle.write("}\n")

		return self.attribViewViewMethod(attribView)
		pass

	def loadAllSubViewOfView(self,parentView,subMethodNames,writeFileHandle):
		writeFileHandle.write("\n\
	// add subviews\n")
		for subMethod in subMethodNames:
			writeFileHandle.write("\
	["+parentView+" addSubview:[self "+subMethod+"]];\n")
			pass
		pass

	def loadViewConstranit(self, parentView, viewId, attribViews, writeFileHandle):
	 	for attribViewConstraint in list(attribViews):
	 		# print 'attribViewConstraint=',attribViewConstraint
	 		attribView = attribViewConstraint.get('constraint', {})
	 		firstItem = attribView.get('firstItem', '')
	 		firstAttribute = attribView.get('firstAttribute', '')
	 		secondItem = attribView.get('secondItem', '')
	 		secondAttribute = attribView.get('secondAttribute', '')
	 		multiplier = attribView.get('multiplier', '1.0')
	 		priority = attribView.get('priority', '1000')
	 		constant = attribView.get('constant', '0')
	 		relation = attribView.get('relation', 'equal')
	 		subView = "["+parentView+" viewWithTag:[@"+"\""+firstItem+"\""+" hash]]"
	 		if viewId == secondItem:
	 			writeFileHandle.write("\
	["+parentView+" addConstraint:[NSLayoutConstraint constraintWithItem:"+subView+"\n\
															  attribute:"+self.layoutAttribute(firstAttribute)+"\n\
															  relatedBy:"+self.layoutRelation(relation)+"\n\
																 toItem:"+parentView+"\n\
															  attribute:"+self.layoutAttribute(secondAttribute)+"\n\
															 multiplier:"+multiplier+"\n\
															   constant:"+constant+"]];\n");
	 			pass
	 		elif len(firstItem) == 0 and len(secondItem) > 0:
	 			secodeItemView =  "["+parentView+" viewWithTag:[@"+"\""+secondItem+"\""+" hash]]"
	 			writeFileHandle.write("\
	["+parentView+" addConstraint:[NSLayoutConstraint constraintWithItem:"+parentView+"\n\
															  attribute:"+self.layoutAttribute(firstAttribute)+"\n\
															  relatedBy:"+self.layoutRelation(relation)+"\n\
																 toItem:"+secodeItemView+"\n\
															  attribute:"+self.layoutAttribute(secondAttribute)+"\n\
															 multiplier:"+multiplier+"\n\
															   constant:"+constant+"]];\n");
	 			pass
	 		elif len(secondItem) == 0:
	 			writeFileHandle.write("\
	["+parentView+" addConstraint:[NSLayoutConstraint constraintWithItem:"+parentView+"\n\
															  attribute:"+self.layoutAttribute(firstAttribute)+"\n\
															  relatedBy:"+self.layoutRelation(relation)+"\n\
																 toItem:nil\n\
															  attribute:NSLayoutAttributeNotAnAttribute\n\
															 multiplier:"+multiplier+"\n\
															   constant:"+constant+"]];\n");
	 		else :
	 			secodeItemView =  "["+parentView+" viewWithTag:[@"+"\""+secondItem+"\""+" hash]]"
	 			writeFileHandle.write("\
	["+parentView+" addConstraint:[NSLayoutConstraint constraintWithItem:"+subView+"\n\
															  attribute:"+self.layoutAttribute(firstAttribute)+"\n\
															  relatedBy:"+self.layoutRelation(relation)+"\n\
																 toItem:"+secodeItemView+"\n\
															  attribute:"+self.layoutAttribute(secondAttribute)+"\n\
															 multiplier:"+multiplier+"\n\
															   constant:"+constant+"]];\n");
	 		pass
	 	pass

	def analyseAttribView(self, attribViews):
		attribView = {}
		subView = []
		for subAttribView in attribViews:
			for (tag,attrib) in subAttribView.items():
				if tag == 'subviews':
					subView = attrib
					pass
				else:
					attribView[tag] = attrib
					pass
			pass
		return (attribView, subView)
<commit_msg>modify processor.py explation<commit_after>#!/usr/bin/python
# _*_ coding: UTF-8 _*_

# create: 2016/10/18
# version: 0.0.1
# author: Junhg
# contribute:
#
__author__ = 'Junhg'

import os
from ViewObject.CommonObject import JHCommomObject
from ViewObject.ViewObject import JHViewObject
from ViewObject.BasicObject import JHBasicObject
from ViewObject.ActivityIndicatorObject import JHActivityIndicatorObject
from ViewObject.ButtonObject import JHButtonObject
from ViewObject.CollectionViewObject import JHCollectionViewObject
from ViewObject.DataPickerObject import JHDataPickerObject
from ViewObject.GLKViewObject import JHGLKViewObject
from ViewObject.ImageViewObject import JHImageViewObject
from ViewObject.LabelObject import JHLabelObject
from ViewObject.MapViewObject import JHMapViewObject
from ViewObject.MTKViewObject import JHMTKViewObject
from ViewObject.NavigationObject import JHNavigationObject
from ViewObject.PageControlObject import JHPageControlObject
from ViewObject.PickerViewObject import JHPickerViewObject
from ViewObject.ProgressObject import JHProgressObject
from ViewObject.SceneKitViewObject import JHSceneKitViewObject
from ViewObject.ScrollViewObject import JHScrollViewObject
from ViewObject.SearchBarObject import JHSearchBarObject
from ViewObject.SegmentedControlObject import JHSegmentedControlObject
from ViewObject.StackObject import JHStackObject
from ViewObject.StepperObject import JHStepperObject
from ViewObject.SwitchObject import JHSwitchObject
from ViewObject.TabBarObject import JHTabBarObject
from ViewObject.TableViewCellObject import JHTableViewCellObject
from ViewObject.TableViewObject import JHTableViewObject
from ViewObject.TableViewObject import JHTableViewObject
from ViewObject.TextFieldObject import JHTextFieldObject
from ViewObject.TextViewObject import JHTextViewObject
from ViewObject.ToolBarObject import JHToolBarObject
from ViewObject.VisualEffectViewObject import JHVisualEffectViewObject
from ViewObject.WebViewObject import JHWebViewObject

class JHBaseProcessor:
	'定义通用的接口'

	def __init__(self,nibParser):
		self.resouce_file_dir = nibParser.resourceFileDir()
		self.className = nibParser.className
		pass

	def __del__(self):
		pass

	def classFileDir(self):
		resource_file = self.resouce_file_dir+self.className+'.m'
		return resource_file
		pass

	def classTempFileDir(self):
		resource_Temp_file = self.resouce_file_dir+self.className+'Temp.m'
		return resource_Temp_file
		pass

	def readClassFile(self):
		read_Class_file = open(self.classFileDir(), "r")
		return read_Class_file
		pass

	def readTempClassFile(self):
		read_Temp_Class_file = open(self.classTempFileDir(), "w")
		return read_Temp_Class_file
		pass

	def viewObjectType(self, tag):
		viewObject = JHBasicObject()
		if tag == 'view':
			viewObject = JHViewObject()
			pass
		elif tag == 'label':
			viewObject = JHLabelObject()
			pass
		elif tag == 'segmentedControl':
			viewObject = JHSegmentedControlObject()
			pass
		elif tag == 'button':
			viewObject = JHButtonObject()
			pass
		elif tag == 'textField':
			viewObject = JHTextFieldObject()
			pass
		elif tag == 'slider':
			viewObject = JHSliderObject()
			pass
		elif tag == 'switch':
			viewObject = JHSwitchObject()
			pass
		elif tag == 'activityIndicatorView':
			viewObject = JHActivityIndicatorObject()
			pass
		elif tag == 'progressView':
			viewObject = JHProgressObject()
			pass
		elif tag == 'pageControl':
			viewObject = JHPageControlObject()
			pass
		elif tag == 'stepper':
			viewObject = JHStepperObject()
			pass
		elif tag == 'datePicker':
			viewObject = JHDataPickerObject()
			pass
		elif tag == 'pickerView':
			viewObject = JHPickerViewObject()
			pass
		elif tag == 'MTKView':
			viewObject = JHMTKViewObject()
			pass
		elif tag == 'searchBar':
			viewObject = JHSearchBarObject()
			pass
		elif tag == 'tabBar':
			viewObject = JHTabBarObject()
			pass
		elif tag == 'toolbar':
			viewObject = JHToolBarObject()
			pass
		elif tag == 'navigationBar':
			viewObject = JHNavigationObject()
			pass
		elif tag == 'stackView':
			viewObject = JHStackObject()
			pass
		elif tag == 'tableView':
			viewObject = JHTableViewObject()
			pass
		elif tag == 'tableViewCell':
			viewObject = JHTableViewCellObject()
			pass
		# elif tag == 'tableViewCellContentView':
		# 	className = ''
		# 	pass
		elif tag == 'imageView':
			viewObject = JHImageViewObject()
			pass
		elif tag == 'collectionView':
			viewObject = JHCollectionViewObject()
			pass
		elif tag == 'textView':
			viewObject = JHTextViewObject()
			pass
		elif tag == 'scrollView':
			viewObject = JHScrollViewObject()
			pass
		elif tag == 'visualEffectView':
			viewObject = JHVisualEffectViewObject()
			pass
		elif tag == 'webView':
			viewObject = JHWebViewObject()
			pass
		elif tag == 'glkView':
			viewObject = JHGLKViewObject()
			pass
		elif tag == 'mapView':
			viewObject = JHMapViewObject()
			pass
		elif tag == 'sceneKitView':
			viewObject = JHSceneKitViewObject()
			pass
		return viewObject

class JHObjcProcessor(JHBaseProcessor,JHCommomObject):
	'将parseResourceManager解析后的文件保存到实现文件中'
	def __init__(self, nibParser):
		JHBaseProcessor.__init__(self,nibParser)
		self.outletViews = nibParser.outletViews
		self.attribViews = nibParser.attribViews
		pass

	def __del__(self):
		pass

	def processing(self):
		analyseAttrib = self.analyseAttribView(self.attribViews)
		attribView = analyseAttrib[0]
		subView = analyseAttrib[1]
		# print 'attribView=', attribView, 'subView=',subView

		try:
			subMethodNames = []
			readFileHandle = self.readClassFile()
			writeFileHandle = self.readTempClassFile()
			line = readFileHandle.readline()
			while line !='':
				writeFileHandle.write(line)
				if line.find("@interface") != -1:
					self.loadIBOutletProperty(self.outletViews,writeFileHandle)
					pass
				elif line.find("@implementation") != -1:
					self.loadView(attribView, writeFileHandle)
					if len(subView) > 0:
						writeFileHandle.write("\n\
#pragma mark - loadAllSubViews\n")
						subMethodNames = self.loadAllSubView(subView, writeFileHandle)
						pass
					pass
				elif line.find("[super viewDidLoad]") != -1:
					if len(subMethodNames) > 0:
						self.loadAllSubViewOfView('self.view',subMethodNames,writeFileHandle)
						view = self.attribViewTagProperty(attribView)
						self.loadViewConstranit('self.view',view.get('id', ''),attribView.get('constraints', []),writeFileHandle)
						pass
					pass
				else:
					pass

				line = readFileHandle.readline()
				pass
		except Exception as e:
			print 'crashed when parser ', self.className, '.xib file'
			os.remove(self.classTempFileDir())
			raise
		else:
			os.remove(self.classFileDir())
			os.rename(self.classTempFileDir(),self.classFileDir())
		finally:
			print 'finish parsor ',self.className, '.xib file'
			readFileHandle.close()
			writeFileHandle.close()
			pass

	def loadIBOutletProperty(self, attribView, writeFileHandle):
		for attrib in attribView:
			tag = attrib.get('property','')
			if tag == 'view':
				pass
			else:
				className = self.objcClassNameType(tag)
				if len(className) > 0:
					writeFileHandle.write("@property (nonatomic, strong) "+className+" *"+tag+";\n")
					pass
				pass
			pass
		pass

	def loadView(self, attribView, writeFileHandle):
		viewName = self.attribViewTag(attribView)
		className = self.objcClassNameType(viewName)
		if len(className) > 0:
			viewObject = self.viewObjectType(viewName)
			writeFileHandle.write("\n#pragma mark - lifeCycle\n")
			writeFileHandle.write(viewObject.addSubview(attribView,True))
			pass
		pass

	def loadAllSubView(self, attribViews, writeFileHandle):
		methodNames = []
		subMethodNames = []
		for subAttribView in attribViews:
			attribView = {}
			subViews = []
			for (tag,attrib) in subAttribView.items():
				if tag == 'subviews':
					subViews = attrib
					pass
				else:
					attribView[tag] = attrib
					pass

			if len(subViews):
				subMethodNames = self.loadAllSubView(subViews, writeFileHandle)
				pass
			# print 'attribView=', attribView
			methodName = self.loadSubView(attribView, subMethodNames, writeFileHandle)
			methodNames.append(methodName);
			pass
		return methodNames

	def loadSubView(self, attribView, subMethodNames, writeFileHandle):
		classViewName = self.attribViewTag(attribView)
		viewObject = self.viewObjectType(classViewName)

		writeFileHandle.write(viewObject.addSubview(attribView,False))
		for subMethod in subMethodNames:
			writeFileHandle.write("\
	["+classViewName+" addSubview:[self "+subMethod+"]];\n")
			pass

		parentView = self.attribViewTag(attribView)
		viewId = self.attribViewNameID(attribView)
		self.loadViewConstranit(parentView,viewId,attribView.get('constraints', []),writeFileHandle)
		writeFileHandle.write("\
	return "+classViewName+";\n")
		writeFileHandle.write("}\n")

		return self.attribViewViewMethod(attribView)
		pass

	def loadAllSubViewOfView(self,parentView,subMethodNames,writeFileHandle):
		writeFileHandle.write("\n\
	// add subviews\n")
		for subMethod in subMethodNames:
			writeFileHandle.write("\
	["+parentView+" addSubview:[self "+subMethod+"]];\n")
			pass
		pass

	def loadViewConstranit(self, parentView, viewId, attribViews, writeFileHandle):
	 	for attribViewConstraint in list(attribViews):
	 		# print 'attribViewConstraint=',attribViewConstraint
	 		attribView = attribViewConstraint.get('constraint', {})
	 		firstItem = attribView.get('firstItem', '')
	 		firstAttribute = attribView.get('firstAttribute', '')
	 		secondItem = attribView.get('secondItem', '')
	 		secondAttribute = attribView.get('secondAttribute', '')
	 		multiplier = attribView.get('multiplier', '1.0')
	 		priority = attribView.get('priority', '1000')
	 		constant = attribView.get('constant', '0')
	 		relation = attribView.get('relation', 'equal')
	 		subView = "["+parentView+" viewWithTag:[@"+"\""+firstItem+"\""+" hash]]"
	 		if viewId == secondItem:
	 			writeFileHandle.write("\
	["+parentView+" addConstraint:[NSLayoutConstraint constraintWithItem:"+subView+"\n\
															  attribute:"+self.layoutAttribute(firstAttribute)+"\n\
															  relatedBy:"+self.layoutRelation(relation)+"\n\
																 toItem:"+parentView+"\n\
															  attribute:"+self.layoutAttribute(secondAttribute)+"\n\
															 multiplier:"+multiplier+"\n\
															   constant:"+constant+"]];\n");
	 			pass
	 		elif len(firstItem) == 0 and len(secondItem) > 0:
	 			secodeItemView =  "["+parentView+" viewWithTag:[@"+"\""+secondItem+"\""+" hash]]"
	 			writeFileHandle.write("\
	["+parentView+" addConstraint:[NSLayoutConstraint constraintWithItem:"+parentView+"\n\
															  attribute:"+self.layoutAttribute(firstAttribute)+"\n\
															  relatedBy:"+self.layoutRelation(relation)+"\n\
																 toItem:"+secodeItemView+"\n\
															  attribute:"+self.layoutAttribute(secondAttribute)+"\n\
															 multiplier:"+multiplier+"\n\
															   constant:"+constant+"]];\n");
	 			pass
	 		elif len(secondItem) == 0:
	 			writeFileHandle.write("\
	["+parentView+" addConstraint:[NSLayoutConstraint constraintWithItem:"+parentView+"\n\
															  attribute:"+self.layoutAttribute(firstAttribute)+"\n\
															  relatedBy:"+self.layoutRelation(relation)+"\n\
																 toItem:nil\n\
															  attribute:NSLayoutAttributeNotAnAttribute\n\
															 multiplier:"+multiplier+"\n\
															   constant:"+constant+"]];\n");
	 		else :
	 			secodeItemView =  "["+parentView+" viewWithTag:[@"+"\""+secondItem+"\""+" hash]]"
	 			writeFileHandle.write("\
	["+parentView+" addConstraint:[NSLayoutConstraint constraintWithItem:"+subView+"\n\
															  attribute:"+self.layoutAttribute(firstAttribute)+"\n\
															  relatedBy:"+self.layoutRelation(relation)+"\n\
																 toItem:"+secodeItemView+"\n\
															  attribute:"+self.layoutAttribute(secondAttribute)+"\n\
															 multiplier:"+multiplier+"\n\
															   constant:"+constant+"]];\n");
	 		pass
	 	pass

	def analyseAttribView(self, attribViews):
		attribView = {}
		subView = []
		for subAttribView in attribViews:
			for (tag,attrib) in subAttribView.items():
				if tag == 'subviews':
					subView = attrib
					pass
				else:
					attribView[tag] = attrib
					pass
			pass
		return (attribView, subView)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# coding: utf-8

import sys, os
assert sys.version >= '3.3', 'Please use Python 3.4 or higher.'

import settings
sys.path.append(settings.root)
sys.path.append( os.path.dirname( __file__ ) )

from tao1.core.union import init_gunicorn
app = init_gunicorn()

# gunicorn app:app -k aiohttp.worker.GunicornWebWorker -b localhost:6677
<commit_msg>fix gunicorn  run file<commit_after>#!/usr/bin/env python
# coding: utf-8

import sys, os
assert sys.version >= '3.3', 'Please use Python 3.4 or higher.'

sys.path.append(os.path.dirname(__file__))

import settings

sys.path.append(settings.tao_path)

from core.union import init_gunicorn
app = init_gunicorn()

# gunicorn app:app -k aiohttp.worker.GunicornWebWorker -b localhost:6677
<|endoftext|>


<commit_before>from Tkinter import *
from PIL import Image, ImageTk
import threading
from time import sleep
import os
import inspect

class display():
    def __init__(self, run, kill, scale, dims):
        """
        run: function to run once setup is complete
        kill: deconstructor once simulation is closed
        scale: integer to scale dims by
        dims: tuple of matrix dimensions in pixels (x, y)
        """
        self.root = Tk()
        self.scale = scale
        self.dims = dims
        self.image = Image.new('RGB', self.dims)
        photo = ImageTk.PhotoImage(image)
        self.label = Label(image=photo)
        self.label.image = photo
        # keep a reference!
        self.label.pack()
        self.t = threading.Thread(target=run)
        self.t.start()
        self.root.mainloop()
        kill()

    def SetImage(self, img, x=0, y=0):
        """
        Takes an image, copies it then scales it and displays
        """
        img = ImageTk.PhotoImage(img.copy().resize(
            [a * self.scale for a in self.dims], Image.ANTIALIAS))
        self.label.configure(image=img)
        self.label.image = img
        self.root.update()

    def Clear(self):
        """
        clears display to black
        """
        self.SetImage(Image.new('RGB', self.dims))

    def SetPWMBits(self, n):
        """
        Not applicable to simulation
        """
        pass

    def SetPixel(self, x, y, r, g=None, b=None):
        """
        draws a pixel on the matrix at x,y
        """
        try:
            r = int(r)
        except TypeError:
            r, g, b = *r

    def SetBuffer(self):
        """
        """
        pass

    def Fill(self, color):
        """
        """
        pass
<commit_msg>Make Interface Closer to Drivers<commit_after>from Tkinter import *
from PIL import Image, ImageTk
import threading
from time import sleep
import os
import inspect

class display():
    def __init__(self, matrix_height, chain_length):
        """
        run: function to run once setup is complete
        kill: deconstructor once simulation is closed
        scale: integer to scale dims by
        dims: tuple of matrix dimensions in pixels (x, y)
        """
        self.root = Tk()
        self.scale = 6
        self.dims = (32*chain_length, matrix_height)
        self.image = Image.new('RGB', self.dims)
        photo = ImageTk.PhotoImage(self.image)
        self.label = Label(image=photo)
        self.label.image = photo
        # keep a reference!
        self.label.pack()

    def start(self, run, kill):
        self.t = threading.Thread(target=run)
        self.t.start()
        self.root.mainloop()
        kill()

    def SetImage(self, img, x=0, y=0):
        """
        Takes an image, copies it then scales it and displays
        """
        img = ImageTk.PhotoImage(img.copy().resize(
            [a * self.scale for a in self.dims], Image.ANTIALIAS))
        self.label.configure(image=img)
        self.label.image = img
        self.root.update()

    def Clear(self):
        """
        clears display to black
        """
        self.SetImage(Image.new('RGB', self.dims))

    def SetPWMBits(self, n):
        """
        Not applicable to simulation
        """
        pass

    def SetPixel(self, x, y, r, g=None, b=None):
        """
        draws a pixel on the matrix at x,y
        """
        try:
            r = int(r)
        except TypeError:
            pass
            # r, g, b = *r

    def SetBuffer(self):
        """
        """
        pass

    def Fill(self, color):
        """
        """
        pass
<|endoftext|>