Example #1
0
def crawl(website, shard, conn):
    name = 'foo-bar'
    task = 'crawl'
    count_for_checkpoint_pid = 20

    if get_finished(conn, task, shard):
        print 'Task %s at Shard %d finished.' % (task, shard)
        return

    for loop_count, pid in enumerate(enum(conn, task, shard)):
        # remember where we are, so we can resume
        # this pid will be retried when resume
        if (loop_count+1) % count_for_checkpoint_pid == 0:
            set_last_pid(conn, task, shard, pid)

        url = 'http://www.%s.com/pub/%s/%s' % (website, name, pid)
        print url
        profile = r.table('profile').get(pid).run(conn)
        if profile:
            print '%s existed.' % (url,)
            continue
        try:
            cp = CandidatePage.from_url(url)
        except HTMLParser.HTMLParseError, e:
            cp = None
            pass
        if not cp:
            continue
        try:
            cp_dict = cp.to_dict()
            cp_dict['pid'] = pid
            r.table('profile').insert( cp.to_dict() ).run(conn)
        except RqlRuntimeError, e:
            print e
class ImageAnnotation(Observable):
    """ Annotation localized on an image. Position is in mm, expressed as 
        (z,y,x). Can fire the following events : 
            
            * position : old_value
            * label : old_value
            * shape : old_value
            * size : old_value
            * color : old_value
            * filled : old_value
            * comment : old_value
    """

    Shape = enum("Shape", "sphere", "cube", "cross", "point")

    def __init__(self,
                 position=None,
                 label=None,
                 shape=None,
                 size=None,
                 color=None,
                 filled=None,
                 comment=None):

        Observable.__init__(self, [
            "position", "label", "shape", "size", "color", "filled", "comment"
        ])

        # Position in image space
        self.position = position if position is not None else [0., 0., 0.]
        self.label = label or ""
        # Integer, value in ImageAnnotation.Shape
        self.shape = shape or ImageAnnotation.Shape.sphere
        self.size = size or 0.
        # RGB color, each component in 0,1 range
        self.color = color or [0., 0., 0.]
        self.filled = filled or False
        self.comment = comment or ""

    def __setattr__(self, attr, value):
        if attr in [
                "position", "label", "shape", "size", "color", "filled",
                "comment"
        ]:
            old_value = getattr(self, attr, None)
            object.__setattr__(self, attr, value)
            self.notify_observers(attr, old_value=old_value)
        else:
            Observable.__setattr__(self, attr, value)
Example #3
0
File: utils.py Project: marckn/qevo
def printData(fname,data, lcoords, format="dat"):
   """
   Given a data file with coordinates list print a gnuplot .dat file
   IN:    fname   =   the output file name
          data    =   numpy ndarray containing data in the format value=V[i,j,...]
	  lcoords =   tuple of lists containing the coordinates (x1,x2,x3):
	              this are the values assigned by the enum function
		      
          format  =   the output format, supports: .dat (gnuplot-like), csv (comma separated values)
   """
   
   f = open(fname+"."+format,"w+")
   if len(data.shape) != len(lcoords):
      print "ERROR: data and coordinates are inconsistent"
      raise ValueError
      
   caps=[]
   for l in lcoords:
      caps.append(len(l))
      
   enu = enum(caps)
   
   for i in range(enu.maxidx):
      levels = enu.tolevels(i)
      
      lout=""
      for ci, cc in zip(levels,lcoords):
         if format == "dat":
	    lout= lout + "{0:4f}    ".format(float(cc[ci]))
	 elif format == "csv":
	    lout= lout + "{0:.4f},".format(float(cc[ci]))
	 
	 
      value = data[levels]
      if format == "dat":
         lout = lout + "{0:8f}\n".format(float(value))
         if levels[-1] == caps[-1]-1:
            lout = lout + "\n"
	
      elif format == "csv":
         lout = lout + "{0:.8f}\n".format(float(value))
      
       
      f.write(lout)
Example #4
0
    def __init__(self, resolution=(1280, 800)):
        """
            Images for reference on the board
        """
        self.images = {
            'settings': scvImage('./images/board/settings.png'),
            'friends':  scvImage('./images/board/friends.png'),
            'windowed': scvImage('./images/board/windowed.png'),
            'confirm_button': scvImage('./images/board/confirm_button.png'),
            'ogrimmar': scvImage('./images/board/ogrimmar.png'),
            'pandaria': scvImage('./images/board/pandaria.png'),
            'stormwind': scvImage('./images/board/stormwind.png'),
            'stranglethornVale': scvImage('./images/board/stranglethornVale.png')
        }

        """
            Bounding boxes of the targets
        """
        self.UpLeft    = None
        self.UpRight   = None
        self.DownLeft  = None
        self.DownRight = None

        self.__enemy_card_position  = (None, None)
        self.__turn_button_position = (None, None)

        """
            Game Boards
        """
        self.GameBoards = enum('Ogrimmar', 'Pandaria', 'Stormwind', 'StranglethornVale')
        self.__game_board = None

        self.heigth = 0
        self.width = 0

        self.board_img = None

        """
            Resolution of the board (game)
        """
        self.resolution = resolution
Example #5
0
def duration(conn, shard):
    task = 'duration'
    for loop_count, pid in enumerate(enum(conn, task, shard)):
        profile = r.table('profile').get(pid).run(conn)
        if not profile:
            print '%s not existed.' % (pid,)
            continue
        #print profile

        positions = profile.get('positions')
        if not positions:
            continue
        durations = map(lambda x:x.get('duration'), positions)
        if not any(durations):
            continue

        for days in durations:
            if days is None:
                continue
            months = int(days)/30
            print 'month %d incremented.' % (months,)
            r.table('duration').get(months).update({'n': r.row['n'] + 1}).run(conn)
Example #6
0
class Player(ServerEntity):
    __slots__ = "state", "__somsgbuf"
    State = enum("LOGGING_IN", "ACTIVE")

    def __init__(self, opensock):
        ServerEntity.__init__(self)
        self.__somsgbuf = SocketMessageBuffer(opensock)
        self.state = self.State.LOGGING_IN

    def disconnect(self):
        self.__somsgbuf.get_socket().close()

    def socket_fileno(self):
        return self.__somsgbuf.fileno()

    def needs_writing(self):
        return self.__somsgbuf.pending_out()

    def read_incoming(self):
        return self.__somsgbuf.receive_more()

    def write_outgoing(self):
        return self.__somsgbuf.send_pending()

    def get_message(self):
        return self.__somsgbuf.get_message()

    def post_message(self, title, *pargs, **kwargs):
        return self.__somsgbuf.post_message(title, *pargs, **kwargs)

    def setattr(self, key, value):
        print key, value
        assert False

    def get_remote_address(self):
        return self.__somsgbuf.get_socket().getpeername()

class Intersection(qn.Server):
  """Intersection where cars move between roads."""
  pass


class ExitPoint(Intersection):
  """Intersection where cars can exit the simulation."""
  pass


# Enumerate the server types.
ServerTypes = enum.enum(
    PARKING_LOT=ParkingLot,
    INTERSECTION=Intersection,
    EXIT_POINT=ExitPoint,
)

def get_server_types():
  """Accessor method for server types."""
  server_types = [getattr(ServerTypes, name) for name in dir(ServerTypes)
                  if not name.startswith('_')]
  return server_types


# Roads.

