Example #1
0
class Reporter:
	"""
	columns are implemented by ReportResult and exposed as attributes
	"""
	default_columns = ['recordID', 'collection', 'title', 'authors', 'pubName']
	searcher_class = ReportSearcher
	verbose = 0
	
	def __init__ (self, propsFile):
		self.props = Properties (propsFile)
		if self.props.hasProperty ('report.columns'):
			self.columns = map (lambda x:x.strip(), self.props.getProperty('report.columns').split(','))
			if self.verbose:
				print 'using CUSTOM COLUMNS (%s)' % self.columns
		else:
			if self.verbose:
				print 'using DEFAULT COLUMNS'
			self.columns = self.default_columns
		self.results = self.searcher_class(propsFile)
		
		self.resultClass = self.results.searchResult_constructor
		try:
			self.verifyColumns()
		except Exception, msg:
			print "could not verify columns: %s" % msg
			# print "first result:", self.results[1]
			sys.exit()
Example #2
0
 def __init__(self,
              type=None,
              stationName=None,
              snowQty=None,
              coordinates=None,
              date=None):
     self.geometry = Geometry(
         type,
         coordinates)  # type is string, coordinates are array [lat, lon]
     self.properties = Properties(
         stationName, snowQty,
         date)  # sName is string, snowQty is float, date is date.
Example #3
0
 def test(self):
     props = Properties.getInstance()
     host2 = props.get('QA', 'host')
     print(host2)
     host1 = props.get('DEV', 'host')
     print(host1)
     self.assertEqual(host1, host2)
Example #4
0
 def init_objects(self):
     with self.canvas:
         self.stones = []
         self.rubies = []
         self.player = Player(self.width / 2)
         self.properties = Properties()
         self.score = Score(self.height)
Example #5
0
    def performSearch(self, criteria):

        #initial configuration
        logger = Logger.getInstance()
        logger.logDebug('performing search with criteria: ' + criteria)
        props = Properties.getInstance()
        index_path = props.get(self.__environment, 'index_path')

        # define schema and get a writer for it
        ix = open_dir(index_path)

        # perform search
        searchResults = []
        i = 0
        with ix.searcher() as searcher:
            query = QueryParser("content", ix.schema).parse(criteria)
            results = searcher.search(query, limit=20)
            for result in results:

                order = result['orderno']
                path = result['path']
                title = result['title']
                searchResult = SearchResult(title, path, order, criteria)
                searchResults.append(searchResult)
                i = i + 1

        logger.logDebug("results found: " + str(i))
        return searchResults
Example #6
0
class ReportSearcher (RepositorySearcher):
	"""
	reads properties file to parameterize search - see ReportSearcher.get_params
	
	"""

	numToFetch = 20
	batchSize = 400
	searchResult_constructor = ReportResult
	filter_predicate = None
	verbose = 0
	
	def __init__ (self, propsFile):
		self.props = Properties (propsFile)
		baseUrl = self.props.getProperty("baseUrl")
		RepositorySearcher.__init__(self)
			
	def get_params (self, collection, xmlFormat):
		"""
		use params defined in properties file to query the search service
		"""
		
		parms_dict = {
			"verb": "Search",
			"xmlFormat": self.props.getProperty('xmlFormat'),
			"ky": self.props.getProperty('collection'),
			'q' : self.props.getProperty('q'),
			'dcsStatus' : self.props.getProperty('dcsStatus'),
			"storedContent":['dcsstatus', 'dcsstatusNote', 'dcsisValid','osmDatePublished']
			}
			
		# process params dict from properties
		propertyParams = self.props.params
		if propertyParams:
			if self.verbose:
				print "\nProperty Params"
				for parm in propertyParams:
					print "- %s - %s" % (parm, propertyParams[parm])
			parms_dict.update (propertyParams)
			
		if self.verbose:
			print "\nQuery Params"
			for parm in parms_dict:
				print "- %s - %s" % (parm, parms_dict[parm])
			
		return parms_dict
Example #7
0
def copy_tree(props, src, dest):
    name_pattern = re.compile(".+\\.properties")

    if not path.exists(dest):
        os.mkdir(dest, 0775)

    for root, subdirs, files in os.walk(src):
        dest_dir = "%s%s" % (dest, root[len(src):])

        for name in subdirs:
            dest_subdir = path.join(dest_dir, name)

            if not path.exists(dest_subdir):
                os.mkdir(dest_subdir, 0775)

        for name in files:
            src_name = path.join(root, name)
            dest_name = path.join(dest_dir, name)

            if path.islink(src_name):
                link_target = os.readlink(src_name)

                os.symlink(link_target, dest_name)

            elif path.exists(dest_name):
                if name_pattern.match(name):
                    print "merging property file %s" % (dest_name)

                    src_props = Properties(src_name)
                    dest_props = Properties(dest_name)

                    for key, value in src_props.iteritems():
                        dest_props[key] = value

                    filter_props(props, dest_props, dest_name)

                else:
                    print "overwriting %s" % (dest_name)

                    filter_file(props, src_name, dest_name)

            else:
                filter_file(props, src_name, dest_name)

            shutil.copystat(src, dest)
Example #8
0
  def __init__(self, name, dead=False, status=None, gender='m', **properties):
    self.properties = Properties(properties)
    self.name = name
    self.dead = dead
    self.status = status  # TODO: shouldn't "dead" be a status?
    self.gender = gender
    self.pronoun = Pronoun.PRONOUN[self.gender]

    self.CHARACTERS.add(self)
Example #9
0
def filter_props(props, src, dest):
    self_ref_pattern = re.compile("^([a-zA-Z0-9._\\-]+)\\s*=.*@\\{\\1\\}.*$",
                                  re.MULTILINE)

    while True:
        src_text = StringIO.StringIO()

        try:
            src.save(src_text)

            __filter(props, src_text.getvalue(), dest)

        finally:
            src_text.close()

        dest_props = Properties(dest)
        dest_text = StringIO.StringIO()

        try:
            dest_props.save(dest_text)

            match = self_ref_pattern.search(dest_text.getvalue())

            if match is not None:
                raise BuildError(
                    "self-referencing value found for property %s" %
                    (match.group(1)))

        finally:
            dest_text.close()

        modified = False

        for key, value in src.iteritems():
            if dest_props[key] != value:
                modified = True

                break

        if not modified:
            break

        src = dest_props
Example #10
0
	def __init__ (self, propsFile):
		self.props = Properties (propsFile)
		if self.props.hasProperty ('report.columns'):
			self.columns = map (lambda x:x.strip(), self.props.getProperty('report.columns').split(','))
			if self.verbose:
				print 'using CUSTOM COLUMNS (%s)' % self.columns
		else:
			if self.verbose:
				print 'using DEFAULT COLUMNS'
			self.columns = self.default_columns
		self.results = self.searcher_class(propsFile)
		
		self.resultClass = self.results.searchResult_constructor
		try:
			self.verifyColumns()
		except Exception, msg:
			print "could not verify columns: %s" % msg
			# print "first result:", self.results[1]
			sys.exit()
Example #11
0
class Snow:
    def __init__(self,
                 type=None,
                 stationName=None,
                 snowQty=None,
                 coordinates=None,
                 date=None):
        self.geometry = Geometry(
            type,
            coordinates)  # type is string, coordinates are array [lat, lon]
        self.properties = Properties(
            stationName, snowQty,
            date)  # sName is string, snowQty is float, date is date.

    def jdefault(self):
        return self.geometry.to_json(), self.properties.to_json()

    def merge_two_dicts(self, x, y):
        """Given two dicts, merge them into a new dict as a shallow copy."""
        z = x.copy()
        z.update(y)
        return z

    def printSnow(self):
        print("type: " + self.geometry.getType() + "name: " +
              self.properties.getName() + " snowQty: " +
              str(self.properties.getSnowQty()) + " date: " +
              str(self.properties.getDate()) + " geometry: " +
              str(self.geometry.getCoordinates()))

    def getGeometry(self):
        return self.geometry

    def getProperties(self):
        return self.properties

    def setGeometry(self, value):
        self.geometry = value

    def setProperties(self, value):
        self.properties = value
Example #12
0
    def run(self):

        logger = Logger.getInstance()
        logger.logInfo('---------------------------------------------------')
        logger.logInfo('----------- Starting indexing process      --------')

        props = Properties.getInstance()
        files_path = props.get(self.__environment, 'files_path')
        index_path = props.get(self.__environment, 'index_path')

        logger.logInfo('-- files path: ' + files_path)
        logger.logInfo('----------------------------------------------------')

        #discover files, specify extensions
        filesList = None
        files = FileDiscover()
        files.add_extension('docx')
        files.add_extension('txt')
        files.add_extension('pdf')
        files.add_localtion(files_path)
        filesList = files.explore()

        # create an index subdir in case it not exists
        if not os.path.exists(index_path):
            os.mkdir(index_path)

        # define schema and get a writer for it
        schema = Schema(title=TEXT(stored=True),
                        path=ID(stored=True),
                        orderno=ID(stored=True),
                        content=TEXT)
        ix = create_in(index_path, schema)

        # index the content
        for curfile in filesList:
            writer = ix.writer()
            tokens = curfile.split('/')
            filetitle = tokens[len(tokens) - 1]
            logger.logInfo('Indexing file: ' + filetitle)
            reader = ParserProvider.getParser(filetitle)
            filepointer = reader.openFile(curfile)
            fr = reader.readFile(filepointer)
            i = 0
            while i < fr:
                text = reader.readNextSegment(filepointer)
                if (text != ''):
                    writer.add_document(title=filetitle,
                                        path=curfile,
                                        orderno=str(i),
                                        content=text)
                i = i + 1
            reader.closeFile(filepointer)
            writer.commit()
