Example #1
0
def modifyNPCWeights(records):
    """ Modify NPC Weight to lower with distribution around 35%
	"""
    from System import Predicate
    from System.Text import StringBuilder
    from System.Text.RegularExpressions import Regex
    sb = StringBuilder()
    #types = set(('NPC_',))
    masterIdx = loadMasterPluginIndex()  # build dictionary of masters
    #matchType = Predicate[BaseRecord](lambda rec: (isinstance(rec, Plugin) or isinstance(rec,GroupRecord) or (isinstance(rec,Record) and rec.Name in types)))

    for plugin in records:
        lowerName = plugin.Name.lower()
        pluginIdMap = buildPluginMasterIndexMap(
            plugin,
            masterIdx)  # build dictionary of masters.  invalid map to 0xFF
        pluginidx = masterIdx.get(lowerName, 255) & 0xFF

        first = True
        pluginID = plugin.GetMasters().Length
        for rec in plugin.GetRecordList('NPC_'):
            itemMaster = (rec.FormID & 0xFF000000) >> 24
            formid = translateRecordID(rec, pluginIdMap)

            if first:
                sb.AppendFormat("\n; [{0:X2}] {1}\n", pluginidx,
                                plugin.DescriptiveName)
                first = False

            try:
                fullname = getTrimFullName(rec)
                weight = getWeight(rec)
                print weight
                if not weight or weight >= 10:  # leave alone
                    newweight = rnorminv(
                        35, 20, 0, 100
                    )  # generate random value between 0 and 100 centered around 35 with sigma of 20
                    if not newweight:
                        newweight = rnorminv(35, 20, 0, 100)  # try again
                    setWeight(rec, newweight)

                    sb.AppendFormat(
                        "{0:X8}.SetNPCWeight {4} ; {3} \t{1} \t{2} \n", formid,
                        rec.DescriptiveName, fullname, weight, newweight)
            except Exception, e:
                print str(e)
                pass
Example #2
0
def listNPCWeights(records):
    from System import Predicate
    from System.Text import StringBuilder
    from System.Text.RegularExpressions import Regex
    sb = StringBuilder()
    masterIdx = loadMasterPluginIndex()  # build dictionary of masters
    #types = set(('NPC_',))
    #matchType = Predicate[BaseRecord](lambda rec: (isinstance(rec, Plugin)
    #  or isinstance(rec,GroupRecord) or (isinstance(rec,Record) and rec.Name in types)))

    for plugin in records:
        lowerName = plugin.Name.lower()
        # Build master map with invalid masters mapping to 0xFF
        pluginIdMap = buildPluginMasterIndexMap(plugin, masterIdx)
        pluginidx = masterIdx.get(lowerName, 255) & 0xFF

        first = True
        pluginID = plugin.GetMasters().Length
        for rec in plugin.GetRecordList('NPC_'):
            itemMaster = (rec.FormID & 0xFF000000) >> 24
            formid = translateRecordID(rec, pluginIdMap)

            if first:
                sb.AppendFormat("\n; [{0:X2}] {1}\n", pluginidx,
                                plugin.DescriptiveName)
                first = False

            try:
                fullname = getTrimFullName(rec)
                weight = getWeight(rec)
                scale = getScale(rec)

                sb.AppendFormat("{0:X8}.SetNPCWeight {3} ; {1} \t{2}\n",
                                formid, rec.DescriptiveName, fullname, weight)
                # if scale <> 1.0 and scale <> None:
                # sb.AppendFormat("{0:X8}.SetScale {3} ; {1} \t{2}\n",
                # formid, rec.DescriptiveName, fullname, weight
                # )
            except Exception, e:
                print str(e)
                pass