def TimeToDrive(road):
  """Computes time taken to reach back of the line at other end of the road.
Example #8
0
class PluginConnection(object):

    currently_supported_clients = [
        'SUBLIME_TEXT_2', 'SUBLIME_TEXT_3', 'BRACKETS'
    ]
    PluginClients = enum(SUBLIME_TEXT_2='SUBLIME_TEXT_2',
                         SUBLIME_TEXT_3='SUBLIME_TEXT_3',
                         ATOM='ATOM',
                         BRACKET='BRACKETS',
                         NOTEPAD_PLUS_PLUS='NOTEPAD_PLUS_PLUS',
                         TEXTMATE='TEXTMATE')

    def __init__(self, params={}, **kwargs):
        params = dict(params.items() + kwargs.items())  #join params and kwargs
        self.params = params
        self.operation = params.get('operation', None)
        self.args = params.get('args', None)
        self.plugin_client = params.get(
            'client',
            'SUBLIME_TEXT_3')  #=> "Sublime Text", "Notepad++", "TextMate"
        if self.plugin_client not in self.currently_supported_clients:
            self.plugin_client = 'SUBLIME_TEXT_3'
        self.project_name = params.get('project_name', None)
        self.project_location = params.get('project_location', None)
        self.plugin_client_settings = self.get_plugin_client_settings()
        if self.project_location == None:
            self.workspace = params.get('workspace', self.get_workspace())
        else:
            self.workspace = os.path.dirname(self.project_location)
        if self.project_name != None and self.project_location == None:
            self.project_location = os.path.join(self.workspace,
                                                 self.project_name)
        self.project_id = params.get('project_id', None)
        self.project = None
        self.sfdc_api_version = self.get_sfdc_api_version()
        self.ui = params.get(
            'ui', False
        )  #=> whether this connection was created for the purposes of generating a UI
        self.verbose = params.get('verbose', False)
        if 'wsdl_path' in params:
            util.WSDL_PATH = params.get('wsdl_path')

        self.setup_logging()
        if self.get_plugin_client_setting('mm_timeout', None) != None:
            socket.setdefaulttimeout(
                self.get_plugin_client_setting('mm_timeout'))

        debug('')
        debug('--------------------------------------------')
        debug('---------- NEW OPERATION REQUESTED ---------')
        debug('--------------------------------------------')
        debug('')
        debug(self.operation)
        debug(self.args)
        debug(params)
        debug('')
        debug('--------------------------------------------')

        if self.sfdc_api_version != None:
            util.SFDC_API_VERSION = self.sfdc_api_version  #setting api version based on plugin settings
            util.set_endpoints()

        if self.operation != 'new_project' and self.operation != 'upgrade_project' and self.operation != 'new_project_from_existing_directory' and self.project_location != None:
            if not os.path.exists(os.path.join(self.project_location)):
                raise MMException('Could not find project in workspace: ' +
                                  self.workspace)
            if not os.path.exists(
                    os.path.join(self.project_location, "config",
                                 ".settings")):
                raise MMException(
                    'This does not seem to be a valid MavensMate project, missing config/.settings'
                )
            #if not os.path.exists(os.path.join(self.project_location,"src","package.xml")):
            #    raise MMException('This does not seem to be a valid MavensMate project, missing package.xml')
        if self.project_name != None and self.project_name != '' and not os.path.exists(
                self.project_location
        ) and self.operation != 'new_project_from_existing_directory' and self.operation != 'new_project':
            raise MMException('The project could not be found')
        elif self.project_name != None and self.project_name != '' and os.path.exists(
                os.path.join(
                    self.workspace,
                    self.project_name)) and self.operation == 'new_project':
            raise MMException(
                'A project with this name already exists in your workspace. To create a MavensMate project from an existing non-MavensMate Force.com project, open the project directory in Sublime Text, right click the project name in the sidebar and select "Create MavensMate Project"'
            )
        elif self.project_name != None and self.project_name != '' and os.path.exists(
                os.path.join(self.workspace, self.project_name)
        ) and self.operation != 'new_project_from_existing_directory':
            params['location'] = self.project_location
            params['ui'] = self.ui

    def setup_logging(self):
        if self.get_log_level() != None:
            if self.get_log_location() != None:
                try:
                    config.logger.handlers = []
                    config.suds_logger.handlers = []
                    handler = RotatingFileHandler(os.path.join(
                        self.get_log_location(), "mm.log"),
                                                  maxBytes=10 * 1024 * 1024,
                                                  backupCount=5)
                    config.logger.addHandler(handler)
                    config.suds_logger.addHandler(handler)
                    config.requests_log.addHandler(handler)
                except:
                    pass
            log_level = self.get_log_level()
            if log_level == 'CRITICAL':
                config.logger.setLevel(logging.CRITICAL)
                config.suds_logger.setLevel(logging.CRITICAL)
                config.requests_log.setLevel(logging.CRITICAL)
            elif log_level == 'ERROR':
                config.logger.setLevel(logging.ERROR)
                config.suds_logger.setLevel(logging.ERROR)
                config.requests_log.setLevel(logging.ERROR)
            elif log_level == 'WARNING':
                config.logger.setLevel(logging.WARNING)
                config.suds_logger.setLevel(logging.WARNING)
                config.requests_log.setLevel(logging.WARNING)
            elif log_level == 'DEBUG':
                config.logger.setLevel(logging.DEBUG)
                config.suds_logger.setLevel(logging.DEBUG)
                config.requests_log.setLevel(logging.DEBUG)
            elif log_level == 'INFO':
                config.logger.setLevel(logging.INFO)
                config.suds_logger.setLevel(logging.INFO)
                config.requests_log.setLevel(logging.INFO)

    #returns the workspace for the current connection (/Users/username/Workspaces/MavensMate)
    def get_workspace(self):
        mm_workspace_path = None
        mm_workspace_setting = self.get_plugin_client_setting('mm_workspace')
        if type(mm_workspace_setting) is list and len(
                mm_workspace_setting) > 0:
            mm_workspace_path = mm_workspace_setting[0]  #grab the first path
        else:
            mm_workspace_path = mm_workspace_setting  #otherwise, it's a string, set it

        if mm_workspace_path == None or mm_workspace_path == '':
            raise MMException(
                "Please set mm_workspace to the location where you'd like your mavensmate projects to reside"
            )
        elif not os.path.exists(mm_workspace_path):
            try:
                os.makedirs(mm_workspace_path)
            except:
                raise MMException("Unable to create mm_workspace location")
        return mm_workspace_path

    #returns the list of workspaces
    def get_workspaces(self):
        workspaces = []
        mm_workspace_setting = self.get_plugin_client_setting('mm_workspace')
        if type(mm_workspace_setting) is list and len(
                mm_workspace_setting) == 0:
            raise MMException("mm_workspace not properly set")

        if type(mm_workspace_setting) is list and len(
                mm_workspace_setting) > 0:
            workspaces = mm_workspace_setting
        else:
            workspaces = [mm_workspace_setting]
        return workspaces

    #returns the MavensMate settings as a dict for the current plugin
    def get_plugin_client_settings(self):
        user_path = self.get_plugin_settings_path("User")
        def_path = self.get_plugin_settings_path("MavensMate")
        settings = {}

        workspace = self.params.get('workspace', None)
        if self.project_name != None and workspace != None:
            try:
                settings['project'] = util.parse_json_from_file(
                    os.path.join(workspace, self.project_name,
                                 self.project_name + '.sublime-settings'))
            except:
                debug('Project settings could not be loaded')
        if not user_path == None:
            try:
                settings['user'] = util.parse_json_from_file(user_path)
            except:
                debug('User settings could not be loaded')
        if not def_path == None:
            try:
                settings['default'] = util.parse_json_from_file(def_path)
            except:
                raise MMException(
                    'Could not load default MavensMate settings.')
        if settings == {}:
            raise MMException(
                'Could not load MavensMate settings. Please ensure they contain valid JSON'
            )
        return settings

    def get_plugin_settings_path(self,
                                 type="User",
                                 obj="mavensmate.sublime-settings"):
        if self.plugin_client == self.PluginClients.SUBLIME_TEXT_3:
            sublime_ver = "Sublime Text 3"
        elif self.plugin_client == self.PluginClients.SUBLIME_TEXT_2:
            sublime_ver = "Sublime Text 2"

        if sys.platform == 'darwin':
            if 'SUBLIME_TEXT' in self.plugin_client:
                if sublime_ver == "Sublime Text 3":
                    if os.path.exists(
                            os.path.join(os.path.expanduser('~'), "Library",
                                         "Application Support", sublime_ver,
                                         "Packages", type, obj)):
                        return os.path.join(os.path.expanduser('~'), "Library",
                                            "Application Support", sublime_ver,
                                            "Packages", type, obj)
                    else:
                        return os.path.join(os.path.expanduser('~'), "Library",
                                            "Application Support",
                                            "Sublime Text", "Packages", type,
                                            obj)
                else:
                    return os.path.join(os.path.expanduser('~'), "Library",
                                        "Application Support", sublime_ver,
                                        "Packages", type, obj)
            elif 'BRACKETS' in self.plugin_client:
                if type == "User":
                    return os.path.join(os.path.expanduser('~'), "Library",
                                        "Application Support", "Brackets",
                                        "extensions", "user",
                                        "mavensmate-user-settings.json")
                else:
                    return os.path.join(os.path.expanduser('~'), "Library",
                                        "Application Support", "Brackets",
                                        "extensions", "user", "mavensmate",
                                        "settings.json")
        elif sys.platform == 'win32' or sys.platform == 'cygwin':
            return os.path.join(os.environ['APPDATA'], sublime_ver, 'Packages',
                                type, obj)
        elif sys.platform == 'linux2':
            return os.path.join(os.path.expanduser('~'), ".config",
                                "sublime-text-3", "Packages", type, obj)
        else:
            return None

    def get_plugin_client_setting(self, key, default=None):
        if self.plugin_client_settings != None:
            if 'project' in self.plugin_client_settings and key in self.plugin_client_settings[
                    "project"]:
                return self.plugin_client_settings["project"][key]
            if 'user' in self.plugin_client_settings and key in self.plugin_client_settings[
                    "user"]:
                return self.plugin_client_settings["user"][key]
            if 'default' in self.plugin_client_settings and key in self.plugin_client_settings[
                    "default"]:
                return self.plugin_client_settings["default"][key]
        return default

    def run_subl_command(self, command, params):
        if self.plugin_client != self.PluginClients.SUBLIME_TEXT_3:
            raise MMException('unsupported operation')

        if sys.platform == 'darwin':
            client_location = self.get_plugin_client_setting(
                'mm_plugin_client_location')
            plugin_app_name = self.get_plugin_client_setting(
                'mm_osx_plugin_client_app_name')
            if client_location == None:
                client_location = '/Applications'
            if plugin_app_name == None:
                plugin_app_name = 'Sublime Text 3.app'
            if os.path.exists(
                    os.path.join('{0}/{1}'.format(client_location,
                                                  plugin_app_name))):
                os.system(
                    "'{0}/{1}/Contents/SharedSupport/bin/subl' --command '{2} {3}'"
                    .format(client_location, plugin_app_name, command, params))
            elif os.path.exists(
                    os.path.join(
                        '{0}/Sublime Text 3.app'.format(client_location))):
                os.system(
                    "'{0}/Sublime Text 3.app/Contents/SharedSupport/bin/subl' --command '{1} {2}'"
                    .format(client_location, command, params))
            else:
                os.system(
                    "'{0}/Sublime Text.app/Contents/SharedSupport/bin/subl' --command '{1} {2}'"
                    .format(client_location, command, params))
        elif 'linux' in sys.platform:
            subl_location = self.get_plugin_client_setting(
                'mm_subl_location', '/usr/local/bin/subl')
            os.system("'{0}' --command '{1} {2}'".format(
                subl_location,
                os.path.join(self.project.location, command, params)))
        else:
            subl_location = self.get_plugin_client_setting(
                'mm_windows_subl_location')
            if not os.path.isfile(
                    subl_location) and "x86" not in subl_location:
                subl_location = subl_location.replace("Program Files",
                                                      "Program Files (x86)")
            params = params.replace('"', '\"')
            cmd = '"{0}" --command "{1} {2}"'.format(
                subl_location,
                os.path.join(self.project.location, command, params))
            subprocess.call(cmd)

    def get_log_level(self):
        try:
            return self.get_plugin_client_setting('mm_log_level')
        except:
            return None

    def get_log_location(self):
        try:
            return self.get_plugin_client_setting('mm_log_location')
        except:
            return None

    def get_sfdc_api_version(self):
        try:
            return self.get_plugin_client_setting('mm_api_version')
        except:
            return None

    def get_app_settings_directory(self):
        if sys.platform == 'darwin':
            if not os.path.exists(
                    os.path.join(os.path.expanduser('~'), 'Library',
                                 'Application Support', 'MavensMate')):
                os.makedirs(
                    os.path.join(os.path.expanduser('~'), 'Library',
                                 'Application Support', 'MavensMate'))
            return os.path.join(os.path.expanduser('~'), 'Library',
                                'Application Support', 'MavensMate')
        elif 'linux' in sys.platform:
            if not os.path.exists(
                    os.path.join(os.path.expanduser('~'), '.config',
                                 'mavensmate')):
                os.makedirs(
                    os.path.join(os.path.expanduser('~'), '.config',
                                 'mavensmate'))
            return os.path.join(os.path.expanduser('~'), '.config',
                                'mavensmate')
        elif sys.platform == 'win32':
            if not os.path.exists(
                    os.path.join(os.environ['APPDATA'], 'MavensMate')):
                os.makedirs(os.path.join(os.environ['APPDATA'], 'MavensMate'))
            return os.path.join(
                os.path.join(os.environ['APPDATA'], 'MavensMate'))

    def sign_in_with_github(self, creds):
        try:
            response = github.sign_in(creds)
            if 'message' in response:
                return util.generate_error_response(response['message'])
            elif 'authentication' in response:
                src = open(
                    os.path.join(self.get_app_settings_directory(),
                                 '.github.json'), "wb")
                src.write(json.dumps(response, sort_keys=False, indent=4))
                src.close()
                return util.generate_success_response(
                    'Connected to GitHub successfully!')
            else:
                return util.generate_error_response(response)
        except Exception, e:
            return util.generate_error_response(
                "Error connecting to GitHub: " + e.message)
import signal
import os
import switch
import rotary
import logging 

PandoraEvent = enum.enum(
        ARTIST_BOOKMARK="artistbookmark", 
        SONG_BAN="songban", 
        SONG_BOOKMARK="songbookmark",
        SONG_EXPLAIN="songexplain",  
        SONG_FINISH="songfinish",  
        SONG_LOVE="songlove",  
        SONG_MOVE="songmove",  
        SONG_SHELF="songshelf",  
        SONG_START="songstart",
        STATION_ADD_MUSIC="stationaddmusic",    
        STATION_ADD_SHARED="stationaddshared",   
        STATION_CREATE="stationcreate",   
        STATION_DELETE="stationdelete",
        STATION_FETCH_PLAYLIST="stationfetchplaylist", 
        STATION_QUICK_MIX_TOGGLE="stationquickmixtoggle", 
        STATION_RENAME="stationrename",
        USER_GET_STATIONS="usergetstations",
        PANDORA_CONTROLLER_QUIT="pandoracontrollerquit")


PandoraData = enum.enum(
        ARTIST="artist",
        TITLE="title",
        ALBUM="album",
	- F9_KEY
	- F10_KEY
	- F11_KEY
	- F12_KEY
	- DELETE_KEY
	- HELP_KEY

'''
import platform
import gwindow
from enum import enum

EventClassType = enum(  NULL_EVENT   = 0x000, \
						ACTION_EVENT = 0x010, \
						KEY_EVENT    = 0x020, \
						TIMER_EVENT  = 0x040, \
						WINDOW_EVENT = 0x080, \
						MOUSE_EVENT  = 0x100, \
						CLICK_EVENT  = 0x200, \
						ANY_EVENT    = 0x3F0)
						
EventType = enum(   WINDOW_CLOSED    = EventClassType.WINDOW_EVENT + 1, \
					WINDOW_RESIZED   = EventClassType.WINDOW_EVENT + 2, \
					ACTION_PERFORMED = EventClassType.ACTION_EVENT + 1, \
					MOUSE_CLICKED    = EventClassType.MOUSE_EVENT + 1, \
					MOUSE_PRESSED    = EventClassType.MOUSE_EVENT + 2, \
					MOUSE_RELEASED   = EventClassType.MOUSE_EVENT + 3, \
					MOUSE_MOVED      = EventClassType.MOUSE_EVENT + 4, \
					MOUSE_DRAGGED    = EventClassType.MOUSE_EVENT + 5, \
					KEY_PRESSED      = EventClassType.KEY_EVENT + 1, \
					KEY_RELEASED     = EventClassType.KEY_EVENT + 2, \
					KEY_TYPED        = EventClassType.KEY_EVENT + 3, \
from enum import enum

class_state = enum('TIMEOUT','RECEIVED','TRANSMITTED','IDLE','NOT_RECEIVED')

phone_state = enum('INCREMENT_AND_WAIT','CHECK_AND_WAIT','REQUEST_AND_WAIT','ERROR_CHECK','ENCRYPT_AND_WAIT','IDLE')

station_state = enum('INCREMENT_AND_WAIT','CHECK_AND_WAIT','REQUEST_AND_WAIT','ERROR_CHECK','ENCRYPT_AND_WAIT','IDLE')

Example #12
0
MAXCLIENTS = 256

CR_DEFAULT = 0

message_types = enum('SV_SERVINFO', 'SV_WELCOME', 'SV_INITCLIENT', 'SV_POS', 'SV_POSC', 'SV_POSN', 'SV_TEXT', 'SV_TEAMTEXT', 'SV_TEXTME', 'SV_TEAMTEXTME', 
                     'SV_SOUND', 'SV_VOICECOM', 'SV_VOICECOMTEAM', 'SV_CDIS', 
                     'SV_SHOOT', 'SV_EXPLODE', 'SV_SUICIDE', 'SV_AKIMBO', 'SV_RELOAD', 'SV_AUTHT', 'SV_AUTHREQ', 'SV_AUTHTRY', 'SV_AUTHANS', 'SV_AUTHCHAL', 
                     'SV_GIBDIED', 'SV_DIED', 'SV_GIBDAMAGE', 'SV_DAMAGE', 'SV_HITPUSH', 'SV_SHOTFX', 'SV_THROWNADE', 
                     'SV_TRYSPAWN', 'SV_SPAWNSTATE', 'SV_SPAWN', 'SV_SPAWNDENY', 'SV_FORCEDEATH', 'SV_RESUME', 
                     'SV_DISCSCORES', 'SV_TIMEUP', 'SV_EDITENT', 'SV_ITEMACC', 
                     'SV_MAPCHANGE', 'SV_ITEMSPAWN', 'SV_ITEMPICKUP', 
                     'SV_PING', 'SV_PONG', 'SV_CLIENTPING', 'SV_GAMEMODE', 
                     'SV_EDITMODE', 'SV_EDITH', 'SV_EDITT', 'SV_EDITS', 'SV_EDITD', 'SV_EDITE', 'SV_NEWMAP', 
                     'SV_SENDMAP', 'SV_RECVMAP', 'SV_REMOVEMAP', 
                     'SV_SERVMSG', 'SV_ITEMLIST', 'SV_WEAPCHANGE', 'SV_PRIMARYWEAP', 
                     'SV_FLAGACTION', 'SV_FLAGINFO', 'SV_FLAGMSG', 'SV_FLAGCNT', 
                     'SV_ARENAWIN', 
                     'SV_SETADMIN', 'SV_SERVOPINFO', 
                     'SV_CALLVOTE', 'SV_CALLVOTESUC', 'SV_CALLVOTEERR', 'SV_VOTE', 'SV_VOTERESULT', 
                     'SV_SETTEAM', 'SV_TEAMDENY', 'SV_SERVERMODE', 
                     'SV_WHOIS', 'SV_WHOISINFO', 
                     'SV_LISTDEMOS', 'SV_SENDDEMOLIST', 'SV_GETDEMO', 'SV_SENDDEMO', 'SV_DEMOPLAYBACK', 
                     'SV_CONNECT', 'SV_SPECTCN', 
                     'SV_SWITCHNAME', 'SV_SWITCHSKIN', 'SV_SWITCHTEAM', 
                     'SV_CLIENT', 
                     'SV_EXTENSION', 
                     'SV_MAPIDENT', 'SV_HUDEXTRAS', 'SV_POINTS', 'SV_NUM')
                     
flag_states = enum('CTFF_INBASE', 'CTFF_STOLEN', 'CTFF_DROPPED', 'CTFF_IDLE')

flag_messages = enum('FM_PICKUP', 'FM_DROP', 'FM_LOST', 'FM_RETURN', 'FM_SCORE', 'FM_KTFSCORE', 'FM_SCOREFAIL', 'FM_RESET', 'FM_NUM')
Example #13
0
from enum import enum

tcp_states = enum('CLOSED', 'SYN_SENT', 'SYN_RECV', 'LISTEN', 'ESTABLISHED',
                  'CLOSE_WAIT', 'LAST_ACK', 'FIN_WAIT1', 'FIN_WAIT2',
                  'CLOSING', 'TIME_WAIT')
Example #14
0
from BeautifulSoup import BeautifulSoup
try:
	from libs import requests
except:
	path = kodi.vfs.join(kodi.get_path(), "libs")
	sys.path.append(path)
	import requests
from enum import enum

class installerException(Exception):
	pass

tva_user = '******'

# Define source types
SOURCES = enum(DEFAULT=0, REPO=1, ZIP=2, SUPER=3, NATIVE=4)

def update_addons():
	return
	save_file = kodi.vfs.join(kodi.get_profile(), "install.log")
	if vfs.exists(save_file):
		temp = kodi.load_data(save_file, format='json', compress=True)
	else:
		temp = {}
	kodi.open_busy_dialog()
	v = kodi.get_kodi_version()
	from sqlite3 import dbapi2
	dbf = kodi.vfs.join("special://profile/Database", "Addons20.db")
	if v >= 17:
		dbf = kodi.vfs.join("special://profile/Database", "Addons27.db")
		SQL = """SELECT installed.addonID, addons.version from installed 