Example #13
0
def calculateProperties(timestepData, atoms):

    properties = Properties()

    timestepData["molecule"] = {}
    timestepData["molecule"]["moleculeList"] = properties.findStructure(
        atoms, timestepData["position"], consts.cutoff)

    #init data lists in timestep data
    timestepData["molecule"]["RKE"] = []
    timestepData["molecule"]["KE"] = []
    timestepData["molecule"]["TKE"] = []
    timestepData["molecule"]["VelocityCOM"] = []
    timestepData["molecule"]["KECOM"] = []

    for molecule in timestepData["molecule"]["moleculeList"]:

        #    timestepData["molecule"]["RKE"].append(properties.RKE(molecule,atoms,timestepData["position"],timestepData["velocity"]))

        timestepData["molecule"]["TKE"].append(
            properties.TKE(molecule, atoms, timestepData["velocity"]))

        Vcom = properties.Vcom(molecule, atoms, timestepData["velocity"])

        timestepData["molecule"]["VelocityCOM"].append(Vcom)

        timestepData["molecule"]["KECOM"].append(
            properties.KEcom(molecule, atoms, Vcom))

    return timestepData
Example #14
0
    def test(self, spec_filename):
        function_map = {
            "TEXT": str,
            "INTEGER": int,
            "BOOLEAN": int,
            "DATE": str
        }

        properties = Properties.getProperties()
        db = Db(properties)

        data_files = os.listdir("data")

        file_map = {}
        for data_file in data_files:
            file_info = data_file.split("_")
            if not file_info[0] in file_map:
                file_map[file_info[0]] = []
            file_map[file_info[0]].append(data_file)

        with open("specs/" + spec_filename, "rt") as spec_file:
            filename_info = spec_filename.split(".")
            file = csv.reader(spec_file, delimiter=",")
            next(file)  # Skip first row
            columns = []
            for column in file:
                columns.append({
                    "name": column[0],
                    "width": int(column[1]),
                    "data_type": column[2]
                })
            if filename_info[0] in file_map:
                for data_filename in file_map[filename_info[0]]:
                    with open("data/" + data_filename, "rt") as data_file:
                        for line in data_file:
                            sql = "SELECT count(*) as total FROM {} WHERE ".format(
                                filename_info[0])
                            index = 0
                            fields = []
                            for column in columns:
                                fields.append(column["name"] + " = '" + str(
                                    function_map[column["data_type"]]
                                    (line[index:(index + column["width"])])) +
                                              "'")
                                index += column["width"]
                            sql += " AND ".join(fields)
                            row = db.select(sql)[0]
                            if row["total"] != 1:
                                raise Exception(
                                    "Line: {} was not inserted".format(
                                        line.strip()))
Example #15
0
	def test(self, spec_filename):
		function_map = {
			"TEXT": str,
			"INTEGER": int,
			"BOOLEAN": int,
			"DATE": str
		}

		properties = Properties.getProperties()
		db = Db(properties)

		data_files = os.listdir("data")

		file_map = {}
		for data_file in data_files:
			file_info = data_file.split("_")
			if not file_info[0] in file_map:
				file_map[file_info[0]] = []
			file_map[file_info[0]].append(data_file)

		with open("specs/" + spec_filename, "rt") as spec_file:
			filename_info = spec_filename.split(".")
			file = csv.reader(spec_file, delimiter=",")
			next(file) # Skip first row
			columns = []
			for column in file:
				columns.append({"name": column[0], "width": int(column[1]), "data_type": column[2]})
			if filename_info[0] in file_map:
				for data_filename in file_map[filename_info[0]]:
					with open("data/" + data_filename, "rt") as data_file:
						for line in data_file:
							sql = "SELECT count(*) as total FROM {} WHERE ".format(filename_info[0])
							index = 0
							fields = []
							for column in columns:
								fields.append(column["name"] + " = '" + str(function_map[column["data_type"]](line[index:(index + column["width"])])) + "'")
								index += column["width"]
							sql += " AND ".join(fields)
							row = db.select(sql)[0]
							if row["total"]	!= 1:
								raise Exception("Line: {} was not inserted".format(line.strip()))
Example #16
0
 def Classic(self,M):
     
     row_storage = []
     
     for row,conversion in zip(M,self.conversions):
         clean_row = np.unique(row[~np.isnan(row)])
         row_storage.append((clean_row,np.round(conversion/clean_row.shape[0],10)))
         
     row_data = pd.DataFrame(row_storage,columns=[CHANNEL_NAME,SHAPLEY_VALUE])
     row_agg = row_data.explode(CHANNEL_NAME).groupby([CHANNEL_NAME])[SHAPLEY_VALUE].sum()
     row_agg.index = row_agg.index.astype(int)
     
     shapley_Encoded = row_agg.to_dict()
     
     shapley_classic = DecodeDict(shapley_Encoded,self.channel_id_dict)
     
     Properties(self.data,shapley_classic).run() #Check Properties
     
     shapley_classic = pd.DataFrame(shapley_classic.items(),columns=[CHANNEL_NAME,SHAPLEY_VALUE])
      
     return shapley_classic
Example #17
0
    def create_object(self, x, y):
        """
        Метод создания объекта
        :param x: координата х
        :param y: координата y
        """
        frame = Frame(x, y, x, y)
        prop = Properties()
        prop.prop_group.list_prop.append(self.pen_props)
        prop.prop_group.list_prop.append(self.brush_prop)

        if self.object_type == "rect":
            rect = Rectangle(frame, prop)
            self.store.add(rect)

        elif self.object_type == "ellipse":
            ellipse = Ellipse(frame, prop)
            self.store.add(ellipse)

        elif self.object_type == "line":
            line = Line(frame, prop)
            self.store.add(line)
Example #18
0
	def __init__(self):
		self.Window = tkinter.Tk()
		self.Properties = Properties()
		self.setTitle('Bloc Note')
		self.setSize(self.Properties.x, self.Properties.y)
		self.Frame = tkinter.Frame(self.Window).pack(fill="x", padx=1, pady=1)
		self.TextScroll = tkinter.Scrollbar(self.Frame)
		self.Text = tkinter.Text(self.Frame, width=97, height=25, font=("Helvetica", self.Properties.TextSize, "bold"),
			selectbackground="gray",
			selectforeground="black",
			undo=True,
			yscrollcommand=self.TextScroll.set
		)
		self.TextScroll.config(command=self.Text.yview)
		self.Text.pack()
		self.Menu = tkinter.Menu(self.Window)
		self.Window.config(menu=self.Menu)
		self.Files = tkinter.Menu(self.Window, tearoff=False)
		self.Menu.add_cascade(label='File', menu=self.Files)
		self.Files.add_command(label='New File', command=self.newFile)
		self.Files.add_command(label='Open File', command=self.openFile)
		self.Files.add_command(label='Save File', command=self.saveFile)
		self.Files.add_command(label='Save As', command=self.saveAsFile)
		self.Files.add_command(label='Exit', command=self.Window.quit)
Example #19
0
    def read_properties(self):
        prop = Properties(
            os.path.join(os.path.abspath('.'), "config",
                         'config.properties')).get_properties()

        self.git_server_path = prop["GIT_SERVER"]
        self.sign_file = os.path.abspath(prop["STORE_FILE"])
        self.key_alias = prop["KEY_ALIAS"]
        self.store_password = prop["STORE_PASSWORD"]
        self.key_password = prop["KEY_PASSWORD"]
        self.use_resguard = prop["USE_RES_GUARD"] == "true"
        self.account360 = prop["360_ACCOUNT"]
        self.password360 = prop["360_PASSWORD"]
        self.use_tinker = prop["USE_TINKER"] == "true"
        self.module_app = prop["MODULE_APP"]
        self.jiagu_type = int(prop["JIAGU_TYPE"])
        self.market_tool_type = int(prop["MARKET_TOOL_TYPE"])
        self.ftpServer = prop["FTP_SERVER"]
        self.ftpPort = int(prop["FTP_PORT"])
        self.ftpAccount = prop["FTP_ACCOUNT"]
        self.ftpPassword = prop["FTP_PASSWORD"]
        self.ftpDir = prop["FTP_DIR"]
        self.tencent_cloud_api = prop["t_cloud_api"]
        self.tencent_cloud_secret = prop["t_cloud_secret"]
Example #20
0
    def __init__(self):
        if Logger.__instance == None:
            #get configuration
            props = Properties.getInstance()
            glevel = props.get(self.__environment, 'log_level')
            logpath = props.get(self.__environment, 'log_file')
            logOutput = props.get(self.__environment, 'log_output')
            lformat = '%(asctime)s - %(levelname)s - %(message)s'
            Logger.__instance = self
            logger = logging.getLogger()

            #file logger configuration
            logging.basicConfig(format=lformat, filename=logpath, level=glevel)

            #console logger config
            if (logOutput == '2'):
                ch = logging.StreamHandler()
                ch.setLevel(glevel)
                chformatter = logging.Formatter(lformat)
                ch.setFormatter(chformatter)
                logger.addHandler(ch)

            #asign instance
            Logger.__loggerUtil = logger