Example #3
0
def generateItemList(records):
    from System.Text import StringBuilder

    reWhite = Regex(
        r"[\n\t\r]"
    )  # can probably use re but user might not have full IronPython
    sb = StringBuilder()
    masterIdx = loadMasterPluginIndex()
    types = set(("ARMO", "WEAP", "MISC", "AMMO", "KEYM"))
    #matchType = Predicate[BaseRecord](lambda rec: (isinstance(rec, Plugin) or isinstance(rec,GroupRecord) or (isinstance(rec,Record) and rec.Name in types)))

    for plugin in records:
        lowerName = plugin.Name.lower()

        if lowerName == 'rbs.esp':
            continue  # skip this mod since its huge and not very interesting here
        pluginidx = masterIdx.get(lowerName, 255) & 0xFF

        first = True
        pluginID = plugin.GetMasters().Length
        for rec in plugin.GetRecordList(types):
            itemMaster = (rec.FormID & 0xFF000000) >> 24
            if itemMaster != pluginID:  # not interested in overrides
                continue

            if first:
                sb.AppendFormat("\n; [{0:X2}] {1}\n", pluginidx,
                                plugin.DescriptiveName)
                first = False

            fullname = getTrimFullName(rec)
            sb.AppendFormat("player.additem {0:X2}{1:X6} 1 ; {2} \t{3}\n",
                            pluginidx, rec.FormID & 0x00FFFFFF,
                            rec.DescriptiveName, fullname)

    return sb.ToString()