Example #15
0
class CT200(object):
    """\
    CT200 적외선 온도센서의 RS485 프로토콜을 구현한 클래스이다.
    _로 시작하는 메소드는 private 로 간주하고,
    all 이 붙어있는 메소드는 연결된 전체 센서에 대한 명령으로 이해하면 된다.

        >>> config = {"tty" : "/dev/ttyUSB0", "id" : [1, 2], "retry" : 3}
        sensor = CT200 (config)
        print sensor.readalltemperature ()
        ...
    """
    FUNCTION_CODE = enum.enum(READ_TEMP=0x03,
                              READ_EMIS=0x04,
                              WRITE_ID=0x06,
                              WRITE_EMIS=0x06)
    DEFAULT_BAUDRATE = 19200

    def __init__(self, config):
        """\
        클래스 생성자로 딕셔너리형식의 설정을 인자로 한다.

        :param config: CT200 센서를 위한 설정

        config["tty"] -- RS485 통신을 위한 포트
        config["id"] --  연결된 적외선 온도센서의 아이디 리스트
        config["retry"] --  통신실패시 재시도 회수

        >>> config = {"tty" : "/dev/ttyUSB0", "id" : [1, 2], "retry" : 3}

        """

        self.retry = config["retry"]
        self.ser = serial.Serial(config["tty"], CT200.DEFAULT_BAUDRATE)
        self.ser.close()
        self.ser.open()
        self.devices = []
        for devid in config["id"]:
            dev = {"id": devid, "target": [], "environs": []}
            self.devices.append(dev)

    @staticmethod
    def _crc(bytearr):
        """
        CT200 이 사용하는 CRC를 계산한다.

        :param bytearr: CRC를 계산하기위한 바이트 배열
        :return: 2byte CRC 값
        """
        crc = 0xFFFF
        for bchar in bytearr:
            crc ^= bchar
            for _ in range(8):
                flag = crc & 0x0001
                crc >>= 1
                if flag:
                    crc ^= 0xA001
        return crc

    @staticmethod
    def _getresponselength(func):
        """
        응답별로 응답의 길이를 알려준다.
        """
        if func == CT200.FUNCTION_CODE.READ_TEMP:
            return 9
        elif func == CT200.FUNCTION_CODE.READ_EMIS:
            return 7
        return 8

    def _getdevice(self, devid):
        """\
        내부 버퍼에 저장된 장비에 관한 정보를 읽어온다.

        :param devid: 장비아이디
        """
        for device in self.devices:
            if device["id"] == devid:
                return device
        return None

    def clearall(self):
        """
        내부적으로 측정치 평균을 내기 위해 들고 있는 내부 임시 버퍼값을 모두 삭제한다.
        """
        for device in self.devices:
            device["target"] = []
            device["environs"] = []

    def clear(self, devid):
        """
        특정 장비아이디(devid)를 가진 센서의 내부 임시 버퍼값을 삭제한다.

        :param devid: 장비아이디
        """
        device = self._getdevice(devid)
        if device:
            device["target"] = []
            device["environs"] = []

    def getallaverage(self):
        """
        내부 임시 버퍼값을 이용하여 센서별 평균치를 계산해준다.
        """
        ret = []
        for device in self.devices:
            ret.append(self.getaverage(device["id"]))
        return ret

    def getaverage(self, devid):
        """\
        특정 장비아이디(devid)를 가진 센서의 평균치를 계산해준다.

        :param devid: 장비아이디
        :return: 평균 온도값
        """
        device = self._getdevice(devid)
        if device:
            if len(device["target"]) == 0:
                return (0, 0)
            target = reduce(lambda x, y: x + y, device["target"]) \
                        / len(device["target"])
            environs = reduce(lambda x, y: x + y, device["environs"]) \
                        / len(device["environs"])
            return {"id": devid, "target": target, "environs": environs}
        return None

    def readalltemperature(self):
        """
        모든 장비로 부터 순차적으로 온도정보를 읽어옵니다.
        """
        ret = []
        for device in self.devices:
            ret.append(self.readtemperature(device["id"]))
        return ret

    def readtemperature(self, devid):
        """\
        특정 장비아이디(devid)를 가진 센서의 온도정보를 읽어옵니다.

        :param devid: 장비아이디
        :return: 성공시 읽어온 온도값, 없는 장비아이디이거나 실패시 None
        """
        device = self._getdevice(devid)
        if device == None:
            sys.stderr.write("no device with " + str(devid) + "\n")
            return None

        request = array.array(
            "B",
            [devid, CT200.FUNCTION_CODE.READ_TEMP, 0x04, 0xB0, 0x00, 0x02])
        for _ in range(self.retry):
            if self._writemsg(request):
                response = self._readmsg(CT200.FUNCTION_CODE.READ_TEMP)
                if response:
                    target = struct.unpack('>h', response[3:5])[0] / 10.0
                    environs = struct.unpack('>h', response[5:7])[0] / 10.0

                    device["target"].append(target)
                    device["environs"].append(environs)

                    return {
                        "id": devid,
                        "target": target,
                        "environs": environs
                    }

                sys.stderr.write("fail to get response.\n")
            else:
                sys.stderr.write("fail to send request.\n")
            sys.stderr.write("Retry to read temperature.\n")
        return None

    def writeid(self, devid):
        """\
        연결된 장비에 입력된 아이디(devid)를 배정합니다. 주의) 여러장비가 연결되어 있으면 안됩니다.

        :param devid: 장비아이디
        :return: 성공시 true, 실패시 false
        """
        request = array.array(
            "B", [0xFF, CT200.FUNCTION_CODE.WRITE_ID, 0x03, 0xe8, 0x00, devid])
        for _ in range(self.retry):
            if self._writemsg(request):
                response = self._readmsg(CT200.FUNCTION_CODE.WRITE_ID)
                if response:
                    if response[5] == request[5]:
                        return True
                    else:
                        sys.stderr.write("The device gave a well-formed \
                                response, but the id was not changed.\n")
                        return False
                sys.stderr.write("fail to get response.\n")
            else:
                sys.stderr.write("fail to send request.\n")
            sys.stderr.write("Retry to write id.\n")
        sys.stderr.write("Fail to write id.\n")
        return False

    def setemissivity(self, emissivity):
        """\
        장비에 방사율을 설정합니다.

        :param emissivity: 방사율 값으로 0.01에서 0.99까지 설정이 가능합니다.
        :return: 성공하면 true, 실패하거나 방사율값이 범위를 벗어나면 false
        """
        if emissivity < 0.01 or emissivity > 0.99:
            sys.stderr.write("Emissivity should be between 0.01 and 0.99.\n")
            return False

        emis = int(emissivity * 100)
        request = array.array(
            "B",
            [0xFF, CT200.FUNCTION_CODE.WRITE_EMIS, 0x03, 0x20, 0x00, emis])
        for _ in range(self.retry):
            if self._writemsg(request):
                response = self._readmsg(CT200.FUNCTION_CODE.WRITE_EMIS)
                if response:
                    if response[5] == request[5]:
                        return True
                    else:
                        sys.stderr.write("The device gave a well-formed \
                            response, but the emissivity was not changed.\n")
                        return False
                sys.stderr.write("fail to get response.\n")
            else:
                sys.stderr.write("fail to send request.\n")
            sys.stderr.write("Retry to set emissivity.\n")
        sys.stderr.write("Fail to set emissivity.\n")
        return False

    def getemissivity(self, devid):
        """\
        특정 장비아이디(devid)를 가진 센서의 방사율을 읽어옵니다.

        :param devid: 장비아이디
        :return: 성공시 방사율, 없는 장비아이디이거나 실패시 None
        """
        device = self._getdevice(devid)
        if device == None:
            sys.stderr.write("no device with " + str(devid) + "\n")
            return None

        request = array.array(
            "B",
            [devid, CT200.FUNCTION_CODE.READ_EMIS, 0x03, 0x20, 0x00, 0x01])
        for _ in range(self.retry):
            if self._writemsg(request):
                response = self._readmsg(CT200.FUNCTION_CODE.READ_EMIS)
                if response:
                    return response[4] / 100.0
                sys.stderr.write("fail to get response.\n")
            else:
                sys.stderr.write("fail to send request.\n")
            sys.stderr.write("Retry to get emissivity.\n")
        sys.stderr.write("Fail to get emissivity.\n")
        return None

    def _readmsg(self, func):
        """
        CT200으로 부터 전달되는 응답을 읽어줍니다.
        """
        length = CT200._getresponselength(func)
        try:
            self.ser.setRTS(1)
            self.ser.setDTR(1)
            buf = self.ser.read(length)
        except serial.SerialException as ex:
            sys.stderr.write("fail to read : " + str(ex))
            raise

        bytearr = array.array("B", buf)
        rescrc = struct.unpack('H', bytearr[-2:])
        if CT200._crc(bytearr[:-2]) == rescrc[0]:
            return bytearr[:-2]
        else:
            sys.stderr.write("fail to check crc. message would be dropped.\n")
            sys.stderr.write(str(bytearr) + "\n")
            return None

    def _writemsg(self, request):
        """
        CT200으로 요청을 전송합니다.
        """
        bytearr = request.tostring() + struct.pack('H', CT200._crc(request))
        try:
            self.ser.setDTR(0)
            self.ser.setRTS(0)
            time.sleep(0.500)
            self.ser.write(bytearr[0])
            self.ser.flush()
            time.sleep(0.001)
            self.ser.write(bytearr[1:])
            self.ser.flush()
            time.sleep(0.005)
        except serial.SerialTimeoutException:
            return False
        except serial.SerialException as ex:
            sys.stderr.write("fail to write : " + str(ex))
            raise
        return True