Example #21
0
class Character(object):
  """ base class for all characters in the game."""
  _DESCRIPTION_STRING = (
    'Name = {0.name}, '
    'Character Class = {1}, '
    'Status: {0.status}, '
    'Gender: {0.gender}, '
    'Properties: {0.properties}'
    )

  CHARACTERS = set()

  attack_succeeded_message = '{0.name} hit {1.name} for {damage} points.'
  attack_missed_message = '{0.name} attacked {1.name} - and missed!'
  opponent_died_message = '{0.name} killed {1.name}!'
  retreated_message = '{0.name} retreated...'
  defended_message = '{0.name} defended against attack!'

  def __init__(self, name, dead=False, status=None, gender='m', **properties):
    self.properties = Properties(properties)
    self.name = name
    self.dead = dead
    self.status = status  # TODO: shouldn't "dead" be a status?
    self.gender = gender
    self.pronoun = Pronoun.PRONOUN[self.gender]

    self.CHARACTERS.add(self)

  def prepare_for_turn(self):
    self.combat = UNPREPARED

  def select_action(self, friends, enemies):
    hp = self.properties.get('hit_points')
    if hp < self.properties('retreat_hit_points'):
      return self.retreat
    if hp < self.properties('defend_hit_points'):
      return self.defend
    return functools.partial(self.attack, random.choose(enemies))

  def initiative(self, action):
    return self.properties.get('initiative'), self.combat

  def clean_up_after_turn(self):
    return self.combat == Character.RETREAT

  def attack(self, opponent, messages):
    def messsage(msg, **kwds):
      messages.append(msg.format(self, opponent, **kwds))

    skill = self.properties.get('attack_skill', DEFAULT_ATTACK_SKILL)
    if skill >= random.randrange(D100):
      # Hit!
      max_damage = self.properties.get('attack_damage', DEFAULT_ATTACK_DAMAGE)
      damage = random.randint(1, max_damage)
      points_left = opponent.properties.increment('hit_points', -damage)
      message(self.attack_succeeded_message, damage=damage)
      if points_left <= 0:
        # Your opponent died.
        message(self.opponent_died_message)
        return [opponent]
    else:
      message(self.attack_missed_message)

  def retreat(self, messages):
    self.combat = RETREAT
    messages.append(self.retreated_message.format(self))

  def defend(self, messages):
    self.combat = DEFEND
    messages.append(self.defended_message.format(self))

  def __str__(self):
    return self._DESCRIPTION_STRING.format(self, self.__class__.__name__)

  def __repr__(self):
    return '%s(%s)' % (self.__class__.__name__, str(self))
	def generate_files(self):
		'''
		generate_files will do just that. We create several lists of 
		Necessary files, the ones we want to use and the ones we want
		to create.
		We send the HTML and Properties files in to be compared, and to 
		verify we have all the ID's in the Properties Files that aren't
		labeled "no translate".
		We also compare the Properties Files for the Languages to the 
		English Properties Files, in case something is missing, then
		we replace it.
		We take the Old Stuff, and concantinate the Old Properties 
		together, based on the HTML, and put all that into the NEW
		Properties Files.
		'''

		# Extract the first Properties File from the list, and get 2 things, Language Code (if any) and the Base Property File Name
		### Note, we also create the Default Property File Name (English) and the new Property File ".NEW" as well
		### Note, the main body of parsing code is also explained below
		for p_file in self.__prop_files:
			left_side, right_side = p_file.split('l10n/', 1)
			file_name, extension = right_side.split('.', 1)

			# Some of the Properties Files have odd names XXX_XXX_XXX_en.properties, so we have to parse that out...
			if "_" in file_name: 
				file_side, lang_code = file_name.split('_', 1)
				
				if "_" in lang_code:
					file_side, a_lang_code = lang_code.split('_', 1)
					lang_code = a_lang_code
					
					if "_" in lang_code:
						file_side, b_lang_code = lang_code.split('_', 1)
						lang_code = b_lang_code 
						
				lang_code = "_" + lang_code # This is the Language Code as found in the List, (_en is NOT in the list)
				
			else:
				lang_code = "_en"
			
			# We don't have _en in the list, so we only do this for any foreign language files
			if lang_code in self.__ignore:
				file_name = file_name[0:-3]
				default_property = left_side + "l10n/" + file_name + "." + extension
				temp = left_side + "l10n/" + file_name + lang_code + "." + extension + ".new"
				
			else: # This is for the English Property Files
				default_property = p_file
				temp = p_file + ".new"
		
			is_html = re.compile(r'\b' + file_name + '.htm') # The searcher for the currently needed HTML File
			is_ssi = re.compile(r'\b' + file_name + '.ssi') # The searcher for the currently needed SSI File
			
			# Take the first HTML file in the list and move forward
			for h_file in self.__html_files:
				
				# If the HTML File is the one for the Property File...
				if is_html.search(h_file) or is_ssi.search(h_file):
					props = Properties() # Initialize the language Properties Files via this program (creates a Dictionary)
					props.load(open(p_file))
					default_props = Properties() # Initialize the English Properties Files via this program (creates a Dictionary)
					
					try: # If the Default Properties Files does not exist, throw the error, but don't fail, continue
						default_props.load(open(default_property))
						
					except IOError:
						### Logging
						LOGGING = open('/home/sandbox/SCRIPT_RUN.LOG', 'a') #Log file location
						LOG_ME = "Missing the Default English property file:\t%s\n\n" % default_property
						print LOG_ME
						LOGGING.write(LOG_ME)
						LOGGING.close()
						continue

					MHP = My_Html_Parser(); # Initialize the HTML Parser to read the HTML
					MHP.my_init(props, temp, default_props) # Send in the Language Property File, the Temp File Name and Location and the English Property File
					read_html = open(h_file, "r") # Open the HTML File
					
					### Logging Info
					LOGGING = open('/home/sandbox/SCRIPT_RUN.LOG', 'a') #Log file location
					LOG_ME = "The current HTML File is:\n"
					print LOG_ME
					LOGGING.write(LOG_ME)
					LOG_ME = "\t\t" + h_file + "\n"
					print LOG_ME
					LOGGING.write(LOG_ME)
					LOG_ME = "The Default (English) Property File is:\n"
					print LOG_ME
					LOGGING.write(LOG_ME)
					LOG_ME = "\t\t" + default_property + "\n"
					print LOG_ME
					LOGGING.write(LOG_ME)
					LOG_ME = "The NEW Property File is:\n"
					print LOG_ME
					LOGGING.write(LOG_ME)
					LOG_ME = "\t\t" + temp + "\n\n"
					print LOG_ME
					LOGGING.write(LOG_ME)
					LOGGING.close()
					
					MHP.feed(read_html.read()) # Read the HTML File into the HTML Parser
					
					# Make the NEW (.new) Property File
					MHP.make_file()
					
					#MHP.close() # Keep things Tidy
					
				else:
					
					continue # Finish running the list
Example #23
0
class StartQT5(QMainWindow):

	global irc_Connection 
	#global server_OutputSorter
	global channelArray
	global channelWindow
	global _nick_
	global app

	const_NONE=0
	const_TILE=1
	const_CASCADE=2


	config=""
	_nick_=""
	_nick=""
	_version="0.5.0.2 ALPHA"
	statusWindow = ""
	_layout=const_NONE

	#PyQt5 Signals
	NickChange = QtCore.pyqtSignal(str)

	#Create and Empty array to hold the Channels in.
	channelArray=dict()


	def __init__(self,parent=None):
		global irc_Connection
		#global server_OutputSorter
		global channelWindow
		global _nick_

		#scan the plugins. 
		self.plugins=PluginArchitecture()

		QWidget.__init__(self,parent)
		self.ui = Ui_PyBirch()
		self.ui.setupUi(self)
		
		#Self is the main window.
		self.setWindowTitle("Py-Birch "+self._version)

		self.config = Properties()
		
	#	self.config = configparser.ConfigParser(allow_no_value=True)
	#	try:
	#		if os.path.isfile("py-birch.cfg"):
	#			self.config.read("py-birch.cfg")
	#	except:
	#		self.config.add_section("IRC_Server")
	#		self.config.set("IRC_Server", "Server", "irc.dal.net")
		
		Gui = self
		#QtCore.QObject.connect(irc_Connection,QtCore.SIGNAL("incomming"),self.update_editorWindow);
		
		self.irc_Connection = IrcConnection(self.config)
		self.server_OutputSorter = ServerOutputSorter(self.config,self.plugins)
		self.channelArray = dict()
		
		#channelWindow = Channel()

		#self.ui.mdiArea.addSubWindow(channelWindow)
		#channelWindow.show()

		layout = QGridLayout()
		
		self.statusWindow = Channel("Status", self.config,self.plugins, Channel.STATUS)
		#self.ui.Status.setLayout(layout)	
		self.ui.mdiArea.addSubWindow(self.statusWindow)
		
		#add a button to the button bar
		btn_Status = QtWidgets.QPushButton("Status")
		self.statusWindow.set_button(btn_Status)
		#btn_Status.resize(250, 250)
		button_bar_layout = self.ui.button_bar.layout()
		button_bar_layout.addWidget(btn_Status)