Example #4
0
def exportSignalsToStream(dc, dayToExport, deviceNameToExport, targetStream, subroutineName, \
	exportFileSystemSignals, exportWifiSignals):
	"""
	Exports signal data of activity log to a stream.

	Keyword arguments:
	dc -- DataContext that should be used to read activity log (TimeCockpit.Data.DataContext)
	dayToExport -- Day that should be exported (DateTime; time-part has to be 0)
	deviceNameToExport -- Name of the device that should be exported
	targetStream -- Target Stream (System.IO.StreamWriter)
	subroutineName -- Name of the generated routine (should be unique for each export)
	exportFileSystemSignals -- Indicates whether file system signals should be exported (bool); default is False
	exportWifiSignals -- Indicates whether WIFI signals should be exported (bool); default is False
	"""

	# Internal helper function for extracting type name
	def extractTypeName(x):
		helper = str(x)
		helper = helper.Substring(0, helper.IndexOf(' '))
		helper = helper.Substring(helper.LastIndexOf('.') + 1)
		return helper

	# Specify all signal types that should be exported
	signalTypes = [ "APP_CleansedChangeSetSignal", "APP_CleansedComputerActiveSignal", "APP_CleansedEmailSentSignal",
		"APP_CleansedIpConnectSignal", "APP_CleansedPhoneCallSignal", "APP_CleansedShortMessageSignal", 
		"APP_CleansedUserActiveSignal", "APP_CleansedUserNoteSignal", "APP_CleansedWindowActiveSignal", 
		"APP_CleansedWorkItemChangeSignal" ]
	if exportFileSystemSignals:
		# Only export file system signals if explicitly asked for
		signalTypes.append("APP_CleansedFileSystemSignal")
	if exportWifiSignals:
		# Only export WIFI signals if explicitly asked for
		signalTypes.append("APP_CleansedWifiAvailableSignal")

	try:
		chunks = dc.SelectWithParams({
			"Query": "From C In SYS_Chunk.Include('SYS_Entity').Include('SYS_Device') " \
				"Where ((:Year(C.BeginTime) = @FilterYear And :Month(C.BeginTime) = @FilterMonth And :Day(C.BeginTime) = @FilterDay) " \
				"	Or (:Year(C.EndTime) = @FilterYear And :Month(C.EndTime) = @FilterMonth And :Day(C.EndTime) = @FilterDay)) " \
				"	And C.Device.DeviceName = @DeviceName Select C",
			"@FilterYear": dayToExport.Year, "@FilterMonth": dayToExport.Month, "@FilterDay": dayToExport.Day,
			"@DeviceName": deviceNameToExport })
		if (len(chunks) == 0):
			raise Exception("No chunks found. Please review export filter criteria.")
		
		# Write documentation header
		targetStream.WriteLine("# -*- coding: utf-8 -*-")
		targetStream.WriteLine("# This is an auto-generated script")
		targetStream.WriteLine("#\tGeneration date: {0}", DateTime.Today)
		targetStream.WriteLine("#\tSource device name: {0}", deviceNameToExport)
		targetStream.WriteLine("#\tSource day: {0}", dayToExport)
		targetStream.WriteLine()

		# Write necessary imports		
		targetStream.WriteLine("from System.Collections.Generic import List")
		targetStream.WriteLine()
		
		# Generate method that regenerates activity log
		targetStream.WriteLine("def {0}(dc, targetDay):", subroutineName)

		targetStream.WriteLine("\t\"\"\"", subroutineName)
		targetStream.WriteLine("\tGenerates activity log in the current user account")
		targetStream.WriteLine("")
		targetStream.WriteLine("\tKeyword arguments:")
		targetStream.WriteLine("\tdc -- DataContext that should be used to write activity log")
		targetStream.WriteLine("\ttargetDay -- Day into which the activity log should be imported")
		targetStream.WriteLine("\t\"\"\"", subroutineName)

		targetStream.WriteLine("\tentities = dc.Select(\"From E In SYS_Entity Select E\")")
		targetStream.WriteLine("\tdevice = dc.SelectSingle(\"From D In SYS_Device Select D\")")
		targetStream.WriteLine("\tif device is None:")
		targetStream.WriteLine("\t\traise Exception(\"No device found\")")
		targetStream.WriteLine("\ttimeCorrection = targetDay - DateTime({0}, {1}, {2})", dayToExport.Year, dayToExport.Month, dayToExport.Day)
		
		targetStream.WriteLine("\tdc.DbClient.BeginTransaction()")
		targetStream.WriteLine("\ttry:")
		for chunk in chunks:
			if (chunk.Entity.EntityName in signalTypes):
				targetStream.WriteLine("\t\tchunk = dc.CreateChunk({{ \"BeginTime\": DateTime({0}, {1}, {2}, {3}, {4}, {5}) + timeCorrection,", chunk.BeginTime.Year, chunk.BeginTime.Month, chunk.BeginTime.Day, chunk.BeginTime.Hour, chunk.BeginTime.Minute, chunk.BeginTime.Second)
				targetStream.WriteLine("\t\t\t\"EndTime\": DateTime({0}, {1}, {2}, {3}, {4}, {5}) + timeCorrection,", chunk.EndTime.Year, chunk.EndTime.Month, chunk.EndTime.Day, chunk.EndTime.Hour, chunk.EndTime.Minute, chunk.EndTime.Second)
				targetStream.WriteLine("\t\t\t\"LogicalBeginTime\": DateTime({0}, {1}, {2}, {3}, {4}, {5}) + timeCorrection,", chunk.LogicalBeginTime.Year, chunk.LogicalBeginTime.Month, chunk.LogicalBeginTime.Day, chunk.LogicalBeginTime.Hour, chunk.LogicalBeginTime.Minute, chunk.LogicalBeginTime.Second)
				targetStream.WriteLine("\t\t\t\"LogicalEndTime\": DateTime({0}, {1}, {2}, {3}, {4}, {5}) + timeCorrection,", chunk.LogicalEndTime.Year, chunk.LogicalEndTime.Month, chunk.LogicalEndTime.Day, chunk.LogicalEndTime.Hour, chunk.LogicalEndTime.Minute, chunk.LogicalEndTime.Second)
				targetStream.WriteLine("\t\t\t\"Entity\": [e for e in entities if e.EntityName == \"{0}\"][0],", chunk.Entity.EntityName)
				targetStream.WriteLine("\t\t\t\"Device\": device })")
				
				targetStream.WriteLine("\t\tchunkContentList = List[EntityObject]()")
				for signal in chunk.Content:
					signalContent = StringBuilder()
					for prop in signal.Entity.Properties:
						typeName = extractTypeName(prop)
						if (typeName <> "CalculatedProperty"):
							if (signalContent.Length > 0):
								signalContent.Append(", ")
							signalContent.AppendFormat("\"{0}\": ", prop.Name)
							if (typeName == "TextProperty"):
								signalContent.Append('"')
								t = eval("signal.{0}".format(prop.Name)).Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\t").Replace("\r", "\\r")
								signalContent.Append(t)
								signalContent.Append('"')
							elif (typeName == "DateTimeProperty"):
								signalContent.Append('DateTime(')
								d = eval("signal.{0}".format(prop.Name))
								signalContent.AppendFormat("{0}, {1}, {2}, {3}, {4}, {5}", d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second)
								signalContent.Append(')')
								if (prop.Name == "APP_BeginTime" or prop.Name == "APP_EndTime" or prop.Name == "APP_EventTime"):
									signalContent.Append(" + timeCorrection")
							elif (typeName == "BooleanProperty"):
								b = eval("signal.{0}".format(prop.Name))
								signalContent.Append("True" if b else "False")
							elif (typeName == "GuidProperty"):
								signalContent.Append('Guid("')
								signalContent.Append(eval("signal.{0}".format(prop.Name)))
								signalContent.Append('")')
							elif (typeName == "NumericProperty"):
								n = eval("signal.{0}".format(prop.Name))
								signalContent.Append(n)
							else:
								raise Exception("MISSING TYPE {0}".format(typeName))
					targetStream.WriteLine("\t\tchunkContentList.Add(dc.Create{0}({{ {1} }}))", chunk.Entity.EntityName, signalContent.ToString())
				targetStream.WriteLine("\t\tchunk.Content = chunkContentList")
				targetStream.WriteLine("\t\tdc.SaveObject(chunk)")
		targetStream.WriteLine("\texcept:")
		targetStream.WriteLine("\t\tif (dc.DbClient.TransactionCount > 0):")
		targetStream.WriteLine("\t\t\tdc.DbClient.RollbackTransaction()")
		targetStream.WriteLine("\t\traise")
		targetStream.WriteLine("\tfinally:")
		targetStream.WriteLine("\t\tif (dc.DbClient.TransactionCount > 0):")
		targetStream.WriteLine("\t\t\tdc.DbClient.CommitTransaction()")
		targetStream.WriteLine()

		targetStream.WriteLine("# Uncomment and adapt the following two lines to enable the import execution")
		targetStream.WriteLine("# dc = Context")
		targetStream.WriteLine("# {0}(dc, DateTime({1}, {2}, {3}))", subroutineName, dayToExport.Year, dayToExport.Month, dayToExport.Day)
		
	finally:
		targetStream.Close()
from System.IO import StreamReader, StreamWriter
from System.Text import StringBuilder

path = r"lib/EnyimMemcached/build/CommonProperties.targets"

sr = StreamReader(path)
sb = StringBuilder()

line = sr.ReadLine()
while not line is None:
    
    #I'm sure this could all be done in a couple of lines with a nice multi-line Regex
    #All this does is comment out property groups that attempt to set signing 
    if line.Trim().StartsWith("<PropertyGroup") and line.Contains("PrivateKey"):
        
        sb.AppendFormat("<!--{0}\r\n", line)                 
        while line is not None and line.Trim() != "</PropertyGroup>":
            sb.AppendLine(line)
            line = sr.ReadLine()
        else:
            sb.AppendFormat("{0}-->\r\n", line)            
    else:
        sb.AppendLine(line)
    
    line = sr.ReadLine()
        
content = sb.ToString()
content = content.Replace("<DelaySign>true</DelaySign>", "<DelaySign>false</DelaySign>")
content = content.Replace("<SignAssembly>true</SignAssembly>", "<SignAssembly>false</SignAssembly>")
sr.Dispose()