Example #16
0

class CommError(Exception):
    pass


class BadCRC(Exception):
    pass


commands = enum(CONVERTTEMP=0x44,
                RSCRATCHPAD=0xbe,
                WSCRATCHPAD=0x4e,
                CPYSCRATCHPAD=0x48,
                RECEEPROM=0xb8,
                RPWRSUPPLY=0xb4,
                SEARCHROM=0xf0,
                READROM=0x33,
                MATCHROM=0x55,
                SKIPROM=0xcc,
                ALARMSEARCH=0xec)


class OneWire():
    """
    Implementation of various 1-wire functions
    """
    def __init__(self, simulated=False):
        if simulated:
            self.uart = simulator.UART()
        else:
Example #17
0
__author__     = 'Jan Veverka'
__copyright__  = 'Unknown'
__credits__    = []
__licence__    = 'Unknown'
__version__    = '0.1.1'
__maintainer__ = 'Jan Veverka'
__email__      = '*****@*****.**'
__status__     = 'Development'


import os
import json
import enum

## Enumerates different types of JSON meta files.
Type = enum.enum('MacroMerger', 'MiniEoR', 'Unknown')

#______________________________________________________________________________
class Filename(object):
    '''
    Takes a filename of a meta-data file, parses it and stores the results in
    its attributes.
    
    The given path is required to be of the form run<N>_ls<M>_*_*.jsn
    with <N> and <M> denoting integers, eventually padded with zeroes:
        
        >>> Filename('foo')
        Traceback (most recent call last):
            ...
        ValueError: Bad filename `foo', expect `.jsn' extension!
Example #18
0
try:
    if kodi.get_setting('fanart_proxy_remote') == 'true':
        client_host = kodi.get_setting('fanart_proxy_host')
        client_port = kodi.get_setting('fanart_proxy_port')
        client_protocol = kodi.get_setting('fanart_proxy_protocol')
    else:
        client_host = '127.0.0.1'
        client_port = kodi.get_setting('control_port', 'service.fanart.proxy')
        client_protocol = kodi.get_setting('control_protocol',
                                           'service.fanart.proxy')
    BASE_FANART_URL = '%s://%s:%s/api/images' % (client_protocol, client_host,
                                                 client_port)
except:
    BASE_FANART_URL = ''

DEFAULT_VIEWS = enum(
    DEFAULT=550,
    LIST=int(kodi.get_setting('default_list_view'))
    if kodi.get_setting('default_list_view') else 550,
    MOVIES=int(kodi.get_setting('default_movie_view'))
    if kodi.get_setting('default_movie_view') else 550,
    SHOWS=int(kodi.get_setting('default_show_view'))
    if kodi.get_setting('default_show_view') else 550,
    SEASONS=int(kodi.get_setting('default_season_view'))
    if kodi.get_setting('default_season_view') else 550,
    EPISODES=int(kodi.get_setting('default_episode_view'))
    if kodi.get_setting('default_episode_view') else 550,
    STREAMS=int(kodi.get_setting('default_stream_view'))
    if kodi.get_setting('default_stream_view') else 550,
)
Example #19
0
    print("[GAMEJOLT]", "Missing gamejolt.json file!")

# Globals
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
TICK_SEC = 20
TICK = 1.0 / TICK_SEC
GAME_TICKS = TICK_SEC * 30
TTL = TICK_SEC * 7
MAX_PLAYERS = 8
HSPEED = 6.5
VSPEED = 18
GRAVITY = 0.8
DRAG = 0.35
HVEL = HSPEED * (pow(DRAG, 4) + pow(DRAG, 3) + pow(DRAG, 2) + DRAG + 1)
msg = enum(
    "msg",
    "join leave game update login init endgame win dead info leaderboard lobbyinfo"
)


# Main Game class
class Game(object):
    def __init__(self, game_num, tick_sec, game_ticks):
        self.num = game_num
        self.room = "game_{}".format(self.num)
        self.title = "[GAME {}]".format(self.num)

        self.actors = []
        self.players = []

        self.started = False
        self.finished = False
Example #20
0
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */"""

# Known licenses
License = enum('LGPL', 'MIPS', 'JPEG', 'OGG_MA_MR_2005')

# Tuple describing license and similarity to the FFmpeg LGPL reference for a
# given file. See KNOWN_FILE_BUCKETS.
FileInfo = collections.namedtuple('FileInfo', 'license, license_digest')

# Most files in FFmpeg are LGPL, but there are a few exceptions that are worth
# bucketing together to avoid redundant license texts. The hex values are
# digests of the comment header, used to detect changes in the unlikely event
# that their license texts are altered. Any changes will require manual review
# to decide whether the to update the bucketing.
KNOWN_FILE_BUCKETS = [
    # Files that are LGPL but just miss the similarity cutoff.
    [
        'libavcodec/codec_desc.c', License.LGPL,
        '091f9c6d1efc62038e516f5c67263962'
Example #21
0
from enum import enum

SourceMode = enum(VOLTAGE=1, CURRENT=2, COMMON=3)
Example #22
0
import unittest
from enum import enum

Resources = enum('Red', 'Green', 'Blue', 'Iron', 'Brick', 'Glass', 'Bank')
Firms = [Resources.Red, Resources.Green, Resources.Blue]
Goods = [Resources.Iron, Resources.Brick, Resources.Glass]
FirmsOrGoods = Firms + Goods
AllResources = Resources.reverse_mapping.keys()

def isFirm(resource):
  return (resource >= 0 and resource <= 2);

def isGoods(resource):
  return (resource >= 3 and resource <= 5);

def nextFirm(firm):
  if not isFirm(firm):
    raise RuntimeError('Resource is not a firm ' +
                       Resources.reverse_mapping[firm])
  return (firm + 1) % 3;

def nextGoods(goods):
  if not isGoods(goods):
    raise RuntimeError('Resource is not a goods ' +
                       Resources.reverse_mapping[goods])
  return ((goods - 3) + 1) % 3 + 3;

def mainGoods(firm):
  if not isFirm(firm):
    raise RuntimeError('Resource is not a firm ' +
                       Resources.reverse_mapping[firm])
Example #23
0

class githubException(Exception):
    pass


base_url = "https://api.github.com"
content_url = "https://raw.githubusercontent.com/%s/master/%s"
master_url = "https://github.com/%s/%s/archive/master.zip"
page_limit = 100

#SORT_ORDER = enum(REPO=100, PLUGIN=99, PROGRAM=98, SKIN=97, SERVICE=96, SCRIPT=95, OTHER=0)
SORT_ORDER = enum(REPO=0,
                  PLUGIN=1,
                  PROGRAM=2,
                  SKIN=3,
                  SERVICE=4,
                  SCRIPT=5,
                  OTHER=100)


def search(q, method=False):
    if method == 'user':
        return call("/search/repositories",
                    query={
                        "per_page": page_limit,
                        "q": "user:%s" % q
                    })
    if method == 'title':
        return call("/search/repositories",
                    query={
Example #24
0
GN_CONDITION_END = """}

"""
GN_C_SOURCES_BEGIN = """ffmpeg_c_sources += [
"""
GN_GAS_SOURCES_BEGIN = """ffmpeg_gas_sources += [
"""
GN_YASM_SOURCES_BEGIN = """ffmpeg_yasm_sources += [
"""
GN_SOURCE_ITEM = """  "%s",
"""
GN_SOURCE_END = """]
"""

# Controls GYP conditional stanza generation.
Attr = enum('ARCHITECTURE', 'TARGET', 'PLATFORM')
SUPPORT_MATRIX = {
    Attr.ARCHITECTURE:
    set(['ia32', 'x64', 'arm', 'arm64', 'arm-neon', 'mipsel', 'mips64el']),
    Attr.TARGET:
    set(['Chromium', 'Chrome', 'ChromiumOS', 'ChromeOS']),
    Attr.PLATFORM:
    set(['android', 'linux', 'win', 'mac'])
}


def NormalizeFilename(name):
    """ Removes leading path separators in an attempt to normalize paths."""
    return string.lstrip(name, os.sep)

#!/usr/bin/python3
# -*-coding:utf-8 -*

import sys, os
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + "/../formation")
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + "/../contraintes")
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + "/../../outils")
import Creneau, Seance, Td, Tp, Cm, Examen, Autre
import Blocage
import Fabrique, enum


# enum des valeurs de clefs possible pour cette fabrique.
CreneauxPossible = enum.enum('CRENEAU', 'SEANCE', 'AUTRE', 'EXAMEN', 'TD', 'TP', 'CM', 'BLOCAGE')


class FabriqueCreneau(Fabrique.Fabrique):
	"""
	La fabrique qui va construire des L{Creneau} (ou des classes plus
	spécialisées, comme une L{Seance}, un L{Cm}, etc.
	USAGE :
	Si on veut quelque chose de particulier, il suffit de renseigner
	un des enum situé plus haut (CreneauxPossible).
	Il faudra néanmoins fournir un identifiant et un Horaire en tant qu'arguments.
	@author: Laurent Bardoux p1108365
	@version: 1.0
	"""
	
	def __init__(self):
		"""
		Le constructeur de cette fabrique de L{Creneau}.
# Neuron Model

from multiprocessing import Value
from enum import enum
from soma import Soma
from synapse import Synapse
from molecule import Transporters, Receptors
from photoreceptor import PhotoreceptorSoma

NeuronTypes = enum(
    PHOTORECEPTOR = 0,
    GANGLION = 1
)

class Neuron:
    def __init__(self, neuron_id=None, base_current=0.0,
                    neuron_type=NeuronTypes.GANGLION, environment=None):
        self.environment = environment
        self.neuron_id = neuron_id

        # Soma and axon threshold
        if neuron_type == NeuronTypes.PHOTORECEPTOR:
            self.soma = PhotoreceptorSoma(environment)
            self.axon_threshold = -9999
        elif neuron_type == NeuronTypes.GANGLION:
            self.soma = Soma(base_current, environment)
            self.axon_threshold = -55.0

        # Inputs
        self.dendrites = []
        self.external_activation = Value('d', 0.0)
#!/usr/bin/python3
# -*-coding:utf-8 -*

import os, sys
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + "/")
import Contrainte, Blocage, Ressource, Precedence, Obligation, DateLimite
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + "/../../outils")
import enum, Fabrique


# Création de l'enum pour la fabrique
Contraintes = enum.enum('PRECEDENCE', 'OBLIGATION', 'DATE_LIMITE', 'RESSOURCE')


class FabriqueContrainte(Fabrique.Fabrique):
	"""
	Voici la classe qui va se charger de la création des contraintes.
	Via un "enum", il suffira de demander ce que l'on veut
	Et la fabrique nous le fournira directement, si tant est qu'on lui
	fourni les bons matériaux.
	USAGE :
	--> créer une Obligation : il faut un nombre en argument
	--> créer une Blocage : il faut un ou plusieurs nombre(s)  en argument
	--> créer une DateLimite : il faut un nombre en argument
	--> créer une Precedence : il faut 2 arguments
	@author: Laurent Bardoux p1108365
	@version: 2.0
	"""
	
	def __init__(self):
		"""
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */'''