#		self.statusWindow.connect(btn_Status, QtCore.SIGNAL("clicked()"), self.statusWindow.button_click)
		btn_Status.clicked.connect(self.statusWindow.button_click)

		#Set Up Signals
		#self.setUpSignals()
	
		#self.ui.Status.setWindowTitle("Status")

		#self.ui.Status.show()
		#so who needs to know when a nickname is update.
		#PyQt4 Method
		#self.connect(self,QtCore.SIGNAL("NickChange"),self.nick_update)
		#self.connect(self,QtCore.SIGNAL("NickChange"),self.statusWindow.nick_update)
		#self.connect(self,QtCore.SIGNAL("NickChange"),self.irc_Connection.nick_update)

		self.NickChange.connect(self.nick_update)
		self.NickChange.connect(self.statusWindow.nick_update)
		self.NickChange.connect(self.irc_Connection.nick_update)

		#self.connect(self.statusWindow,QtCore.SIGNAL("UserInput"),self.send_to_server,2)
		self.statusWindow.UserInput.connect(self.send_to_server)

		#self.connect(self.irc_Connection,QtCore.SIGNAL("NickChange"), self.statusWindow.nick_update,2)
		self.irc_Connection.NickChange.connect(self.statusWindow.nick_update)

		#Qt::QueuedConnection = 2
		#self.connect(self.irc_Connection,QtCore.SIGNAL("incomming"),self.update_editorWindow, 2)
		self.irc_Connection.Incomming.connect(self.update_editorWindow)
		#self.connect(self.irc_Connection,QtCore.SIGNAL("Status"),self.update_statusWindow, 2)
		self.irc_Connection.Status.connect(self.update_statusWindow)
		#self.connect(self.irc_Connection,QtCore.SIGNAL("NickChange"), self.nick_update, 2)
		self.irc_Connection.NickChange.connect(self.nick_update)
		#self.connect(self.irc_Connection,QtCore.SIGNAL("ProcessEvents"),self.process_gui_events,2)
		self.irc_Connection.ProcessEvents.connect(self.process_gui_events)
		#self.connect(self.irc_Connection, QtCore.SIGNAL("StatusBar"), self.statusBar)
		self.irc_Connection.StatusBar.connect(self.statusBar)
		#self.connect(self.irc_Connection, QtCore.SIGNAL("Disconnect"),self.disconnect,2)
		self.irc_Connection.Disconnect.connect(self.disconnect)

		#self.irc_Connection.connect(self.irc_Connection, QtCore.SIGNAL("NickChange"), self.irc_Connection.nick_update)
		#irc_Connection.connect(irc_Connection, QtCore.SIGNAL("NickChange"), self.nick_update)
		self.irc_Connection.NickChange.connect(self.irc_Connection.nick_update)

		#self.connect(self.server_OutputSorter,QtCore.SIGNAL("join"),self.channel_join)
		self.server_OutputSorter.JOIN.connect(self.channel_join)

		#Part/Quit/Kick are all currently dealt with by the same method, but they are separated
		#In the Sorter for future-proofing (if neeeded) - done: Alpha 0.4.2.1
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("PART"), self.remove_nick)
		self.server_OutputSorter.PART.connect(self.remove_nick)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("QUIT"), self.remove_nick)
		self.server_OutputSorter.QUIT.connect(self.remove_nick)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("KICK"), self.remove_nick)
		self.server_OutputSorter.KICK.connect(self.remove_nick)

		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("NamesOnChannel"), self.channel_nicklist)
		self.server_OutputSorter.NamesOnChannel.connect(self.channel_nicklist)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("RemoveName"), self.remove_nick)
		self.server_OutputSorter.RemoveName.connect(self.remove_nick)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("nick_mode"), self.nick_mode_change)
		self.server_OutputSorter.Nick_Mode.connect(self.nick_mode_change)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("nicklist_update"), self.nicklist_update)
		self.server_OutputSorter.Nicklist_Update.connect(self.nicklist_update)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("ChannelTitle"),self.channel_title_update)
		self.server_OutputSorter.ChannelTitle.connect(self.channel_title_update)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("Notice"), self.statusBarNotice)
		self.server_OutputSorter.Notice.connect(self.statusBarNotice)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("StatusBar"), self.statusBar)
		self.server_OutputSorter.StatusBar.connect(self.statusBar)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("NickChange"), self.nick_update, 2)
		self.server_OutputSorter.NickChange.connect(self.nick_update)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("NewNick"),self.new_nick)
		self.server_OutputSorter.NewNick.connect(self.new_nick)

		#QtCore.QObject.connect(self.ui.button_Connect,QtCore.SIGNAL("clicked()"),self.connectToServer)
		self.ui.button_Connect.clicked.connect(self.connectToServer)
		#QtCore.QObject.connect(self.ui.button_Send,QtCore.SIGNAL("clicked()"),self.sendToServer)
		#self.ui.button_Send.clicked.connect(self.sendToServer)
		#QtCore.QObject.connect(self.ui.button_Disconnect,QtCore.SIGNAL("clicked()"),self.button_disconnect)
		self.ui.button_Disconnect.clicked.connect(self.button_disconnect)
		
		#QtCore.QObject.connect(self.ui.button_Tile, QtCore.SIGNAL("clicked()"), self.tileHorizontally)
		self.ui.button_Tile.clicked.connect(self.tileHorizontally)
		#QtCore.QObject.connect(self.ui.button_Cascade,  QtCore.SIGNAL("clicked()"), self.cascade)
		self.ui.button_Cascade.clicked.connect(self.cascade)
		#QtCore.QObject.connect(self.ui.button_Properties, QtCore.SIGNAL("clicked()"), self.show_properties)
		self.ui.button_Properties.clicked.connect(self.show_properties)


		#QtCore.QObject.connect(self.ui.actionProperties, QtCore.SIGNAL("triggered()"), self.show_properties)
		self.ui.actionProperties.triggered.connect(self.show_properties)
		#QtCore.QObject.connect(self.ui.actionConnect, QtCore.SIGNAL("triggered()"), self.connectToServer)
		self.ui.actionConnect.triggered.connect(self.connectToServer)
		#QtCore.QObject.connect(self.ui.actionDisconnect,  QtCore.SIGNAL("triggered()"), self.button_disconnect)
		self.ui.actionDisconnect.triggered.connect(self.button_disconnect)

		#QtCore.QObject.connect(self.ui.actionTile, QtCore.SIGNAL("triggered()"), self.tileHorizontally)
		self.ui.actionTile.triggered.connect(self.tileHorizontally)
		#QtCore.QObject.connect(self.ui.actionCascade, QtCore.SIGNAL("triggered()"), self.cascade)
		self.ui.actionCascade.triggered.connect(self.cascade)
		#QtCore.QObject.connect(self.ui.actionAbout_Py_Birch, QtCore.SIGNAL("triggered()"), self.show_about)
		self.ui.actionAbout_Py_Birch.triggered.connect(self.show_about)



		self.pluginsMenu=self.ui.menubar.addMenu("Plugins")
		self.rescanAction=self.pluginsMenu.addAction("Rescan")
			
#		self.rescanMenu=QtGui.QAction("Rescan",self.pluginMenu)
#		self.rescanMenu.setObjectName("Rescan")

#		self.rescanAction.QtGui.QAction(self.plugins.discover_plugins())

		#QtCore.QObject.connect(self.rescanAction,QtCore.SIGNAL("triggered()"),self.plugins.discover_plugins)
		self.rescanAction.triggered.connect(self.plugins.discover_plugins)
		

		#self.ui.text_Input.installEventFilter(self)
	
		ts = TextString()

		ts.set_channel("#test")
		ts.set_nick(self._nick)
		
		self.config.saveConfig()
		self.ui.statusbar.showMessage("Loaded...")
	#	try:
	#		with open('py-birch.cfg', 'w') as configfile:
	#			self.config.write(configfile)
	#	except:
	#		print("Config Writing Fail")
#		self.channel_join(ts)

	def setUpSignals(self):
		self.NickChange = QtCore.pyqtSignal()

	def statusBarNotice(self, ts):
		
		message = "Notice From :"+ ts.get_nick()+" - "+ ts.get_message()
		
		self.statusBar(message)

	def statusBar(self, myMessage):
		self.ui.statusbar.showMessage("")
		self.ui.statusbar.showMessage(myMessage)


	def eventFilter(self, obj ,event):
		if event.type() == QtCore.QEvent.KeyPress and event.matches(QtGui.QKeySequence.InsertParagraphSeparator):
			self.sendToServer()
			return True

		return False

	def connectToServer(self):
		#print 'in file dialogue'
		self.statusWindow.append_channel_text("File Dialog Clicked. Touch me, I Rock!\n")
		try:
			self.irc_Connection.connectToIrc()
		#	if irc_Connection.is_alive():
		#			irc_Connection.run()
		#			else:
		#				irc_Connection.start()
			self.statusBar("Connecting...")
		except Disconnected:
			self.statusWindow.append_channel_text(self.ui.editor_Window.getText()+"Disconnected ", Disconnect)
			self.irc_Connection.stop()
			self.statusBar("Connection Failed")
			self.disconnect("Failed to Connect")
			
		


		#print "leaving file dialogue"

	def new_nick(self):
	
		myText, myOk = QtWidgets.QInputDialog.getText(self, 'Enter New Nickname','Nickname In Use. Enter New Nickname:')
		if myOk:
			print (myOk)
			#self.emit(QtCore.SIGNAL("NickChange"),myText)
			self.NickChange.emit(myText)
			#self.raw_sendToServer("NICK "+nick)
			self.send_to_server("NICK "+myText)

	#This method simply takes an *already formatted* string
	#and sends it to the server. It does not processing.
	#should be renamed raw_sendToServer
	def send_to_server(self, string_to_send):

	
		self.irc_Connection.sendToIrc(string_to_send)

	#This method is used for the *status* window. 
	#It is essentially depreicated, and will be cleaned up
	#and only send data without the addition of a channel in later
	#versions.
	def sendToServer(self):

		
		originalString = self.ui.text_Input.text()
		textToSend = originalString
		displayText = textToSend
	
		myTextToSwitch = textToSend.split(" ")

		if myTextToSwitch[0][0:1] == "/":
			if myTextToSwitch[0] == "/msg":
				remainderIndex = string.find(textToSend,myTextToSwitch[1])
				textToSend = "PRIVMSG "+myTextToSwitch[1]+textToSend[remainderIndex:]
				displayText = "**Messaging "+myTextToSwitch[1]+textToSend[remainderIndex:]
			else:
				textToSend = str(textToSend[1:])
				displayText = "---"+str(textToSend)
#remainderIndex=string.find(strServerOutput,":",2)
		else:
				textToSend = "PRIVMSG "+channelName+" :"+textToSend
				displayText = "["+channelName+"] "+originalString
		
		self.irc_Connection.sendToIrc(textToSend)
		displayText = html.escape(displayText)
		self.ui.editor_Window.insertHtml(displayText+"<br>")
		self.ui.text_Input.setText("")

	def button_disconnect(self):
		self.disconnect("Button Clicked")

	def close_channels(self):

		
		for chan in self.ui.mdiArea.subWindowList():
			print("<DEBUG>Disconnecting: Closing Channel Windows:"+chan.get_channel_name().lower())
			if chan.channelType == Channel.CHANNEL:
				chan.closeChannel()
				#self.channelArray[chan.get_channel_name().lower()] = None
				#del self.channelArray[chan.get_channel_name().lower()]
				#del chan

	#	self.channelArray = dict() 
			

	def disconnect(self,MyMessage):
		#print "in disconnect"
		self.irc_Connection.stop()
		self.close_channels()
		self.statusBar("Disconnected :"+MyMessage)

	def removeChannel(self):

		closedChannel = self.sender()

		ts = TextString()
		print("<DEBUG>removeChannel: Entered method : " + closedChannel.get_channel_name())

		#do I need some sanity check for it being OfType Channel?
		#for chan in channelArray:
			#if(chan.get_channel_name() == closedChannel.get_channel_name()):
		if(self.channelArray[closedChannel.get_channel_name().lower()] != None):
	#			print(chan.get_channel_name()+" removed")
			if closedChannel.channelType == Channel.CHANNEL:
				textToSend="PART "+self.channelArray[closedChannel.get_channel_name().lower()].get_channel_name()
				self.send_to_server(textToSend)
	
			self.ui.mdiArea.removeSubWindow(closedChannel)
			self.channelArray[closedChannel.get_channel_name().lower()] = None
			del self.channelArray[closedChannel.get_channel_name().lower()]

				
	def channel_nicklist(self, my_TextString):

		ts = my_TextString
		
		print("<DEBUG:start:channel_nicklist: ts.get_channel:"+ts.get_channel().lower()+" Channel Name:", self.channelArray[ts.get_channel().lower()].get_channel_name())
		
		try:
			self.channelArray[ts.get_channel().lower()].insert_nick(ts)
		except KeyError:
			print("<DEBUG>start.py:channel_nicklist:", KeyError)

	def nick_mode_change(self, my_TextString):
		
		self.channelArray[my_TextString.get_channel().lower()].nick_mode_change(my_TextString)
		print("<DEBIG> nick change fired :" +my_TextString.get_code())

	def remove_nick(self, my_TextString):
		
		ts = my_TextString

		ts.set_nick(ts.get_nick().strip())
		found=False

		#This ensures that a single True response will stop the nick
		#appearing in the status window, which is desired behaviour
		foundSwitch=False
		
		if ts.get_nick().lower().strip() == self._nick.lower().strip():
			print("<DEBUG>Remove Nick: I am leaving a channel!"+ts.get_channel())
			#Print a message in the status window that the user has left
			self.statusWindow.append_channel_text(ts.get_display_string()+"<DEBUG>-From start.remove_nick()" )	
		else:
			print("<DEBUG>Remove Nick (Channel):"+ts.get_channel()+" (nick)"+ts.get_nick())
			if ts.get_code() == "QUIT":
				#we now have to cycle through all channels!
				#we also have to check all channels, incase they are on
				#more than one
			
				for chan in self.channelArray:
					print("<DEBUG>Remove Nick:QUIT:Trying to remove:"+ts.get_nick()+"- From :"+chan)
					found=self.channelArray[chan].remove_nick(ts)	
					if found == True:
						self.channelArray[chan].append_channel_text(ts.get_display_string())
						foundSwitch=True
			else:
				print("<DEBUG>Remove "+ts.get_nick()+" for:"+ts.get_code()+" from (Channel):"+ts.get_channel()+" (Nick)"+ts.get_nick())
			
				found=self.channelArray[ts.get_channel().lower()].remove_nick(ts)
				if found==True:
					self.channelArray[ts.get_channel().lower()].append_channel_text(ts.get_display_string())
					foundSwitch=True

			if foundSwitch:
				print("<DEBUG>remove_nick:QUIT:Nickname found\n")
			else:
				print("<DEBUG>remove_nick:QUIT:Nickname not found\n")
				self.statusWindow.append_channel_text(ts.get_display_string())	
			

	def channel_title_update(self,my_TextString):
		ts = my_TextString
		#print ("<DEBUG>Channel_title_update:Channel"+my_TextString.get_channel())
		#print("<DEBUG>Channel_title_update:Title"+my_TextString.get_display_string())
		self.channelArray[ts.get_channel().lower()].set_channel_title(ts.get_display_string())

	def channel_join(self,my_TextString):

		ts = my_TextString

		myChannelName= ts.get_channel()
		print ("Chan Name "+ myChannelName)
		
		for char in ' :':
			myChannelName = myChannelName.replace(char,'')
			
		#Create the Channel Window, passing in the Channel Name

		exists=False

		#This unusuall series of if's is because of the unusuall case
		# where by chanName can be ==, which means that it is not None,
		# and testing them together passes through the if statement. 
		for chanName in self.channelArray:
			if (chanName is None):
				print("None Type")
			if(not chanName==""):
				#print("Chan Name "+chanName)
				if not (self.channelArray[chanName] is None):
					print("Channel Name " + self.channelArray[chanName].get_channel_name().lower())
					if self.channelArray[chanName].get_channel_name().lower() == myChannelName.lower():
						print("Match Found:"+chanName+"+"+myChannelName.lower())
						exists=True

		if exists:
			print("Channel "+myChannelName+" exists");

		if ts.get_nick() ==  self._nick and not exists: 

			#print ("<DEBUG:Channel:Join:>Creating " + myChannelName)
			#Adding @, so that ops notices get their own channel. 

			if str(myChannelName).startswith("#") or str(myChannelName).startswith("@"):
				channelWindow = Channel(str(myChannelName),self.config,self.plugins)

			else:
				channelWindow = Channel(str(myChannelName), self.config,self.plugins,2)

			#Pass the nickname into the channel. Could be a
			#Constructer variable.
			channelWindow.nick_update(self._nick)

			#Add the Channel to the MDI Area
			self.ui.mdiArea.addSubWindow(channelWindow)
			#Missing - Check to see if Channel Already joined.
			#- This may not be needed as this can only be fired on
			# JOIN recieved from the server. HOWEVER Channel Window
			# may still be open from Disconnect. (v0.1)
		
			#add the Channel to the ChannelArray.
			#channelArray.append(channelWindow)
			##########
			#All channel Keys must be lower case! (or the same case, but I've chosen lower case!)
			##########
			#print("<DEBUG:join:Checking Channel Name", channelWindow.get_channel_name())
			self.channelArray[channelWindow.get_channel_name().lower()] = channelWindow
			
			#Stuff to enable connection to continue to Status Window
			#self.ui.label_ChanName.setText(str(myChannelName))
			channelName = str(myChannelName)

			#Qt::QueuedConnection=2
			#self.connect(channelWindow,QtCore.SIGNAL("UserInput"),self.send_to_server,2)
			channelWindow.UserInput.connect(self.send_to_server)
			#self.connect(self.irc_Connection,QtCore.SIGNAL("NickChange"), channelWindow.nick_update,2)
			self.irc_Connection.NickChange.connect(channelWindow.nick_update)
			#self.connect(self,QtCore.SIGNAL("NickChange"),channelWindow.nick_update)
			self.NickChange.connect(channelWindow.nick_update)
			#self.connect(channelWindow,QtCore.SIGNAL("Channel_Closed"),self.removeChannel,2)
			channelWindow.Channel_Closed.connect(self.removeChannel)
			
			#add a button to the button bar
			
			button_bar_layout = self.ui.button_bar.layout()

			btn_Channel = QtWidgets.QPushButton(channelName)
			#btn_Channel.set
			button_bar_layout.addWidget(btn_Channel)
			
			btn_Channel.show()
			#channelWindow.connect(btn_Channel, QtCore.SIGNAL("clicked()"), channelWindow.button_click)
			btn_Channel.clicked.connect(channelWindow.button_click)

			channelWindow.set_button(btn_Channel)
			
			#Make the Channel Visible
			channelWindow.show()	
			#print("<DEBUG:start:join "+channelWindow.get_channel_name()+">")
			
		else:
			ts.set_channel(myChannelName)
			ts.set_message(ts.get_nick())
			self.channel_nicklist(ts)

	def update_statusWindow(self,  ircMessage):
		
		myQString = "!==!==! "
		myQString = myQString+str(ircMessage)
		myQString = QString(myQString)
		myQString = html.escape(myQString)
		self.statusWindow.append_channel_text(myQString+"<br>")

	def show_about(self):

		self.about = About()

		self.ui.mdiArea.addSubWindow(self.about)

		self.about.show_window()


	def update_editorWindow(self, ircMessage):
		#global server_outputSorter	
		
		ts = self.server_OutputSorter.sortOutput(ircMessage)	
		found = False
		
		#Quite messages are sorted elsewhere. 
		#We need to remove the messages here that are added to the window elsewehre. 
		#--- this list might become a long list, and we might need to find a better way of
		#recording if this should be generalically added. 

		print("<DEBUG>update_editorWindow:Code: "+" "+ts.get_nick()+" "+ts.get_code().lower()+" "+ts.get_channel())
		if ts.get_code() != 'QUIT' and ts.get_code() != 'PART' and ts.get_code() != 'KICK':
			try:
				if (self.channelArray[ts.get_channel().lower()] != None):
					#self.channelArray[ts.get_channel().lower()].append_channel_text(ts.get_display_string())
					self.channelArray[ts.get_channel().lower()].append_channel_ts(ts)
					found = True
				else:
					if self.channelArray[ts.get_code().lower()] != None:
						#self.channelArray[ts.get_code().lower()].append_channel_text(ts.get_display_string())
						self.channelArray[ts.get_code().lower()].append_channel_ts(ts)

						found = True
			except KeyError as e:
				print("<DEBUG>update_editorWindow:KeyError: "+ts.get_code().lower()+" "+ts.get_channel().lower()+" Error:"+ e.args[0])
				pass
		
		
	#NOTE Stauts window access need to be collected into a single method
	#	ircMessage+="\n"
			if (found == False):
				myQString = ""
				myQString = ts.get_display_string()
				myQString = QString(myQString)
				self.statusWindow.append_channel_text(myQString)	
		
		#This should stop the window from updating when scrolling
		#up and down through the channel!
		#if not self.ui.editor_Window.isHorizontalSliderPressed():

		#self.ui.editor_Window.moveCursor(11,False)
		
		del ts
		
	def nicklist_update(self, ts):
		myChannel = ts.get_channel()

		if myChannel.lower() in self.channelArray:
			print( myChannel + " exists. Trying to update " + ts.get_nick())
			self.channelArray[myChannel.lower()].nicklistupdate(ts)
			
		print (myChannel + "Looping through all channels just in case.")
		for chan in self.channelArray:
			self.channelArray[chan].nicklist_update(ts)

	def nick_update(self, myNick) :
		global _nick_
		
		#if myNick == self._nick_:
		#	#update all the channels with the new nickname
		#	for chan in self.channelArray:
		#		chan.nick_update(myNick)
			
		
		_nick_ = myNick
		self._nick=myNick
		self.statusWindow.nick_update(myNick)
	
	def process_gui_events(self):
		global app
		app.processEvents()	

	def tile(self):
		self.ui.mdiArea.tilesSubWindows()