# Known licenses
License = enum('LGPL', 'MIPS', 'JPEG', 'OGG_MA_MR_2005')

# Tuple describing license and similarity to the FFmpeg LGPL reference for a
# given file. See KNOWN_FILE_BUCKETS.
FileInfo = collections.namedtuple('FileInfo', 'license, license_digest')

# Most files in FFmpeg are LGPL, but there are a few exceptions that are worth
# bucketing together to avoid redundant license texts. The hex values are
# digests of the comment header, used to detect changes in the unlikely event
# that their license texts are altered. Any changes will require manual review
# to decide whether the to update the bucketing.
KNOWN_FILE_BUCKETS = [
    # Files that are LGPL but just miss the similarity cutoff.
    ['libavcodec/codec_desc.c', License.LGPL, '091f9c6d1efc62038e516f5c67263962'],
    # Files with MIPS license.
    ['libavcodec/mdct_fixed_32.c', License.MIPS, '179c17c9dab77f95dc6540709b5fb8cd'],
Example #29
0
            response = True  # Start with high bus
            for device in self.devices:
                response &= device.frame(bitToSend)

            if response:
                self.inputBuffer.append(0xFF)  # All ones in reply.
            else:
                self.inputBuffer.append(0xFE)  # The first bit zero.
        else:
            # We have sent a strange byte, or have the wrong baudrate
            raise ValueError('Unhandled data sent on UART @ %d baud: %s' %
                             (self.baudrate, str(data)))


state = enum('reset', 'romcommand', 'idle', 'search', 'searchcomplement',
             'searchselectbit')
romcommand = enum(search=0xF0,
                  read=0x33,
                  match=0x55,
                  skip=0xCC,
                  alarmsearch=0xEC)


class OWdevice:
    """
    This class implements the logic of a 1-wire device. It is initialized with
    an ID (or generates one randomly).

    It can be attached to the simulated UART and will then receive data from
    it and will also be queried for responses.
    """
Example #30
0
GN_CONDITION_END = """}

"""
GN_C_SOURCES_BEGIN = """ffmpeg_c_sources += [
"""
GN_GAS_SOURCES_BEGIN = """ffmpeg_gas_sources += [
"""
GN_YASM_SOURCES_BEGIN = """ffmpeg_yasm_sources += [
"""
GN_SOURCE_ITEM = """  "%s",
"""
GN_SOURCE_END = """]
"""

# Controls GYP conditional stanza generation.
Attr = enum('ARCHITECTURE', 'TARGET', 'PLATFORM')
SUPPORT_MATRIX = {
    Attr.ARCHITECTURE:
        set(['ia32', 'x64', 'arm', 'arm64', 'arm-neon', 'mipsel', 'mips64el']),
    Attr.TARGET: set(['Chromium', 'Chrome', 'ChromiumOS', 'ChromeOS']),
    Attr.PLATFORM: set(['android', 'linux', 'win', 'mac'])
}


def NormalizeFilename(name):
  """ Removes leading path separators in an attempt to normalize paths."""
  return string.lstrip(name, os.sep)


def CleanObjectFiles(object_files):
  """Removes unneeded object files due to linker errors, binary size, etc...
Example #31
0
from enum import enum
from struct import Struct

##############################################
## Parameters for the structure drawing     ##
##############################################

TDP_LEN_LBL = 16

TBL_TYPES = enum(
    itBASIC = 0, 
    itISOTOPIC = 1, 
    itSTEREO = 2, 
    TDP_NUM_PAR =3
)

TBL_LABELS = enum(
    ilSHOWN = 0,
    TDP_NUM_LBL = 1
)

class TBL_DRAW_PARMS(Struct):
    ReqShownFoundTxt = None
    ReqShownFound = None
    nOrientation = None # 10*degrees: 0 or 2700
    bDrawTbl = None

class SET_DRAW_PARMS(Struct): # input only: how to draw or calculate
    tdp = None
    ulDisplTime = None
    bOrigAtom = None
Example #32
0
sys.path.append('../build/swig')
sys.path.append('../build/.libs')

import artifastring_instrument
ARTIFASTRING_SAMPLE_RATE = artifastring_instrument.ARTIFASTRING_INSTRUMENT_SAMPLE_RATE
HAPTIC_DOWNSAMPLE_FACTOR = artifastring_instrument.HAPTIC_DOWNSAMPLE_FACTOR

import vivi_controller

import actions_file
import collections
import monowav
import midi_pos

import enum
COMMANDS = enum.enum('BOW', 'FINGER', 'TENSION', 'UNSAFE', 'RESET')

ArtifastringInit = collections.namedtuple('ArtifastringInit', """
    instrument_type,
    instrument_number,
    """)

HOPSIZE = artifastring_instrument.NORMAL_BUFFER_SIZE;


import os
### portaudio should use plughw
os.environ['PA_ALSA_PLUGHW'] = '1'
import pyaudio

def make_audio_stream():
#!/usr/bin/python3
# -*-coding:utf-8 -*

import sys, os
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + "/../../../outils")
import enum, Fabrique
import ExporteurIcs
import ExporteurTxt


exporteurs = enum.enum('TXT', 'ICS')

class FabriqueExporteur(Fabrique.Fabrique):
	"""
	La classe chargée de créer les exporteurs, afin d'assurer que ce soit
	la seule à devoir etre importer dans les fichiers nécéssitants une exportation.
	Cela assure une faible dépendance envers toute une arborescence de classes.
	
	@author: Laurent Bardoux p1108365
	@version: 1.0
	"""
	
	def __init__(self):
		"""
		Construit une instance de FabriqueExporteur.
		Cela va initialiser le dictionaire interne à toutes les Fabriques
		@param self: L'argument implicite.
		On peut ajouter des L{Exporteur} simplement en modifiant le dictionnaire
		et l'enum.
		"""
		dico = {
Example #34
0
import datetime
from bson.objectid import ObjectId
from pymongo import MongoClient

from enum import enum

client = MongoClient()
db = client["c4"]
games_collection = db["games"]
players_collection = db["players"]


PlayerTypes = enum(SPECTATOR='spectator', HOST='host', CHALLENGER='challenger')


class Game():
    '''
    This class wraps the MongoDB game collection
    Schema:
      - name
      - host_id
      - host_name
      - board
      - host_turn
      - last_access
      - challenger
      - staged_delete (used to confirm a game delete from both players when
                       a game ends)
    '''
    @classmethod
    def new(cls, name, host_id, host_name):
Example #35
0
	- F10_KEY
	- F11_KEY
	- F12_KEY
	- DELETE_KEY
	- HELP_KEY

"""
import platform
import gwindow
from enum import enum

EventClassType = enum(
    NULL_EVENT=0x000,
    ACTION_EVENT=0x010,
    KEY_EVENT=0x020,
    TIMER_EVENT=0x040,
    WINDOW_EVENT=0x080,
    MOUSE_EVENT=0x100,
    CLICK_EVENT=0x200,
    ANY_EVENT=0x3F0,
)

EventType = enum(
    WINDOW_CLOSED=EventClassType.WINDOW_EVENT + 1,
    WINDOW_RESIZED=EventClassType.WINDOW_EVENT + 2,
    ACTION_PERFORMED=EventClassType.ACTION_EVENT + 1,
    MOUSE_CLICKED=EventClassType.MOUSE_EVENT + 1,
    MOUSE_PRESSED=EventClassType.MOUSE_EVENT + 2,
    MOUSE_RELEASED=EventClassType.MOUSE_EVENT + 3,
    MOUSE_MOVED=EventClassType.MOUSE_EVENT + 4,
    MOUSE_DRAGGED=EventClassType.MOUSE_EVENT + 5,
    KEY_PRESSED=EventClassType.KEY_EVENT + 1,
import dom_parser
from libs import requests
from enum import enum
from distutils.version import LooseVersion
from libs.database import DB

class githubException(Exception):
	pass

base_url = "https://api.github.com"
content_url = "https://raw.githubusercontent.com/%s/master/%s"
master_url = "https://github.com/%s/%s/archive/master.zip"
page_limit = 100

#SORT_ORDER = enum(REPO=100, PLUGIN=99, PROGRAM=98, SKIN=97, SERVICE=96, SCRIPT=95, OTHER=0)
SORT_ORDER = enum(REPO=0, PLUGIN=1, PROGRAM=2, SKIN=3, SERVICE=4, SCRIPT=5, OTHER=100)


def search(q, method=False):
	if method=='user':
		return call("/search/repositories", query={"per_page": page_limit, "q": "user:%s" % q})
	if method=='title':
		return call("/search/repositories", query={"per_page": page_limit, "q": "in:name+%s" % q})
	else:
		return call("/search/repositories", query={"per_page": page_limit, "q": q})

re_plugin = re.compile("^plugin\.", re.IGNORECASE)
re_service = re.compile("^service\.", re.IGNORECASE)
re_script = re.compile("^script\.", re.IGNORECASE)
re_repository = re.compile("^repository\.", re.IGNORECASE)
re_program = re.compile("^(program\.)|(plugin\.program)", re.IGNORECASE)

### load artifastring from build dir if exists
import sys
sys.path.append('../build/swig')
sys.path.append('../build/.libs')

import artifastring_instrument
ARTIFASTRING_SAMPLE_RATE = artifastring_instrument.ARTIFASTRING_INSTRUMENT_SAMPLE_RATE
HAPTIC_DOWNSAMPLE_FACTOR = artifastring_instrument.HAPTIC_DOWNSAMPLE_FACTOR

import actions_file
import collections

import enum
COMMANDS = enum.enum('BOW', 'FINGER', 'TENSION', 'UNSAFE', 'RESET')

ArtifastringInit = collections.namedtuple('ArtifastringInit', """
    instrument_type,
    instrument_number,
    """)

HOPSIZE = artifastring_instrument.NORMAL_BUFFER_SIZE


import os
### portaudio should use plughw
os.environ['PA_ALSA_PLUGHW'] = '1'
import pyaudio

def make_audio_stream():
Example #38
0
from enum import enum

tcp_states = enum('CLOSED', 'SYN_SENT', 'SYN_RECV', 'LISTEN',
    'ESTABLISHED', 'CLOSE_WAIT', 'LAST_ACK', 'FIN_WAIT1', 'FIN_WAIT2',
    'CLOSING', 'TIME_WAIT')

Example #39
0
import socket
import struct
import socket_utils
import inspect
import enum
import random
from gameconst import *

UINT32_MAX = pow(2, 32) - 1


PacketType = enum.enum("PacketType",
    LOBBY = 1,
    CREATE_PARTY = 15,

    PARTY_STATUS = 21,
    INIT = 32,

    ACTION = 42
)


class PartyInfo(object):
    """Represents a pending party, waiting for players"""
    SIZE = struct.calcsize("<IBBBBHII")
    
    def __init__(self, idp, ip, port, n_players, max_players):
        self.id = idp
        self.ip = ip
        self.port = port
        self.n_players = n_players
Example #40
0
#encoding: utf-8
#!/usr/bin/python

import time
import logging
import os
import sys
from enum import enum

__LOG_TYPE = enum(INFO='Info', WARN='Warning', ERR='Error')

def __write_log(content,log_type, module,func):
    cur_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    template="""
=========================================
%s %s:%s--%s
%s
=========================================

"""
    logger=logging.getLogger()  
    filename = time.strftime('%Y-%m-%d',time.localtime(time.time()))  
    
    abs_path=os.path.abspath(sys.argv[0])

    abs_path=os.path.dirname(abs_path)

    handler=logging.FileHandler("%s/log/%s_%s_%s.log"%(abs_path,module,filename,log_type))  
    logger.addHandler(handler)  
    logger.setLevel(logging.NOTSET)  
    logger.info(template%(cur_time,log_type,module,func,content))  
FISHING_STATE = enum(

    "FISHING_STATE",

    # La couleur cyan n'est pas dominante.
    # On vient de capturer ou de rater un triangle, la zone de jeu
    # est donc en train de s'illuminer en vert ou en rouge.
    "HIGHLIGHTED",

    # Le triangle est passé sur la marque rouge, on l'a détecté,
    # et on a envoyé le signal.
    # On ne renvoie pas d'autre signal juste après, sinon ça risque de faire
    # n'importe quoi.
    # Il faut attendre une surbrillance, un déplacement de la marque rouge et
    # l'apparition d'un nouveau triangle.
    "SIGNAL_SENT",

    # La marque rouge s'est réactualisée. On attend le triangle.
    # Soit il est pas là du tout, soit il est là, mais encore loin.
    "WAIT_FISH",

    # Le triangle est très proche. Il faut faire des screen shot fréquents,
    # afin de détecter le bon moment où le triangle passe sur la marque rouge.
    "FISH_NEAR",

    # Le triangle est pil poil sur la marque rouge. Il faut envoyer le signal.
    "SEND_SIGNAL",

    # La zone critique de perfect catch n'a pas été trouvée à l'écran,
    # alors qu'on aurait dû, car un triangle est présent.
    "CRITICAL_ZONE_NOT_FOUND",
)
import pickle
import traceback

from commons import Frame, Size, Color, Image
from detectors import FaceDetector

def pack(o):
    return pickle.dumps(o)

def unpack(s):
    return pickle.loads(s)


OPENCV_HAAR = "/usr/share/opencv/haarcascades"

Colors = enum(RED = (255, 0, 0), GREEN = (0, 0, 255), BLUE = (0, 255, 0), YELLOW = (255, 255, 0), WHITE = (255, 255, 255))
Haar = enum(FRONTAL_FACE = OPENCV_HAAR + "/haarcascade_frontalface_alt.xml", EYE = OPENCV_HAAR + "/haarcascade_eye.xml", MOUTH = OPENCV_HAAR + "/haarcascade_mcs_mouth.xml", NOSE = OPENCV_HAAR + "/haarcascade_mcs_nose.xml", BODY = OPENCV_HAAR + "/haarcascade_fullbody.xml")

Lbp = enum(FRONTAL_FACE = "/usr/share/opencv/lbpcascades/lbpcascade_frontalface.xml", PROFILE_FACE = "/usr/share/opencv/lbpcascades/lbpcascade_profileface.xml")

VIDEO = "Temoin.mp4"
#VIDEO = "palmashow.flv"

FACE_TRACKER = None
SKIPPED_FRAMES = 2

def write_text(frame, text, coordinate, color):
    cv2.putText(frame.image.array, text, coordinate, cv2.FONT_HERSHEY_SIMPLEX, 1, color, thickness = 2)
    #return frame

def read_frames_target(input_queue, output_queue, arguments):
Example #43
0
import enum

TransactionOutcome = enum.enum(
  "MONEY_OUT",
  "MONEY_IN",
  "NEUTRAL")
# Enumeration for molecules.
#
# NEUROTRANSMITTERS:
#     Gluatamate: excitatory
#     GABA: inhibitory

from enum import enum
from math import exp

#################
"""  ENZYMES  """
#################

Enzymes = enum(
    GLUTAMATE = 0,
    GABA      = 1
)


#################
""" MOLECULES """
#################

class Molecule:
    def __init__(self, name, mol_id, enzyme_id, metab_rate):
        """
        Molecules have a |name|, a unique identifier, a corresponding enzyme,
            and a rate of metabolism by that enzyme.
        """
        self.name = name
        self.mol_id = mol_id
Example #45
0
def make_index(conn, shard, idx='company'):
    task = 'index'
    count_for_checkpoint_pid = 20

    if get_finished(conn, task, shard):
        print 'Task %s at Shard %d finished.' % (task, shard)
        return

    for loop_count, pid in enumerate(enum(conn, task, shard)):
        # remember where we are, so we can resume
        # this pid will be retried when resume
        print 'indexing %s...' % (pid,)
        if (loop_count+1) % count_for_checkpoint_pid == 0:
            set_last_pid(conn, task, shard, pid)

        profile_idx = r.table('profile_index').get(pid).run(conn)
        if not profile_idx:
            r.table('profile_index').insert({'pid':pid, 'indices':[]}).run(conn)
            profile_idx = r.table('profile_index').get(pid).run(conn)

        indices = profile_idx['indices']
        if idx in indices:
            print '%s indexed.' % (pid,)
            # this means this pid has been indexed before
            continue

        profile = r.table('profile').get(pid).run(conn)
        if not profile:
            print '%s not existed.' % (pid,)
            continue
        print profile

        positions = profile.get('positions')
        if not positions:
            continue
        entry_or_list = map(lambda x:x.get('org'), positions)
        if not any(entry_or_list):
            continue
        if not isinstance(entry_or_list, list):
            entry_or_list = [entry_or_list]
        primary_key = idx[0]+'id'
        print entry_or_list
        for entry in entry_or_list:
            if not entry:
                continue
            pids = r.table(idx).get(entry).run(conn)
            if not pids:
                pids = []
                r.table(idx).insert({primary_key: entry, 'pids':pids}).run(conn)
            else:
                pids = pids.get('pids', [])
            print pids
            if pid in pids:
                # this means this pid's index has been processed before
                continue
            print (entry, pid)
            r.table(idx).get(entry).update({'pids': r.row['pids'].append(pid)}).run(conn)
        # tell indexer that we're done
        r.table('profile_index').get(pid).update({'indices': r.row['indices'].append(idx)}).run(conn)

    set_finished(conn, task, shard)
    print 'Task %s at Shard %d finished.' % (task, shard)
Example #46
0
#!/bin/env python2

from enum import enum
import cv2
from cv2 import cv
from commons import Rectangle, Coordinate, Size

OPENCV_HAAR = "/usr/share/opencv/haarcascades"

Cascades = enum(
    FRONTAL_FACE = OPENCV_HAAR + "/haarcascade_frontalface_alt.xml", 
    EYE = OPENCV_HAAR + "/haarcascade_eye.xml", 
    MOUTH = OPENCV_HAAR + "/haarcascade_mcs_mouth.xml", 
    NOSE = OPENCV_HAAR + "/haarcascade_mcs_nose.xml", 
    BODY = OPENCV_HAAR + "/haarcascade_fullbody.xml"
)


class FaceDetector(object):

    def __init__(self, image):
        self.image = image

    @staticmethod
    def for_image(image):
        return FaceDetector(image)
    
    def detect_faces(self, cascade = Cascades.FRONTAL_FACE):
        array = cv2.cvtColor(self.image.array, cv.CV_RGB2GRAY)
        array = cv2.equalizeHist(array)
        cascade_classifier = cv2.CascadeClassifier(cascade)
Example #47
0
from enum import enum
from pluralize import pluralize
import pymysql

SQL_OPERATION = enum("SQL_SELECT", "SQL_UPDATE", "SQL_DELETE", "SQL_INSERT", "SQL_NULL")
BOOL_OPERATION = enum("OP_AND", "OP_OR", "OP_NULL")
GROUP_OPERATION = enum("LEFT_PARAN", "RIGHT_PARAN", "NULL_PARAM")

class Model(object):

    _has_many = []
    _has_one = []
    _related = []
    _related_field = []

    _operation = SQL_OPERATION.SQL_NULL


    class condition:
        operation = BOOL_OPERATION.OP_NULL
        next_cond = None
        group = False
        clause = ""
        def __init__(self, op, clause, group=GROUP_OPERATION.NULL_PARAM):
            self.operation = op
            self.clause = clause
            self.group = group
            self.clause = clause


Example #48
0
#! /usr/bin/env python

''' ------------------------|  Python SOURCE FILE  |------------------------

The Description of this file.

@copyright: Copyright (c) by Kodiak Data, Inc. All rights reserved.
'''

from enum import enum

RC = enum('OK', 'ERROR', 'TIMEOUT', 'WARNING', 'MISMATCH', 'NOT_YET', 'CONTINUE', 'NOT_FOUND')


class RcMsg(object):
    ''' Return code and its message '''

    def __init__(self, rc = RC.OK, msg = None):
        self.rc = rc
        self.msg = msg

    def setRC(self, rc, msg=None):
        self.rc = rc
        self.msg = msg

    def __str__(self):
        if self.msg and self.msg != "":
            return "%s-'%s'" % (self.rc, self.msg)
        else:
            return self.rc.__repr__()
Example #49
0
from enum import enum
import json

Types = enum('NUMERICAL', 'CATEGORICAL_BINARY', 'CATEGORICAL_ORDERED',
             'CATEGORICAL_UNORDERED')


class Column(object):
    def __init__(self, attribute=None, header='', type=None, categories=None):
        self.ATTRIBUTE = attribute
        self.HEADER = header
        self.TYPE = type
        self.CATEGORIES = categories


class Metadata(object):
    def __init__(self):
        metadata = json.load(open('metadata.json', 'r'))
        self.NAME = metadata['NAME']
        self.LOCATION = metadata['LOCATION']
        self.IS_INDEXED = metadata['IS_INDEXED']
        self.IS_LABELED = metadata['IS_LABELED']
        self.COLUMNS = []
        for column in metadata['COLUMNS']:
            self.COLUMNS.append(
                Column(attribute=column['attribute'],
                       header=column['header'],
                       type=getattr(Types, column['type']),
                       categories=column['categories']))
Example #50
0
from enum import enum

message_types = enum('N_CONNECT', 'N_SERVERINIT', 'N_WELCOME', 'N_CLIENTINIT', 'N_POS', 'N_SPHY', 'N_TEXT', 'N_COMMAND', 'N_ANNOUNCE', 'N_DISCONNECT',
                     'N_SHOOT', 'N_DESTROY', 'N_STICKY', 'N_SUICIDE', 'N_DIED', 'N_POINTS', 'N_DAMAGE', 'N_SHOTFX',
                     'N_LOADW', 'N_TRYSPAWN', 'N_SPAWNSTATE', 'N_SPAWN', 'N_DROP', 'N_WSELECT',
                     'N_MAPCHANGE', 'N_MAPVOTE', 'N_CLEARVOTE', 'N_CHECKPOINT', 'N_ITEMSPAWN', 'N_ITEMUSE', 'N_TRIGGER', 'N_EXECLINK',
                     'N_PING', 'N_PONG', 'N_CLIENTPING', 'N_TICK', 'N_NEWGAME', 'N_ITEMACC', 'N_SERVMSG', 'N_GAMEINFO', 'N_RESUME',
                     'N_EDITMODE', 'N_EDITENT', 'N_EDITLINK', 'N_EDITVAR', 'N_EDITF', 'N_EDITT', 'N_EDITM', 'N_FLIP', 'N_COPY', 'N_PASTE', 'N_ROTATE', 'N_REPLACE', 'N_DELCUBE', 'N_REMIP', 'N_CLIPBOARD', 'N_NEWMAP',
                     'N_GETMAP', 'N_SENDMAP', 'N_FAILMAP', 'N_SENDMAPFILE',
                     'N_MASTERMODE', 'N_ADDCONTROL', 'N_CLRCONTROL', 'N_CURRENTPRIV', 'N_SPECTATOR', 'N_WAITING', 'N_SETPRIV', 'N_SETTEAM',
                     'N_SETUPAFFIN', 'N_INFOAFFIN', 'N_MOVEAFFIN',
                     'N_TAKEAFFIN', 'N_RETURNAFFIN', 'N_RESETAFFIN', 'N_DROPAFFIN', 'N_SCOREAFFIN', 'N_INITAFFIN', 'N_SCORE',
                     'N_LISTDEMOS', 'N_SENDDEMOLIST', 'N_GETDEMO', 'N_SENDDEMO',
                     'N_DEMOPLAYBACK', 'N_RECORDDEMO', 'N_STOPDEMO', 'N_CLEARDEMOS',
                     'N_CLIENT', 'N_RELOAD', 'N_REGEN',
                     'N_ADDBOT', 'N_DELBOT', 'N_INITAI',
                     'N_MAPCRC', 'N_CHECKMAPS',
                     'N_SETPLAYERINFO', 'N_SWITCHTEAM',
                     'N_AUTHTRY', 'N_AUTHCHAL', 'N_AUTHANS',
                     'NUMMSG')
            
W_MAX = 11
         
var_types = enum('ID_VAR', 'ID_FVAR', 'ID_SVAR', 'ID_COMMAND', 'ID_ALIAS', 'ID_LOCAL')
                     
physics_events = enum('SPHY_NONE', 'SPHY_JUMP', 'SPHY_BOOST', 'SPHY_DASH', 'SPHY_MELEE', 'SPHY_KICK', 'SPHY_VAULT', 'SPHY_SKATE', 'SPHY_POWER', 'SPHY_EXTINGUISH', 'SPHY_BUFF', 'SPHY_MAX')

game_modes = enum('G_DEMO', 'G_EDITMODE', 'G_DEATHMATCH', 'G_CAPTURE', 'G_DEFEND', 'G_BOMBER', 'G_TRIAL', 'G_GAUNTLET', 'G_MAX')

def m_bomber(gamemode):
    print "Comparing gamemode({}) to G_BOMBER({})".format(gamemode, game_modes.G_BOMBER)
Example #51
0
class MavensMatePluginConnection(object):

    currently_supported_clients = ['SUBLIME_TEXT_2', 'SUBLIME_TEXT_3']
    PluginClients = enum(SUBLIME_TEXT_2='SUBLIME_TEXT_2',
                         SUBLIME_TEXT_3='SUBLIME_TEXT_3',
                         NOTEPAD_PLUS_PLUS='NOTEPAD_PLUS_PLUS',
                         TEXTMATE='TEXTMATE')

    def __init__(self, params={}, **kwargs):
        config.connection = self
        params = dict(params.items() + kwargs.items())

        self.operation = params.get('operation', None)
        self.platform = sys.platform
        self.plugin_client = params.get(
            'client',
            'SUBLIME_TEXT_2')  #=> "Sublime Text", "Notepad++", "TextMate"
        if self.plugin_client not in self.currently_supported_clients:
            self.plugin_client = 'SUBLIME_TEXT_2'

        self.plugin_client_version = params.get(
            'client_version', '2.0.1')  #=> "1.0", "1.1.1", "v1"
        self.plugin_client_settings = self.get_plugin_client_settings()
        self.workspace = self.get_workspace()
        self.project_name = params.get('project_name', None)

        self.project_location = None
        if self.project_name != None:
            self.project_location = os.path.join(self.workspace,
                                                 self.project_name)
        self.project_id = params.get('project_id', None)
        self.project = None
        self.sfdc_api_version = self.get_sfdc_api_version()
        self.ui = params.get(
            'ui', False
        )  #=> whether this connection was created for the purposes of generating a UI
        self.chrome = self.get_chrome()
        self.sublime = self.get_sublime()

        if 'wsdl_path' in params:
            mm_util.WSDL_PATH = params.get('wsdl_path')

        self.setup_logging()

        if self.sfdc_api_version != None:
            mm_util.SFDC_API_VERSION = self.sfdc_api_version  #setting api version based on plugin settings

        if self.operation != 'new_project' and self.operation != 'upgrade_project' and self.operation != 'new_project_from_existing_directory' and self.project_location != None:
            if not os.path.exists(os.path.join(self.project_location)):
                raise MMException('Could not find project in workspace: ' +
                                  self.workspace)
            if not os.path.exists(
                    os.path.join(self.project_location, "config",
                                 ".settings")):
                raise MMException(
                    'This does not seem to be a valid MavensMate project, missing config/.settings'
                )
            if not os.path.exists(
                    os.path.join(self.project_location, "src", "package.xml")):
                raise MMException(
                    'This does not seem to be a valid MavensMate project, missing package.xml'
                )

        if self.project_name != None and self.project_name != '' and not os.path.exists(
                self.project_location
        ) and self.operation != 'new_project_from_existing_directory' and self.operation != 'new_project':
            raise MMException('The project could not be found')
        elif self.project_name != None and self.project_name != '' and os.path.exists(
                self.workspace + "/" + self.project_name
        ) and self.operation != 'new_project_from_existing_directory':
            params['location'] = self.project_location
            params['ui'] = self.ui
            self.project = MavensMateProject(params)

    def setup_logging(self):
        if self.get_log_level() != None:
            if self.get_log_location() != None:
                try:
                    config.logger.handlers = []
                    config.suds_logger.handlers = []
                    handler = logging.FileHandler(self.get_log_location() +
                                                  "/mm.log")
                    config.logger.addHandler(handler)
                    config.suds_logger.addHandler(handler)
                except:
                    pass
            log_level = self.get_log_level()
            if log_level == 'CRITICAL':
                config.logger.setLevel(logging.CRITICAL)
                config.suds_logger.setLevel(logging.CRITICAL)
            elif log_level == 'ERROR':
                config.logger.setLevel(logging.ERROR)
                config.suds_logger.setLevel(logging.ERROR)
            elif log_level == 'WARNING':
                config.logger.setLevel(logging.WARNING)
                config.suds_logger.setLevel(logging.WARNING)
            elif log_level == 'DEBUG':
                config.logger.setLevel(logging.DEBUG)
                config.suds_logger.setLevel(logging.DEBUG)
            elif log_level == 'INFO':
                config.logger.setLevel(logging.INFO)
                config.suds_logger.setLevel(logging.INFO)

    #returns the workspace for the current connection (/Users/username/Workspaces/MavensMate)
    def get_workspace(self):
        mm_workspace_setting = self.get_plugin_client_setting('mm_workspace')
        if mm_workspace_setting == None or mm_workspace_setting == '':
            raise MMException(
                "Please set mm_workspace to the location where you'd like your mavensmate projects to reside"
            )
        elif not os.path.exists(mm_workspace_setting):
            try:
                os.makedirs(mm_workspace_setting)
            except:
                raise MMException("Unable to create mm_workspace location")
        return self.get_plugin_client_setting('mm_workspace')

    def get_chrome(self):
        return self.plugin_client_settings['user']['mm_chrome']

    def get_sublime(self):
        return self.plugin_client_settings['user']['mm_sublime']

    #returns the MavensMate settings as a dict for the current plugin
    def get_plugin_client_settings(self):
        user_path = self.get_plugin_settings_path("User")
        def_path = self.get_plugin_settings_path("MavensMate")

        settings = {}
        if not user_path == None:
            try:
                settings['user'] = mm_util.parse_json_from_file(user_path)
            except:
                config.logger.debug('User settings could not be loaded')
        if not def_path == None:
            try:
                settings['default'] = mm_util.parse_json_from_file(def_path)
            except:
                raise MMException(
                    'Could not load default MavensMate settings.')
        return settings

    def get_plugin_settings_path(self,
                                 type="User",
                                 obj="mavensmate.sublime-settings"):
        if self.plugin_client == self.PluginClients.SUBLIME_TEXT_3:
            sublime_ver = "sublime-text-3"
        elif self.plugin_client == self.PluginClients.SUBLIME_TEXT_2:
            sublime_ver = "sublime-text-2"
        else:
            return None

        if self.platform == 'darwin':
            return os.path.expanduser(
                '~/Library/Application Support/{0}/Packages/{1}/{2}'.format(
                    sublime_ver, type, obj))
        elif self.platform == 'win32' or self.platform == 'cygwin':
            return path.join(environ['APPDATA'], sublime_ver, 'Packages',
                             'MavensMate') + obj
        elif self.platform == 'linux2':
            return os.path.expanduser('~/.config/{0}/Packages/{1}/{2}'.format(
                sublime_ver, type, obj))
        else:
            return None

    def get_plugin_client_setting(self, key, default=None):
        if self.plugin_client_settings != None:
            if 'user' in self.plugin_client_settings and key in self.plugin_client_settings[
                    "user"]:
                return self.plugin_client_settings["user"][key]
            if 'default' in self.plugin_client_settings and key in self.plugin_client_settings[
                    "default"]:
                return self.plugin_client_settings["default"][key]
        return default

    #retrieves metadata from server, creates local project
    def new_project(self, params, **kwargs):
        try:
            if 'username' not in params or params['username'] == '':
                return mm_util.generate_error_response(
                    'Please specify a username')
            if 'password' not in params or params['password'] == '':
                return mm_util.generate_error_response(
                    'Please specify a password')
            if 'project_name' not in params or params['project_name'] == '':
                return mm_util.generate_error_response(
                    'Please specify a project name')

            if ('action' in kwargs
                    and kwargs['action'] == 'new') or 'action' not in kwargs:
                if 'package' not in params or params['package'] == []:
                    params['package'] = {
                        'ApexClass': '*',
                        'ApexComponent': '*',
                        'ApexPage': '*',
                        'ApexTrigger': '*',
                        'StaticResource': '*'
                    }
                self.project = MavensMateProject(params)
                result = self.project.retrieve_and_write_to_disk()
            elif 'action' in kwargs and kwargs['action'] == 'existing':
                self.project = MavensMateProject(params)
                result = self.project.retrieve_and_write_to_disk('existing')

            if json.loads(result)['success'] == True:
                if self.platform == 'linux2':
                    os.system("'" + self.sublime + "' --project '{0}'".format(
                        self.project.location + "/" +
                        self.project.project_name + ".sublime-project"))
                elif self.platform == 'darwin':
                    if self.plugin_client == self.PluginClients.SUBLIME_TEXT_2:
                        os.system(
                            "'/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl' --project '{0}'"
                            .format(self.project.location + "/" +
                                    self.project.project_name +
                                    ".sublime-project"))
                    elif self.plugin_client == self.PluginClients.SUBLIME_TEXT_3:
                        os.system(
                            "'/Applications/Sublime Text 3.app/Contents/SharedSupport/bin/subl' --project '{0}'"
                            .format(self.project.location + "/" +
                                    self.project.project_name +
                                    ".sublime-project"))

            return result
        except BaseException, e:
            return mm_util.generate_error_response(e.message)
Example #52
0
import pygame
from pygame.locals import KEYUP, KEYDOWN
from pygame import Vector2

from lumdareman import game
from lumdareman.data import *

#TURN_SLACK = TILE_SIDE / 5
TURN_SLACK = 2
START_LIFES = 4
START_BOMBS = 5
START_POWER = 4
START_SPEED = 4 * TILE_SIDE / 1000  # tile/ms

CTRL = enum('CTRL', ('RIGHT', 'DOWN', 'LEFT', 'UP', 'BOMB'))
AXIS = enum('AXIS', ('HORI', 'VERT'))


class make_player(pygame.sprite.DirtySprite):
    def __init__(self, pos_tile, ori):
        super().__init__()

        # rendering state
        image = SHEET[9]
        self._images = [
            pygame.transform.flip(image, True, False),
            pygame.transform.rotate(image, 90), image,
            pygame.transform.rotate(image, -90)
        ]
        self.image = self._images[ori]