#The numbers seem to be a bit backwards because it's WIDTH, then HEIGHT
	def tileHorizontally(self):

		self._layout = self.const_TILE
		#self.ui.mdiArea.tileSubWindows()
		subWindowList = self.ui.mdiArea.subWindowList()
		
		windowCount=0
		
		#So the calculation works out properly, and ignores minimised windows.
		for window in subWindowList:
			if not window.isMinimized() and not window.isHidden():
				windowCount = windowCount+1
		
		#windowHeight =  self.ui.mdiArea.height() / len(subWindowList)
		 
		windowHeight = self.ui.mdiArea.height() / windowCount
		
		#print(len(subWindowList), windowHeight,  self.ui.mdiArea.width())
		x = 0
		
		for window in subWindowList:
			if not window.isMinimized():
				window.resize(self.ui.mdiArea.width(),  windowHeight)
				window.move(0, x)
				x = x+ windowHeight
	
	def getProperties(self):
		
		return self.config()
		
	def show_properties(self):
		
		self.config.show_window()
	
	
	def cascade(self):
		self.ui.mdiArea.cascadeSubWindows()
		self._layout=self.const_CASCADE

	def closeEvent(self, event):
		
		
		try:
			self.config.saveConfig()
			self.irc_Connection.disconnect()
		except IOError as err:
			print (err)
		except OSError as err:
			print (err)
		except Exception as err:
			print("Final Error : ")
			print(err)

	def resizeEvent(self,event):

		#if(self._layout==self.const_NONE):
			#print("Do nothing, layout is empty")
		
		if(self._layout==self.const_TILE):
			#print("Tiling Layout")
			self.tileHorizontally()

		if(self._layout == self.const_CASCADE):
			#print("Cascde Layout")
			self.cascade()
Example #24
0
	def __init__(self,parent=None):
		global irc_Connection
		#global server_OutputSorter
		global channelWindow
		global _nick_

		#scan the plugins. 
		self.plugins=PluginArchitecture()

		QWidget.__init__(self,parent)
		self.ui = Ui_PyBirch()
		self.ui.setupUi(self)
		
		#Self is the main window.
		self.setWindowTitle("Py-Birch "+self._version)

		self.config = Properties()
		
	#	self.config = configparser.ConfigParser(allow_no_value=True)
	#	try:
	#		if os.path.isfile("py-birch.cfg"):
	#			self.config.read("py-birch.cfg")
	#	except:
	#		self.config.add_section("IRC_Server")
	#		self.config.set("IRC_Server", "Server", "irc.dal.net")
		
		Gui = self
		#QtCore.QObject.connect(irc_Connection,QtCore.SIGNAL("incomming"),self.update_editorWindow);
		
		self.irc_Connection = IrcConnection(self.config)
		self.server_OutputSorter = ServerOutputSorter(self.config,self.plugins)
		self.channelArray = dict()
		
		#channelWindow = Channel()

		#self.ui.mdiArea.addSubWindow(channelWindow)
		#channelWindow.show()

		layout = QGridLayout()
		
		self.statusWindow = Channel("Status", self.config,self.plugins, Channel.STATUS)
		#self.ui.Status.setLayout(layout)	
		self.ui.mdiArea.addSubWindow(self.statusWindow)
		
		#add a button to the button bar
		btn_Status = QtWidgets.QPushButton("Status")
		self.statusWindow.set_button(btn_Status)
		#btn_Status.resize(250, 250)
		button_bar_layout = self.ui.button_bar.layout()
		button_bar_layout.addWidget(btn_Status)
#		self.statusWindow.connect(btn_Status, QtCore.SIGNAL("clicked()"), self.statusWindow.button_click)
		btn_Status.clicked.connect(self.statusWindow.button_click)

		#Set Up Signals
		#self.setUpSignals()
	
		#self.ui.Status.setWindowTitle("Status")

		#self.ui.Status.show()
		#so who needs to know when a nickname is update.
		#PyQt4 Method
		#self.connect(self,QtCore.SIGNAL("NickChange"),self.nick_update)
		#self.connect(self,QtCore.SIGNAL("NickChange"),self.statusWindow.nick_update)
		#self.connect(self,QtCore.SIGNAL("NickChange"),self.irc_Connection.nick_update)

		self.NickChange.connect(self.nick_update)
		self.NickChange.connect(self.statusWindow.nick_update)
		self.NickChange.connect(self.irc_Connection.nick_update)

		#self.connect(self.statusWindow,QtCore.SIGNAL("UserInput"),self.send_to_server,2)
		self.statusWindow.UserInput.connect(self.send_to_server)

		#self.connect(self.irc_Connection,QtCore.SIGNAL("NickChange"), self.statusWindow.nick_update,2)
		self.irc_Connection.NickChange.connect(self.statusWindow.nick_update)

		#Qt::QueuedConnection = 2
		#self.connect(self.irc_Connection,QtCore.SIGNAL("incomming"),self.update_editorWindow, 2)
		self.irc_Connection.Incomming.connect(self.update_editorWindow)
		#self.connect(self.irc_Connection,QtCore.SIGNAL("Status"),self.update_statusWindow, 2)
		self.irc_Connection.Status.connect(self.update_statusWindow)
		#self.connect(self.irc_Connection,QtCore.SIGNAL("NickChange"), self.nick_update, 2)
		self.irc_Connection.NickChange.connect(self.nick_update)
		#self.connect(self.irc_Connection,QtCore.SIGNAL("ProcessEvents"),self.process_gui_events,2)
		self.irc_Connection.ProcessEvents.connect(self.process_gui_events)
		#self.connect(self.irc_Connection, QtCore.SIGNAL("StatusBar"), self.statusBar)
		self.irc_Connection.StatusBar.connect(self.statusBar)
		#self.connect(self.irc_Connection, QtCore.SIGNAL("Disconnect"),self.disconnect,2)
		self.irc_Connection.Disconnect.connect(self.disconnect)

		#self.irc_Connection.connect(self.irc_Connection, QtCore.SIGNAL("NickChange"), self.irc_Connection.nick_update)
		#irc_Connection.connect(irc_Connection, QtCore.SIGNAL("NickChange"), self.nick_update)
		self.irc_Connection.NickChange.connect(self.irc_Connection.nick_update)

		#self.connect(self.server_OutputSorter,QtCore.SIGNAL("join"),self.channel_join)
		self.server_OutputSorter.JOIN.connect(self.channel_join)

		#Part/Quit/Kick are all currently dealt with by the same method, but they are separated
		#In the Sorter for future-proofing (if neeeded) - done: Alpha 0.4.2.1
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("PART"), self.remove_nick)
		self.server_OutputSorter.PART.connect(self.remove_nick)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("QUIT"), self.remove_nick)
		self.server_OutputSorter.QUIT.connect(self.remove_nick)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("KICK"), self.remove_nick)
		self.server_OutputSorter.KICK.connect(self.remove_nick)

		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("NamesOnChannel"), self.channel_nicklist)
		self.server_OutputSorter.NamesOnChannel.connect(self.channel_nicklist)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("RemoveName"), self.remove_nick)
		self.server_OutputSorter.RemoveName.connect(self.remove_nick)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("nick_mode"), self.nick_mode_change)
		self.server_OutputSorter.Nick_Mode.connect(self.nick_mode_change)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("nicklist_update"), self.nicklist_update)
		self.server_OutputSorter.Nicklist_Update.connect(self.nicklist_update)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("ChannelTitle"),self.channel_title_update)
		self.server_OutputSorter.ChannelTitle.connect(self.channel_title_update)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("Notice"), self.statusBarNotice)
		self.server_OutputSorter.Notice.connect(self.statusBarNotice)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("StatusBar"), self.statusBar)
		self.server_OutputSorter.StatusBar.connect(self.statusBar)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("NickChange"), self.nick_update, 2)
		self.server_OutputSorter.NickChange.connect(self.nick_update)
		#self.connect(self.server_OutputSorter, QtCore.SIGNAL("NewNick"),self.new_nick)
		self.server_OutputSorter.NewNick.connect(self.new_nick)

		#QtCore.QObject.connect(self.ui.button_Connect,QtCore.SIGNAL("clicked()"),self.connectToServer)
		self.ui.button_Connect.clicked.connect(self.connectToServer)
		#QtCore.QObject.connect(self.ui.button_Send,QtCore.SIGNAL("clicked()"),self.sendToServer)
		#self.ui.button_Send.clicked.connect(self.sendToServer)
		#QtCore.QObject.connect(self.ui.button_Disconnect,QtCore.SIGNAL("clicked()"),self.button_disconnect)
		self.ui.button_Disconnect.clicked.connect(self.button_disconnect)
		
		#QtCore.QObject.connect(self.ui.button_Tile, QtCore.SIGNAL("clicked()"), self.tileHorizontally)
		self.ui.button_Tile.clicked.connect(self.tileHorizontally)
		#QtCore.QObject.connect(self.ui.button_Cascade,  QtCore.SIGNAL("clicked()"), self.cascade)
		self.ui.button_Cascade.clicked.connect(self.cascade)
		#QtCore.QObject.connect(self.ui.button_Properties, QtCore.SIGNAL("clicked()"), self.show_properties)
		self.ui.button_Properties.clicked.connect(self.show_properties)


		#QtCore.QObject.connect(self.ui.actionProperties, QtCore.SIGNAL("triggered()"), self.show_properties)
		self.ui.actionProperties.triggered.connect(self.show_properties)
		#QtCore.QObject.connect(self.ui.actionConnect, QtCore.SIGNAL("triggered()"), self.connectToServer)
		self.ui.actionConnect.triggered.connect(self.connectToServer)
		#QtCore.QObject.connect(self.ui.actionDisconnect,  QtCore.SIGNAL("triggered()"), self.button_disconnect)
		self.ui.actionDisconnect.triggered.connect(self.button_disconnect)

		#QtCore.QObject.connect(self.ui.actionTile, QtCore.SIGNAL("triggered()"), self.tileHorizontally)
		self.ui.actionTile.triggered.connect(self.tileHorizontally)
		#QtCore.QObject.connect(self.ui.actionCascade, QtCore.SIGNAL("triggered()"), self.cascade)
		self.ui.actionCascade.triggered.connect(self.cascade)
		#QtCore.QObject.connect(self.ui.actionAbout_Py_Birch, QtCore.SIGNAL("triggered()"), self.show_about)
		self.ui.actionAbout_Py_Birch.triggered.connect(self.show_about)



		self.pluginsMenu=self.ui.menubar.addMenu("Plugins")
		self.rescanAction=self.pluginsMenu.addAction("Rescan")
			
#		self.rescanMenu=QtGui.QAction("Rescan",self.pluginMenu)
#		self.rescanMenu.setObjectName("Rescan")

#		self.rescanAction.QtGui.QAction(self.plugins.discover_plugins())

		#QtCore.QObject.connect(self.rescanAction,QtCore.SIGNAL("triggered()"),self.plugins.discover_plugins)
		self.rescanAction.triggered.connect(self.plugins.discover_plugins)
		

		#self.ui.text_Input.installEventFilter(self)
	
		ts = TextString()

		ts.set_channel("#test")
		ts.set_nick(self._nick)
		
		self.config.saveConfig()
		self.ui.statusbar.showMessage("Loaded...")
Example #25
0
	def __init__ (self, propsFile):
		self.props = Properties (propsFile)
		baseUrl = self.props.getProperty("baseUrl")
		RepositorySearcher.__init__(self)
Example #26
0
#usage: GrowET.py properties_file year
##usage: GrowET.py output_file base_file base_year year
# years are the tX years
import sys,os,math
from Properties import Properties

#outfile = sys.argv[1]
#base_file = sys.argv[2]
#base_year = int(sys.argv[3])
#year = int(sys.argv[4])

properties = Properties()
properties.loadPropertyFile(sys.argv[1])

outfile = properties["et.truck.trips"]
base_file = properties["et.basis.matrix"]
base_year = int(properties["et.basis.year"])
year = int(sys.argv[2])

large_growth = float(properties["large.road.growth.rate"])/100.0
small_growth = float(properties["small.road.growth.rate"])/100.0
large_roads = map(str.strip,properties["large.roads"].split(","))
small_roads = map(str.strip,properties["small.roads"].split(","))


#large_growth = 0.024
#small_growth = 0.01
#large_roads = ["5002","5003","5004","5007","5010"]
#small_roads = ["5001","5005","5006","5008","5009","5011"]
f = open(outfile,"wb")
first = True
Example #27
0
import pygame
from Cube import Cube
from Properties import Properties

properties = Properties()


class Grid:
    def __init__(self, board, width, height):
        self.board = board
        self.rows = len(board)
        self.cols = len(board[0])
        self.cubes = [[
            Cube(self.board[i][j][0], i, j, self.rows, self.cols,
                 self.board[i][j][1], width, height) for j in range(self.cols)
        ] for i in range(self.rows)]
        self.width = width
        self.height = height
        self.selected = None
        self.board_coord = []

    def select(self, row, col):
        if (self.cubes[row][col].selected and not self.cubes[row][col].found):
            self.cubes[row][col].selected = False
            coords = (self.cubes[row][col].row, self.cubes[row][col].col)
            if (coords in self.board_coord):
                self.board_coord.remove(coords)
        else:
            self.cubes[row][col].selected = True
        self.selected = (row, col)
Example #28
0
import os
import csv
from Properties import Properties
from Db import Db

function_map = {
	"TEXT": str,
	"INTEGER": int,
	"BOOLEAN": int,
	"DATE": str
}

properties = Properties.getProperties()
db = Db(properties)

spec_files = os.listdir("specs")
data_files = os.listdir("data")

# map files into a dictionary
file_map = {}
for data_file in data_files:
	file_info = data_file.split("_")
	if not file_info[0] in file_map:
		file_map[file_info[0]] = []
	file_map[file_info[0]].append(data_file)

for spec_filename in spec_files:
	with open("specs/" + spec_filename, "rt") as spec_file:
		filename_info = spec_filename.split(".")
		file = csv.reader(spec_file, delimiter=",")
		next(file) # Skip first row
Example #29
0
#!/usr/bin/python3
# coding=utf8
import sys
import time
from threading import Thread

from Cpu import Cpu
from Daemon import Daemon
from Disk import Disk
from Log import Log
from Properties import Properties
from ytj import YTJService

properties = Properties("info.properties").getProperties()


# 报警邮件和来存吧的health
class Task(Thread):
    def __init__(self):
        super(Task, self).__init__()

    def run(self):
        notify_email = properties["notify_email"]
        cpu = Cpu(properties["cpu_monitor_rate"],
                  properties["cpu_over_max_count"], notify_email)

        disk = Disk(properties["all_disk_max_capacity"],
                    properties["single_file_max_capacity"],
                    properties["all_disk_warn_capacity"],
                    properties["direct_remove_file_suffix"],
                    properties["mem_warn_capacity"], log, notify_email)
Example #30
0
# -*- coding: utf-8 -*-
import json
import os
import random
import re
from urllib import request, parse

from Properties import Properties

pro = Properties("province.properties")

keysArr = [
    "1e8c026584273cd7dca6e56744400289", "9a7cdc939c22449b6c76bedebd44d149",
    "2f52b814f431a00001d4af0f59b183c0", "ddce78d564e4beecfcd4be5341b81cec"
]


def collect(provity, words, path):
    phone_patten = re.compile(
        '([\\w+,])?(13\d|14[5|7]|15\d|166|17[3|6|7]|18\d)\d{8}([\\w+,]])?')
    keywordArr = words.split(" ")

    area = pro.getProperties(provity).split(" ")
    for city in area:
        resDataText = []
        for keyword in keywordArr:

            page = 1

            url = "http://restapi.amap.com/v3/place/text?key={}&keywords={}&types=&city={}&children=1&offset=20&page={}&extensions=all"
Example #31
0

def login(host, port, username, password):
    sock.connect((host, port))
    return query("action: login\r\nusername: "******"\r\nsecret: " + password + "\r\nevents: off\r\n\r\n")


def logout():
    mesg = query("action: logoff\r\n")
    sock.close()
    return mesg


try:

    p = Properties()
    p.load(file(configfile))
    i = 0
    s = p.getProperty("hosts." + str(i) + ".hostname")
    while s != "":
        host.append(p.getProperty("hosts." + str(i) + ".hostname"))
        port.append(eval(p.getProperty("hosts." + str(i) + ".port")))
        username.append(p.getProperty("hosts." + str(i) + ".username"))
        password.append(p.getProperty("hosts." + str(i) + ".password"))
        i = i + 1
        s = p.getProperty("hosts." + str(i) + ".hostname")

    if len(sys.argv) > 1:
        hi = eval(sys.argv[1])
    else:
        hi = 0
Example #32
0
    if not utils.ONLY_SQL:
        logdb.setAutoCommit(True)
        for sql in expireSql:
            while True:
                utils.logInfo("execute sql=%s" % sql)
                if logdb.update(sql) == 0:
                    break
    utils.logInfo("all done!")

    # 关闭连接
    logdb.disconnect()
    gmsdb.disconnect()


if __name__ == "__main__":
    props = Properties()
    props.load(open('conf/conf.properties'))
    utils.initLogger(props["log.file.path"])

    parser = OptionParser()
    parser.add_option("-b",
                      "--btime",
                      action="store",
                      type="string",
                      dest="baseTime",
                      default=str(datetime.date.today()),
                      help="基准时间")
    parser.add_option("-g",
                      "--srvs",
                      action="store",
                      type="string",
	def __init__(self):
		self.properties = Properties.getProperties(False)
Example #34
0
					
	def writeTabDelimited (self, records=None, outpath=None):
		"""
		write tab delimeted report to "outpath"
		"""

			
		tabDelimited = self.getTabDelimited(records)
		if outpath is None:
			# outpath = '%s-tab-delimited.txt' % self.__class__.__name__
			outpath = self.props.getProperty('report.file.path')
		## fp = open (outpath, 'w')
		fp = codecs.open(outpath, 'w', "utf-8")
		fp.write (tabDelimited)
		fp.close()
		
		print 'wrote tab-delimited report to ', outpath
			
if __name__ == '__main__':

	props = Properties('myprops.properties')
	
	if 0:
		for key in props.keys():
			print "%s: %s" % (key, props.getProperty(key))
			
	reporter = Reporter ('myprops.properties')
	reporter.writeTabDelimited()
	# for result in reporter.results:
		# print result.toTabDelimited(reporter.columns)
Example #35
0
class Game(Screen):
    started = False


    def start(self):
        if self.started == False:
            self.init_objects()
            Clock.schedule_interval(self.update, 0.015)
            self.started = True

    def init_objects(self):
        with self.canvas:
            self.stones = []
            self.rubies = []
            self.player = Player(self.width / 2)
            self.properties = Properties()
            self.score = Score(self.height)


    def on_touch_down(self, touch):
        self.firstx = touch.x
        if self.started:
            if touch.x > (self.width / 2):
                self.player.move_right()
            else:
                self.player.move_left()

    def on_touch_up(self, touch):
        if self.started:
            if touch.x > (self.width / 2):
                self.player.stop_move_right()
            else:
                self.player.stop_move_left()

    def update(self, dt):
        self.properties.MAX_SPEED += 0.001
        if not self.properties.BLOCK_FREQ == 1:
            self.properties.BLOCK_FREQ -= 0.00005
        self.properties.MAX_SIZE += 0.02

        #score
        self.score.count_score()

        self.player.movement(self.width - 22)

        with self.canvas:
            #STONES
            if random.randint(0, int(self.properties.BLOCK_FREQ)) == 5:
                self.stones.append(
                    Stone(
                        random.randint(0, self.width),
                        1000,
                        self.properties.MAX_SPEED,
                        random.randint(0, 6),
                        random.randint(10, int(self.properties.MAX_SIZE))
                    )
                )


            for stone in self.stones:
                stone.draw()
                if stone.collision(self.player):
                    self.end_game()
                stone.fall()

                if stone.getY() < -int(stone.getSize() + 15):
                    self.stones.remove(stone)

            #END STONES

            #RUBIES

            if random.randint(0, 400) == 5:
                self.rubies.append(
                    Ruby(
                        random.randint(0, self.width),
                        1000,
                        self.properties
                    )
                )
            for ruby in self.rubies:
                ruby.draw()
                if ruby.collision(self.player):
                    ruby.outOfScreen()
                    ruby.draw()
                    ruby.dice_option(self.stones)
                ruby.fall()

                if ruby.getY() < -(40):
                    self.rubies.remove(ruby)
            #END RUBIES

            self.player.draw()

    def end_game(self):
        Clock.unschedule(self.update)

        self.canvas.clear()
        self.started = False
        self.properties.reset()

        root.current = "score"
p = 0.3e5  # <=============================== change here
T = (30. + 273.15)  # <=============================== change here
LC, base = 0.40, 'mass'  # <=============================== change here
zin = np.array([LC, (1. - LC)])
z, z_mass = Tools_Convert.frac_input(MM, zin, base)
'''
=======================================
         CREATING OBJECTS - [to a better identification, all objects' names are followed by "_obj"]
=======================================
'''
rr_obj = RachfordRice()
eos_obj = PengRobinsonEos(pC, Tc, AcF, omega_a, omega_b, kij)

michelsen_obj = Michelsen()
flash_obj = Flash(max_iter=50, tolerance=1.0e-13, print_statistics=False)
prop_obj = Properties(pC, Tc, AcF, omega_a, omega_b, kij)


def getting_the_results_from_FlashAlgorithm_main(p, T, pC, Tc, AcF, z):
    initial_K_values = calculate_K_values_wilson(p, T, pC, Tc, AcF)
    is_stable, K_michelsen = michelsen_obj(eos_obj,
                                           p,
                                           T,
                                           z,
                                           initial_K_values,
                                           max_iter=100,
                                           tolerance=1.0e-12)
    K_flash, F_V_flash = flash_obj(rr_obj, eos_obj, p, T, z, K_michelsen)
    Vector_ToBe_Optimized = np.append(K_flash, F_V_flash)
    result = fsolve(func=flash_obj.flash_residual_function,
                    x0=Vector_ToBe_Optimized,
(_, _, global_molar_fractions, critical_pressure, critical_temperature,
 acentric_factor, molar_mass, omega_a, omega_b, binary_interaction,
 specific_heat) = props
# [2] - Finally, specifying the pressure and temperature to the problem
pressure = 1.01325 * 1e5  # [bar to Pa]
Tinit = 335.0
Tmax = 355.0

# [3] - CREATING OBJECTS
#eosroots_obj = roots_and_choosing_roots_cubic_equation()
rr_obj = RachfordRice()
eos_obj = PengRobinsonEos(critical_pressure, critical_temperature,
                          acentric_factor, omega_a, omega_b,
                          binary_interaction)
michelsen_obj = Michelsen()
prop_obj = Properties(critical_pressure, critical_temperature, acentric_factor,
                      omega_a, omega_b, binary_interaction)

flash_obj = Flash(max_iter=50, tolerance=1.0e-13, print_statistics=None)

# [4] - Calling the main function, which one responsible by calculate the quality and molar fractions
matrix_results = calculate_molar_fraction_curve(pressure,
                                                Tinit,
                                                Tmax,
                                                molar_mass,
                                                global_molar_fractions,
                                                max_iter=100,
                                                tolerance=1.0e-12,
                                                print_statistics=None)

# [5] - Matrix result
cn = global_molar_fractions.shape[0]  #column's number
Example #38
0
import pygame
import time
import string
import random

from Cube import Cube
from Grid import Grid
from BoardCreator import create_board, get_words_coords
from Properties import Properties
from ConfigScreen import show_config_screen

show_config_screen()

properties = Properties()
properties._load_properties()

### Parametros Ventana ###
WINDOW_WIDTH = 760
WINDOW_HEIGHT = 820
WINDOW_TITLE = 'Sopa De Letras'
HELP_FONT_SIZE = 23
### Parametros adicionales ###
GAME_WORDS = properties.words

pygame.font.init()
win = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption(WINDOW_TITLE)
GAME_BOARD = create_board(GAME_WORDS, properties.orientation)
grid = Grid(GAME_BOARD, WINDOW_WIDTH, WINDOW_HEIGHT - 60)
start = time.time()
correct_words = []
	def __generate_string_list(self):
		'''
		__generate_string_list gets a list of all the strings and IDs
		contained in the list of properties files.
		'''
		
		j = 0
		strings = {}
		faux = {}
		
		# Initialize the HTML Parser to read the HTML
		MHP = My_Html_Parser(); 
							
		# iterate the items in the files list to work on them
		for x_file in self.__complete_files:
			
			# Create the OutPut file name (the PSEUDO file)
			# From FLEX
			if "en_US" in x_file:
				new_file = x_file.replace("en_US", "eo_EO")
			
			#From Frankie	
			elif "www-searchapi" in x_file or "www-web" in x_file or "www-catalogapi" in x_file:
				new_file = x_file.replace(".properties", "_eo.properties")
				
			#From Gadgets	
			elif "langs" in x_file and ".properties" in x_file:
				new_file = x_file.replace(".properties", "_eo.properties")
				
			#From Classic	
			elif "localization" in x_file and ".properties" in x_file:
				new_file = x_file.replace(".properties", "_unicodeasian.properties")
				self.__temporary_debug_1.append(x_file)
				
			else:
				self.__temporary_debug_2.append(x_file)
				continue
			
			# Initialize the English Properties Files via this 
			# program (creates a Dictionary of the Properties)
			eng_props = Properties() 
			eng_props.load(open(x_file))
			# We get the Dictionary for the Default Properties File
			engProps = eng_props.getPropertyDict() 
			
			# Now we iterate the properties to make the list for 
			# PseudoLocalization
			for q in engProps:
				value = engProps[q]
				MHP.reset()
				MHP.my_init() 
				
				# We sometimes use "<" or ">" in our strings
				# This will filter them out for the HTML
				# Parser, to prevent errors.
				# If errors happen, modify this section
				if "<" in value or ">" in value:
					
					if value == "<<First Page":
						value = "&lt;&lt;First Page"
						# Make note of the pseudo 
						# localized string in the "faux"
						# dictionary
						p = PseudoTranslate(value)				
							
						# Continue Building the Snippet 
						# with either the Localized 
						# Version or the English Version				
						tran_tmp = p.get_pseudo_str()
						tmp_tran = tran_tmp.replace ("&lt;", "<")
						
					elif value == "Last Page>>":
						value = "Last Page&gt;&gt;"
						# Make note of the pseudo 
						# localized string in the "faux" 
						# dictionary
						p = PseudoTranslate(value)				
							
						# Continue Building the Snippet 
						# with either the Localized 
						# Version or the English Version				
						tran_tmp = p.get_pseudo_str()
						tmp_tran = tran_tmp.replace ("&gt;", ">")

						
					elif value == "<Previous":
						value = "&lt;Previous"
						# Make note of the pseudo 
						# localized string in the "faux"
						# dictionary
						p = PseudoTranslate(value)				
							
						# Continue Building the Snippet 
						# with either the Localized 
						# Version or the English Version				
						tran_tmp = p.get_pseudo_str()
						tmp_tran = tran_tmp.replace ("&lt;", "<")

						
					elif value == "Next>":
						value = "Next&gt;"
						# Make note of the pseudo 
						# localized string in the "faux"
						# dictionary
						p = PseudoTranslate(value)				
							
						# Continue Building the Snippet
						# with either the Localized 
						# Version or the English Version				
						tran_tmp = p.get_pseudo_str()
						tmp_tran = tran_tmp.replace ("&gt;", ">")

						
					elif value == "<Back":
						value = "&lt;Back"
						# Make note of the pseudo 
						# localized string in the "faux"
						# dictionary
						p = PseudoTranslate(value)				
							
						# Continue Building the Snippet
						# with either the Localized 
						# Version or the English Version				
						tran_tmp = p.get_pseudo_str()
						tmp_tran = tran_tmp.replace ("&lt;", "<")

					
					else:
						# Read the string into the HTML 
						# Parser
						MHP.feed(value) 
						tmp_tran = MHP.get_the_answer()
						
						if tmp_tran == '':
							MHP.my_init()
							MHP.reset()
							try_me = "<body>" + value + "</body>"
							MHP.feed(try_me)
							step_1 = MHP.get_the_answer()
							step_2 = step_1.replace("<body>","")
							step_3 = step_2.replace("</body>","")
							tmp_tran = step_3
							
							if tmp_tran == '':
								print x_file + "\n" + q + "=" + value
									
				else:
					# Make note of the pseudo localized 
					# string in the "faux" dictionary
					p = PseudoTranslate(value)				
						
					# Continue Building the Snippet with
					# either the Localized Version or the 
					# English Version				
					tmp_tran = p.get_pseudo_str()
												
				# Rebuild the format PROPERTY_ID = PROPERTY
				self.__translations.append(q + "=" + tmp_tran)	
						
			# Open the new output file, write it's new content
			N = codecs.open(new_file, 'w')
			
			print "this is #%s of %s files to do" % (j+1, len(self.__complete_files))
			
			j += 1
			
			for write_me in self.__translations:
				
				N.write(write_me + "\n")
				
			N.close()
			
			self.__translations = []
from Properties import Properties
properties = Properties("my.properties")

price = float(properties.get_single_property('price'))

print('price: ' + str(price))
Example #41
0
    Build a "safe" version of the module name, splitting out parameterized levels. Basically splits the name
    by "-" characters, and then replaces all spaces with underscores.
    """
    module_set = map(str.upper,map(str.strip,module.split('-')))
    for i in range(len(module_set)):
        module_set[i] = module_set[i].replace(' ','_')
    return module_set

scenario_dir = os.path.join(root_dir,scenario_name).replace('\\','/')
scenario_inputs = os.path.join(scenario_dir,'inputs').replace('\\','/')
scenario_outputs = os.path.join(scenario_dir,'outputs').replace('\\','/')
config_path = os.path.join(scenario_dir,'model','config').replace('\\','/')

#in some cases, an initial property file definition can be set
initial_token_map_file = os.path.join(config_path,'model_run_initialization.properties')
token_map = Properties()
if os.path.exists(initial_token_map_file):
    token_map.loadPropertyFile(initial_token_map_file)
#update token mapping with overridden initialization
for y in range(len(years)):
    for module_name in module_init_map[y]:
        updateTokenMap(parseModuleName(module_name),years[y],token_map)
        
#add in fixed or initialized tokens
token_map[PropertyTokens.SL_MODE] = 'none'
token_map[PropertyTokens.SCENARIO_NAME] = scenario_name
token_map[PropertyTokens.ROOT_DIR] = root_dir
token_map[PropertyTokens.SCENARIO_INPUTS_DIR] = 'inputs'
token_map[PropertyTokens.SCENARIO_OUTPUTS_DIR] = 'outputs'