示例#1
0
def systemInfo():
    verInfo = r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
    psKey = r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine"
    sysPolKey = r"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System"

    sysSummary = printHeader("SYSTEM INFORMATION")
    sysSummary += "{0:<10}: {1}\n".format("Host", Env.MachineName)
    sysSummary += "{0:<10}: {1} {2}\n".format("OS", Registry.GetValue(verInfo, "ProductName", "Windows"), Diagnostics.FileVersionInfo.GetVersionInfo(Env.SystemDirectory + "\\kernel32.dll").ProductVersion)
    sysSummary += "{0:<10}: {1}\n".format("64-Bit", Env.Is64BitOperatingSystem)
    sysSummary += "{0:<10}: {1}\n".format("Date", DateTime.Now.ToString())
    sysSummary += "{0:<10}: {1}\n\n".format("Uptime", DateTimeOffset(DateTime.Now).AddMilliseconds(-Env.TickCount).LocalDateTime)
    
    sysSummary += "{0:<14}: {1}\{2}\n".format("Username", Env.UserDomainName, Env.UserName)
    sysSummary += "{0:<14}: {1}\n\n".format("Logon Server", Env.GetEnvironmentVariable("LOGONSERVER"))

    sysSummary += "{0:<22}: {1}\n".format("PowerShell Version", Registry.GetValue(psKey, "PowerShellVersion", "N/A - Likely 2.0"))
    sysSummary += "{0:<22}: {1}\n".format("PowerShell Compat", Registry.GetValue(psKey, "PSCompatibleVersion", "N/A - Likely 1.0, 2.0"))
    sysSummary += "{0:<22}: {1}\n".format("PS Script Block Log", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging", "EnableScriptBlockLogging", "N/A"))
    sysSummary += "{0:<22}: {1}\n".format("PS Transcription", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription", "EnableTranscripting", "N/A"))
    sysSummary += "{0:<22}: {1}\n".format("PS Transcription Dir", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription", "OutputDirectory", "N/A"))
    sysSummary += "{0:<22}: {1}\n\n".format("PS Module Logging", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging", "EnableModuleLogging", "N/A"))

    sysSummary += "{0:<27}: {1}\n".format("UAC Enabled", Convert.ToBoolean(Registry.GetValue(sysPolKey, "EnableLUA", "N/A")))
    sysSummary += "{0:<27}: {1}\n".format("High Integrity", WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
    sysSummary += "{0:<27}: {1}\n".format("UAC Token Filter Disabled", Registry.GetValue(sysPolKey, "LocalAccount", False))
    sysSummary += "{0:<27}: {1}\n".format("UAC Admin Filter Enabled", Registry.GetValue(sysPolKey, "FilterAdministratorToken", False))
    sysSummary += "{0:<27}: {1}\n".format("Local Admin Pass Solution", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft Services\AdmPwd", "AdmPwdEnabled", "N/A"))
    sysSummary += "{0:<27}: {1}\n".format("LSASS Protection", Registry.GetValue("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa", "RunAsPPL", "N/A"))
    sysSummary += "{0:<27}: {1}\n".format("Deny RDP Connections", Convert.ToBoolean(Registry.GetValue("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server", "FDenyTSConnections", "N/A")))

    return sysSummary
示例#2
0
 def _get_map_value2(map, key, format=None):
     try:
         if str(type(map[key])) == "<type 'NSData'>":
             if format == 'str':
                 return Encoding.UTF8.GetString(map[key].Bytes)
             if format == 'bool':
                 return Convert.ToBoolean(map[key].Bytes)
             if format == 'int':
                 return Convert.ToInt32(map[key].Bytes)
             return map[key].Bytes
         if format == 'data':
             return Encoding.UTF8.GetBytes(str(map[key]))
         if format == 'bool':
             return bool(map[key])
         if format == 'int':
             return int(str(map[key]))
         return str(map[key])
     except:
         if format == 'bool':
             return False
         elif format == 'int':
             return 0
         elif format == 'str':
             return ""
         elif format == 'data':
             return bytes(0)
示例#3
0
def firewallStatus():
    fwKey = r"HKEY_LOCAL_MACHINE\System\ControlSet001\Services\SharedAccess\Parameters\FirewallPolicy"

    fwSummary = printHeader("FIREWALL STATUS")
    fwSummary += "Standard: {0}\n".format(
        Convert.ToBoolean(
            Registry.GetValue(fwKey + "\StandardProfile", "EnableFirewall",
                              "N/A")))
    fwSummary += "Domain: {0}\n".format(
        Convert.ToBoolean(
            Registry.GetValue(fwKey + "\DomainProfile", "EnableFirewall",
                              "N/A")))
    fwSummary += "Public: {0}\n".format(
        Convert.ToBoolean(
            Registry.GetValue(fwKey + "\PublicProfile", "EnableFirewall",
                              "N/A")))

    #MAYBE TO-DO: Parse/print firewall rules
    '''rulesKey = Registry.LocalMachine.OpenSubKey("System\ControlSet001\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules")
    rules = rulesKey.GetValueNames()
    for rule in rules:
        value = rulesKey.GetValue(rule)
        if "Active=TRUE" in value:
            valueDict = {}
            settings = value.split("|")
            for s in settings[1:-1]:
                k = s.split("=")[0]
                v = s.split("=")[1]
                valueDict[k] = v
            if 'LPort' in valueDict:
                print valueDict
            #fwSummary +=  "{0:<40}: {1}\n".format(rule, value)'''

    print fwSummary
示例#4
0
    def encode_job(self, job):
        random_bytes = Array.CreateInstance(Byte, 2)
        Random().NextBytes(random_bytes)

        data = Encoding.UTF8.GetBytes(JavaScriptSerializer().Serialize(job))
        with MemoryStream(data.Length) as initialStream:
            initialStream.Write(data, 0, data.Length)
            initialStream.Seek(0, SeekOrigin.Begin)
            with MemoryStream() as resultStream:
                with GZipStream(resultStream,
                                CompressionMode.Compress) as zipStream:
                    buffer = Array.CreateInstance(Byte, 4096)
                    bytesRead = initialStream.Read(buffer, 0, buffer.Length)
                    zipStream.Write(buffer, 0, bytesRead)
                    while bytesRead != 0:
                        bytesRead = initialStream.Read(buffer, 0,
                                                       buffer.Length)
                        zipStream.Write(buffer, 0, bytesRead)

                result = resultStream.ToArray()
                result[:2] = random_bytes
                return {
                    Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(
                        0, 8):
                    Convert.ToBase64String(Guid.NewGuid().ToByteArray()),
                    "data":
                    Convert.ToBase64String(result)
                }
示例#5
0
def firewallStatus():
    fwKey = r"HKEY_LOCAL_MACHINE\System\ControlSet001\Services\SharedAccess\Parameters\FirewallPolicy"

    fwSummary = printHeader("FIREWALL STATUS")
    fwSummary += "Standard: {0}\n".format(Convert.ToBoolean(Registry.GetValue(fwKey + "\StandardProfile", "EnableFirewall", "N/A")))
    fwSummary += "Domain: {0}\n".format(Convert.ToBoolean(Registry.GetValue(fwKey + "\DomainProfile", "EnableFirewall", "N/A")))
    fwSummary += "Public: {0}\n".format(Convert.ToBoolean(Registry.GetValue(fwKey + "\PublicProfile", "EnableFirewall", "N/A")))
            
    return fwSummary
示例#6
0
def urlEncode(value):
	unreserved = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"
	sb = StringBuilder()
	bytes = Encoding.UTF8.GetBytes(value)

	for b in bytes:
		if b < 0x80 and unreserved.IndexOf(Convert.ToChar(b)) != -1:
			sb.Append(Convert.ToChar(b))
		else:
			sb.Append('%' + String.Format("{0:X2}", Convert.ToInt32(b)))

	return sb.ToString()
示例#7
0
def getFileLocation(f):
    filemd = get_quicktime_md(f)
    for key in filemd:
        if not key[-7:] == '_source':
            f.MetaData.Add(key, filemd [key], "Quicktime Metadata")
            mdDefGroup = MetaData.EXPORT_METADATA_GROUP_NAME
        if key == 'com.apple.quicktime.creationdate':
            f.MetaData.Add("Record Time", TimeStamp(Convert.ToDateTime(filemd[key]), True).ToString(), mdDefGroup)
        elif key == 'com.apple.quicktime.make':
            f.MetaData.Add ("Camera Make", filemd [key], mdDefGroup)
        elif key == 'com.apple.quicktime.model':
            f.MetaData.Add ("Camera Model", filemd [key], mdDefGroup)
        elif key == 'com.apple.quicktime.software':
            f.MetaData.Add ("Camera Software", filemd [key], mdDefGroup)
        elif key == 'com.apple.quicktime.camera.identifier':
            f.MetaData.Add ("Camera Identifier", filemd [key], mdDefGroup)
        elif key == 'com.apple.quicktime.comment':
            f.MetaData.Add ("User Comment", filemd[key], mdDefGroup)
        elif key == 'com.apple.quicktime.location.name':
            f.MetaData.Add ("Location Name", filemd[key], mdDefGroup)
        if key == 'com.apple.quicktime.location.ISO6709':
            locval = parseLocation(filemd[key])
            if locval is None:
                continue

            if 'com.apple.quicktime.location.ISO6709_source' in filemd:
                src_ind = filemd['com.apple.quicktime.location.ISO6709_source'][0]
                mdSrc = f.Data.GetSubRange(src_ind, sum(map(len, locval)))
            if mdSrc is None:
                msSrc = MemoryRange()
            f.MetaData.Add("Lat/Lon/Elev", "%s/%s/%s" % tuple(locval), mdSrc, mdDefGroup)

            cLoc = Base.Location()
            cLoc.Deleted = f.Deleted
            cLoc.SourceType = LocationSourceType.Media
            cLoc.Coordinate = Base.Coordinate(float(locval[0]), float(locval[1]), float(locval[2]))
            cLoc.SourceFile = f.AbsolutePath
            # LinkModels(cLoc, f)
            
            if 'com.apple.quicktime.location.ISO6709_source' in filemd:
                src_ind = filemd['com.apple.quicktime.location.ISO6709_source'][0]
                src_ind += len(locval[0])
                if locval[2] is not None and len(locval[2]) > 1:
                    src_ind += len(locval[1])

            if 'com.apple.quicktime.creationdate' in filemd:
                tsStr = filemd['com.apple.quicktime.creationdate']
                cLoc.Time = TimeStamp(Convert.ToDateTime(tsStr), True)
                if 'com.apple.quicktime.creationdate' in filemd:
                    src = filemd['com.apple.quicktime.creationdate_source']

            return cLoc
    return None
示例#8
0
 def check_key(key, src):
     rm = RijndaelManaged()
     rm.Key = Convert.FromBase64String(base64.b64encode(key))
     rm.Mode = CipherMode.ECB
     rm.Padding = PaddingMode.None
     tr = rm.CreateDecryptor()
     data = src.Data
     data.seek(0)
     bts = data.read(16)
     bts = Convert.FromBase64String(base64.b64encode(bts))
     t_r = tr.TransformFinalBlock(bts, 0, 16)
     name = str(bytes(t_r))
     print name
     if name != "SQLite format 3\0":
         return False
     return True
示例#9
0
def combinedatetime(isdatei=None, istimei=None):
    import clr
    from System import DateTime
    from System import Convert

    dt = Convert.ToDateTime(isdatei + " " + istimei)
    return dt
    def load_bool_from_xml(self, xmldoc, name):
        """Loads a bool with a specified node name from an XmlDocument and saves it to the attribute. The bool should be saved as:
        <name>true/false</name>

        xmldoc->The XmlDocment to load from.
        name->The attribute to save to and the root node name to load the bool from."""
        if xmldoc.SelectSingleNode(name) is not None:
            setattr(self, name, Convert.ToBoolean(xmldoc.SelectSingleNode(name).InnerText))
示例#11
0
 def aes_decrypt(src, dst, key):
     rm = RijndaelManaged()
     rm.Key = Convert.FromBase64String(base64.b64encode(key))
     rm.Mode = CipherMode.ECB
     rm.Padding = PaddingMode.None
     tr = rm.CreateDecryptor()
     f = open(dst, 'wb')
     data = src.Data
     sz = src.Size
     idx = 0
     while idx < sz:
         bts = data.read(16)
         bts = Convert.FromBase64String(base64.b64encode(bts))
         t_r = tr.TransformFinalBlock(bts, 0, 16)
         f.write(t_r)
         idx += 16
     f.close()
示例#12
0
 def _get_map_value(map, key, format=None):
     try:
         if map.ContainsKey(key) == False:
             if format == 'bool':
                 return False
             elif format == 'int':
                 return 0
             elif format == 'str':
                 return ""
             elif format == 'data':
                 return Encoding.UTF8.GetBytes("0")
         if hasattr(map[key], "Bytes"):
             if format == 'str':
                 return Encoding.UTF8.GetString(map[key].Bytes)
             if format == 'bool':
                 return Convert.ToBoolean(map[key].Bytes)
             if format == 'int':
                 return Convert.ToInt32(map[key].Bytes)
             return map[key].Bytes
         if format == 'data':
             if hasattr(map[key], "Bytes"):
                 return map[key].Bytes
             else:
                 return Encoding.UTF8.GetBytes(map[key].ToString())
         if format == 'bool':
             if hasattr(map[key], "ToBool"):
                 return map[key].ToBool()
             else:
                 return bool(map[key])
         if format == 'int':
             if hasattr(map[key], "ToInt"):
                 return map[key].ToInt()
             else:
                 return Convert.ToInt32(map[key])
         return map[key].ToString()
     except:
         if format == 'bool':
             return False
         elif format == 'int':
             return 0
         elif format == 'str':
             return ""
         elif format == 'data':
             return Encoding.UTF8.GetBytes("0")
示例#13
0
 def run_script(self, data):
     script = Encoding.UTF8.GetString(Convert.FromBase64String(data))
     stream = MuhStream()
     engine = Python.CreateEngine()
     engine.Runtime.IO.SetOutput(stream, Encoding.UTF8)
     engine.Runtime.IO.SetErrorOutput(stream, Encoding.UTF8)
     #scope = engine.CreateScope()
     #scope.SetVariable("client", self)
     engine.Execute(script)
     return stream.string
def test_str_of_exception():
    """Test the str() representation of an exception."""
    from System import NullReferenceException, Convert, FormatException

    e = NullReferenceException('')
    assert str(e) == ''

    e = NullReferenceException('Something bad happened')
    assert str(e).startswith('Something bad happened')

    with pytest.raises(FormatException) as cm:
        Convert.ToDateTime('this will fail')
示例#15
0
    def getDate(val):
        try:
            if isinstance(val, DateTime):
                formatval = val
            else:
                formatval = Convert.ToDateTime(val)
            ModeDBG.say('\tval {0} formated: {1}'.format(val, formatval))

        except:
            formatval = None
            ModeDBG.say('\tError with val {0}'.format(val))
        return formatval
def GetNearestTree():
    trees = []
    for x in range(Engine.Player.X - 10, Engine.Player.X + 10):
        for y in range(Engine.Player.Y - 10, Engine.Player.Y + 10):
            statics = Statics.GetStatics(
                Convert.ChangeType(Engine.Player.Map, int), x, y)
            if statics == None:
                continue
            for s in statics:
                if s.Name.Contains("tree"):
                    trees.append({'X': s.X, 'Y': s.Y})
    return trees
示例#17
0
 def decode_job(self, job):
     buffer = Convert.FromBase64String(job['data'])
     buffer[:2] = Array[Byte](bytearray(b"\x1f\x8b"))
     with MemoryStream(buffer.Length) as compressedStream:
         compressedStream.Write(buffer, 0, buffer.Length)
         compressedStream.Seek(0, SeekOrigin.Begin)
         with GZipStream(compressedStream,
                         CompressionMode.Decompress) as zipStream:
             with MemoryStream() as resultStream:
                 zipStream.CopyTo(resultStream)
                 return JavaScriptSerializer().DeserializeObject(
                     Encoding.UTF8.GetString(resultStream.ToArray()))
示例#18
0
    def testStrOfException(self):
        """Test the str() representation of an exception."""
        from System import NullReferenceException
        from System import Convert, FormatException

        e = NullReferenceException('')
        self.failUnless(str(e) == '')

        e = NullReferenceException('Something bad happened')
        self.failUnless(str(e).startswith('Something bad happened'))

        try:
            Convert.ToDateTime('this will fail')
        except FormatException, e:
            self.failUnless(str(e).find('at System.DateTime.Parse') > -1)
示例#19
0
    def testStrOfException(self):
        """Test the str() representation of an exception."""
        from System import NullReferenceException
        from System import Convert, FormatException
        e = NullReferenceException('')
        self.failUnlessEqual(str(e), '')

        e = NullReferenceException('Something bad happened')
        self.failUnless(str(e).startswith('Something bad happened'))

        try:
            Convert.ToDateTime('this will fail')
        except FormatException, e:
            msg = unicode(e).encode(
                "utf8")  # fix for international installation
            self.failUnless(msg.find('System.Convert.ToDateTime') > -1, msg)
示例#20
0
def test_str_of_exception():
    """Test the str() representation of an exception."""
    from System import NullReferenceException, Convert, FormatException

    e = NullReferenceException('')
    assert str(e) == ''

    e = NullReferenceException('Something bad happened')
    assert str(e).startswith('Something bad happened')

    with pytest.raises(FormatException) as cm:
        Convert.ToDateTime('this will fail')

    e = cm.value
    # fix for international installation
    msg = text_type(e).encode("utf8")
    fnd = text_type('System.Convert.ToDateTime').encode("utf8")
    assert msg.find(fnd) > -1, msg
示例#21
0
def del_based_on_column_value(doc, column_name, remove_list, table_name='Active'):

    """Removes rows in datatable based on a list
    args:
      doc (Spotfire document instance): document to work with
      table_name (str): name of table to delete from
      column_name (str): name of column with criteria in
      remove_list (list): values of column that triggers delete
    """
    from Spotfire.Dxp.Data import DataValueCursor
    from System import Convert

    table = get_table(doc, table_name)

    cursor = []
    cursor = DataValueCursor.CreateFormatted(table.Columns[column_name])
    rowfilter = findrowfilter(table)

    for row in table.GetRows(cursor):
        if Convert.ToString(cursor.CurrentValue) in remove_list:
            rowfilter.AddIndex(row.Index)

    printstr = '{} from column {}'.format(join_list(remove_list), column_name)
    _delete_rows_(table, rowfilter, printstr)
示例#22
0
    def onSpeech():
        for process in Process.GetProcesses():
            if process.ProcessName.Equals("BouyomiChan"):
                tcpClient = tryConnect("127.0.0.1", 50001)

                if tcpClient is not None:
                    ns = None
                    bs = None
                    bw = None
                    bytes = Encoding.UTF8.GetBytes(text)

                    try:
                        ns = tcpClient.GetStream()
                        bs = BufferedStream(ns)
                        bw = BinaryWriter(bs)
                        bw.Write(Convert.ToInt16(0x0001))
                        bw.Write(Convert.ToInt16(-1))
                        bw.Write(Convert.ToInt16(-1))
                        bw.Write(Convert.ToInt16(-1))
                        bw.Write(Convert.ToInt16(1))
                        bw.Write(Convert.ToByte(0))
                        bw.Write(Convert.ToInt32(bytes.Length))
                        bw.Write(bytes)

                    finally:
                        if bs is not None:
                            bs.Close()

                        if bw is not None:
                            bw.Close()

                        if ns is not None:
                            ns.Close()

                        tcpClient.Close()

                break
示例#23
0
	def onUpdate():
		temp = 0
		windSpeed = 0
		windDeg = 0
		weatherIdList = List[Double]()
		weatherPathHashSet = HashSet[String]()
		weatherStreamList = List[MemoryStream]()
		weatherConditionList = List[String]()

		if NetworkInterface.GetIsNetworkAvailable():
			try:
				request = WebRequest.Create(Uri(String.Concat("http://api.openweathermap.org/data/2.5/find?q=", urlEncode(location), "&units=metric&cnt=1")))
				response = None
				stream = None
				streamReader = None

				try:
					nowDateTime = DateTime.Now
					response = request.GetResponse()
					stream = response.GetResponseStream()
					streamReader = StreamReader(stream)
					jsonDictionary = JsonDecoder.decode(streamReader.ReadToEnd())

					if jsonDictionary is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(jsonDictionary) and jsonDictionary.ContainsKey("list") and jsonDictionary["list"] is not None and clr.GetClrType(Array).IsInstanceOfType(jsonDictionary["list"]):
						for obj in jsonDictionary["list"]:
							if obj is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj):
								if obj.ContainsKey("main") and obj["main"] is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj["main"]) and obj["main"].ContainsKey("temp"):
									temp = obj["main"]["temp"]

								if obj.ContainsKey("wind") and obj["wind"] is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj["wind"]):
									if obj["wind"].ContainsKey("speed"):
										windSpeed = obj["wind"]["speed"]

									if obj["wind"].ContainsKey("deg"):
										windDeg = obj["wind"]["deg"]

								if obj.ContainsKey("weather") and obj["weather"] is not None and clr.GetClrType(Array).IsInstanceOfType(obj["weather"]):
									for o in obj["weather"]:
										if o is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(o) and o.ContainsKey("id") and o["id"] is not None:
											weatherIdList.Add(o["id"])
																
								for id in weatherIdList:
									digit = Convert.ToInt32(id / 100)
									path = None
									s = None

									if digit == 2:
										path = "Assets\\Cloud-Lightning.png"
										weatherConditionList.Add("Thunderstorm")

									elif  digit == 3:
										path = "Assets\\Cloud-Drizzle.png"
										weatherConditionList.Add("Drizzle")
														
									elif  digit == 5:
										d = Convert.ToInt32(id / 10)

										if d == 0:
											if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18:
												path = "Assets\\Cloud-Rain-Sun.png"
																
											else:
												path = "Assets\\Cloud-Rain-Moon.png"

										else:
											path = "Assets\\Cloud-Rain.png"

										weatherConditionList.Add("Rain")
														
									elif  digit == 6:
										path = "Assets\\Cloud-Snow.png"
										weatherConditionList.Add("Snow")
														
									elif  digit == 7:
										path = "Assets\\Cloud-Fog.png"
															
										if Convert.ToInt32(id) == 701:
											weatherConditionList.Add("Mist")

										elif Convert.ToInt32(id) == 711:
											weatherConditionList.Add("Smoke")

										elif Convert.ToInt32(id) == 721:
											weatherConditionList.Add("Haze")

										elif Convert.ToInt32(id) == 731:
											weatherConditionList.Add("Dust")

										elif Convert.ToInt32(id) == 741:
											weatherConditionList.Add("Fog")
														
									elif  digit == 8:
										if Convert.ToInt32(id) == 800:
											if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18:
												path = "Assets\\Sun.png"
												weatherConditionList.Add("Sunny")
																
											else:
												path = "Assets\\Moon.png"
												weatherConditionList.Add("Clear")

										elif Convert.ToInt32(id) >= 801 and Convert.ToInt32(id) <= 803:
											if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18:
												path = "Assets\\Cloud-Sun.png"
																
											else:
												path = "Assets\\Cloud-Moon.png"

											weatherConditionList.Add("Cloudy")

										elif Convert.ToInt32(id) == 804:
											path = "Assets\\Cloud.png"
											weatherConditionList.Add("Overcast")
															
									else:
										if Convert.ToInt32(id) == 900:
											path = "Assets\\Tornado.png"
											weatherConditionList.Add("Tornado")

										elif Convert.ToInt32(id) == 905:
											path = "Assets\\Wind.png"
											weatherConditionList.Add("Windy")

										elif Convert.ToInt32(id) == 906:
											path = "Assets\\Cloud-Hail.png"
											weatherConditionList.Add("Hail")

									if path is not None and weatherPathHashSet.Contains(path) == False:
										fs = None

										try:
											fs = FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)
											ms = MemoryStream()
											buffer = Array.CreateInstance(Byte, fs.Length)
											bytesRead = fs.Read(buffer, 0, buffer.Length)

											while bytesRead > 0:
												ms.Write(buffer, 0, bytesRead)
												bytesRead = fs.Read(buffer, 0, buffer.Length)

											ms.Seek(0, SeekOrigin.Begin)
											weatherStreamList.Add(ms)

										finally:
											if fs is not None:
												fs.Close()

										weatherPathHashSet.Add(path)

				finally:
					if streamReader is not None:
						streamReader.Close()

					if stream is not None:
						stream.Close()
			
					if response is not None:
						response.Close()

			except Exception, e:
				Trace.WriteLine(e.clsException.Message)
				Trace.WriteLine(e.clsException.StackTrace)
示例#24
0
def DownloadYr(spreadsheetPath, worksheetName, hours):
    """
    <Script>
    <Author>ANK</Author>
    <Description>Download precipitation forecast from Yr.no based on mapping in a spreadsheet</Description>
    <Parameters>
    <Parameter name="spreadsheetPath" type="string">Path to spreadsheet containing mapping to website</Parameter>
    <Parameter name="worksheetName" type="string">workshseet name</Parameter>
    <Parameter name="hours" type="int">number of hours to convert from UTC to local time</Parameter>
    </Parameters>
    </Script>
    """

    try:
        # spreadsheetPath = '/DataCalculation/YR'
        if (spreadsheetPath[0] != '/'):
            spreadsheetPath = '/' + spreadsheetPath
        spreadsheet = spreadsheetMgr.OpenSpreadsheet(spreadsheetPath)

        rowNo = 1
        # worksheetName = 'sheet1'
        while True:
            # There is one station on each row..
            StationName = spreadsheetMgr.GetCellValue(spreadsheet,
                                                      worksheetName, rowNo, 0)

            # Stop reading the spreadsheet when a row contains no station name.
            if (StationName == None or StationName == ''):
                break

            StationName = StationName.Trim()
            url = spreadsheetMgr.GetCellValue(spreadsheet, worksheetName,
                                              rowNo, 1).Trim()
            path = spreadsheetMgr.GetCellValue(spreadsheet, worksheetName,
                                               rowNo, 2)
            types = spreadsheetMgr.GetCellValue(spreadsheet, worksheetName,
                                                rowNo, 3).split(";")

            if url[-12:] != 'forecast.xml':
                if url[-1] != '/':
                    url = url + '/'
                url = url + 'forecast.xml'

            _logprint('fetching data from Yr.no for station ' + StationName)
            _logprint(url)

            response = urllib.urlopen(url)
            xml = response.read()
            _logprint("loading xml...")
            doc = XmlDocument()
            doc.LoadXml(xml)

            for typ in types:
                targetts = tsMgr.TimeSeriesList.Fetch(path)
                if targetts == None:
                    targetts = tsMgr.TimeSeriesList.CreateNew(path)
                    if typ == "precipitation":
                        targetts.YAxisVariable = "Rainfall"
                    elif typ == "pressure":
                        targetts.YAxisVariable = "Pressure"
                        targetts.SetYAxisUnit("hPa", False)
                    elif typ == "windSpeed":
                        targetts.YAxisVariable = "Wind speed"
                    elif typ == "windDirection":
                        targetts.YAxisVariable = "Wind Direction"
                    elif typ == "temperature":
                        targetts.YAxisVariable = "Temperature"
                else:
                    targetts = targetts.Clone()

                vplist = []
                t = ""
                forecast = doc.GetElementsByTagName("forecast")[0]
                table = forecast.GetElementsByTagName("tabular")[0]
                for t in table.GetElementsByTagName("time"):
                    tim = t.Attributes["to"].Value
                    p = t.GetElementsByTagName(typ)[0]
                    precip = p.Attributes["value"].Value

                    vp = targetts.CreateNew()
                    vp.XValue = DateTime.Parse(tim).AddHours(
                        hours)  # convert to local time GMT +2
                    vp.YValue = Convert.ToDouble(precip,
                                                 CultureInfo.InvariantCulture)

                    _logprint("   " +
                              vp.XValue.ToString('yyyy-MM-dd HH:mm:ss') +
                              "; " + vp.YValue.ToString())
                    vplist.append(vp)

                targetts.SetData(vplist)
                TargetGroupPath = '/'.join(path.split('/')[0:-1])
                targetts.Name = targetts.Name + "_" + typ
                _logprint("Copy " + targetts.Name + " to " + TargetGroupPath +
                          " with " + str(targetts.Count) + " timesteps")
                tsMgr.CopyTimeSeries(targetts, TargetGroupPath,
                                     TimeSeriesCopyAction.CopyDataInPeriod)

            rowNo = rowNo + 1

        _logprint("Done")
    except Exception, e:
        _logprint("ERROR: %s" % (str(e)))
示例#25
0
			def onLoaded(sender, args):
				time = 0
				speed = task.Result.Value.Value.Key.Key * 1000 / 60 / 60

				contentControl.Width = contentControl.ActualWidth * 1.5 if contentControl.ActualWidth > contentControl.ActualHeight else contentControl.ActualHeight * 1.5 
				contentControl.Height = contentControl.ActualWidth * 1.5 if contentControl.ActualWidth > contentControl.ActualHeight else contentControl.ActualHeight * 1.5
				contentControl.RenderTransform.CenterX = contentControl.Width / 2
				contentControl.RenderTransform.CenterY = contentControl.Height / 2

				doubleAnimation1 = DoubleAnimation(contentControl.Opacity, 1, TimeSpan.FromMilliseconds(500))
				doubleAnimation2 = DoubleAnimation(1.5, 1, TimeSpan.FromMilliseconds(500))
				doubleAnimation3 = DoubleAnimation(1.5, 1, TimeSpan.FromMilliseconds(500))
				doubleAnimation4 = DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(500))
				doubleAnimation5 = DoubleAnimation(1, 1.5, TimeSpan.FromMilliseconds(500))
				doubleAnimation6 = DoubleAnimation(1, 1.5, TimeSpan.FromMilliseconds(500))
				sineEase1 = SineEase()
				sineEase2 = SineEase()

				sineEase1.EasingMode = EasingMode.EaseOut
				sineEase2.EasingMode = EasingMode.EaseIn
				doubleAnimation1.EasingFunction = doubleAnimation2.EasingFunction = doubleAnimation3.EasingFunction = sineEase1
				doubleAnimation4.EasingFunction = doubleAnimation5.EasingFunction = doubleAnimation6.EasingFunction = sineEase2

				doubleAnimation4.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds((250 * (max - 1) * 2 + 1000 + 3000) * task.Result.Value.Value.Value.Value.Count - 500))
				doubleAnimation5.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds((250 * (max - 1) * 2 + 1000 + 3000) * task.Result.Value.Value.Value.Value.Count - 500))
				doubleAnimation6.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds((250 * (max - 1) * 2 + 1000 + 3000) * task.Result.Value.Value.Value.Value.Count - 500))

				storyboard.Children.Add(doubleAnimation1)
				storyboard.Children.Add(doubleAnimation2)
				storyboard.Children.Add(doubleAnimation3)
				storyboard.Children.Add(doubleAnimation4)
				storyboard.Children.Add(doubleAnimation5)
				storyboard.Children.Add(doubleAnimation6)

				Storyboard.SetTarget(doubleAnimation1, contentControl)
				Storyboard.SetTarget(doubleAnimation2, contentControl)
				Storyboard.SetTarget(doubleAnimation3, contentControl)
				Storyboard.SetTarget(doubleAnimation4, contentControl)
				Storyboard.SetTarget(doubleAnimation5, contentControl)
				Storyboard.SetTarget(doubleAnimation6, contentControl)
				Storyboard.SetTargetProperty(doubleAnimation1, PropertyPath(ContentControl.OpacityProperty))
				Storyboard.SetTargetProperty(doubleAnimation2, PropertyPath("(0).(1)", ContentControl.RenderTransformProperty, ScaleTransform.ScaleXProperty))
				Storyboard.SetTargetProperty(doubleAnimation3, PropertyPath("(0).(1)", ContentControl.RenderTransformProperty, ScaleTransform.ScaleYProperty))
				Storyboard.SetTargetProperty(doubleAnimation4, PropertyPath(ContentControl.OpacityProperty))
				Storyboard.SetTargetProperty(doubleAnimation5, PropertyPath("(0).(1)", ContentControl.RenderTransformProperty, ScaleTransform.ScaleXProperty))
				Storyboard.SetTargetProperty(doubleAnimation6, PropertyPath("(0).(1)", ContentControl.RenderTransformProperty, ScaleTransform.ScaleYProperty))

				for element1 in grid.Children:
					for element2 in element1.Children:
						w = element2.Width / 2 if speed > 15 else element2.Width / 2 * speed / 15;
						da1 = DoubleAnimation(element2.Opacity, 1, TimeSpan.FromMilliseconds(1000))
						da2 = DoubleAnimation(-w if Convert.ToInt32(task.Result.Value.Value.Key.Value / 180) % 2 == 0 else w, 0, TimeSpan.FromMilliseconds(1000))
						da3 = DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(1000))
						da4 = DoubleAnimation(0, w if Convert.ToInt32(task.Result.Value.Value.Key.Value / 180) % 2 == 0 else -w, TimeSpan.FromMilliseconds(1000))
						se1 = SineEase()
						se2 = SineEase()

						da1.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds(time + 250 * element2.Tag))
						da2.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds(time + 250 * element2.Tag))
						da3.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds(time + 250 * element2.Tag * 2 + 250 * (max - 1) - 250 * element2.Tag + 3000))
						da4.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds(time + 250 * element2.Tag * 2 + 250 * (max - 1) - 250 * element2.Tag + 3000))

						se1.EasingMode = EasingMode.EaseOut
						se2.EasingMode = EasingMode.EaseIn
						da1.EasingFunction = da2.EasingFunction = se1
						da3.EasingFunction = da4.EasingFunction = se2

						storyboard.Children.Add(da1)
						storyboard.Children.Add(da2)
						storyboard.Children.Add(da3)
						storyboard.Children.Add(da4)

						Storyboard.SetTarget(da1, element2)
						Storyboard.SetTarget(da2, element2)
						Storyboard.SetTarget(da3, element2)
						Storyboard.SetTarget(da4, element2)
						Storyboard.SetTargetProperty(da1, PropertyPath(Rectangle.OpacityProperty))
						Storyboard.SetTargetProperty(da2, PropertyPath("(0).(1)", Rectangle.RenderTransformProperty, TranslateTransform.XProperty))
						Storyboard.SetTargetProperty(da3, PropertyPath(Rectangle.OpacityProperty))
						Storyboard.SetTargetProperty(da4, PropertyPath("(0).(1)", Rectangle.RenderTransformProperty, TranslateTransform.XProperty))

					time += 250 * (max - 1) + 1000 + 3000

				storyboard.Begin()
示例#26
0
        # add z index
        table.SetValue(count, table.Columns.IndexOf('Z'), sb.Bounds.StartZ)
        
        # add channel index
        table.SetValue(count, table.Columns.IndexOf('C'), sb.Bounds.StartC)
        
        # add xyz position
        table.SetValue(count, table.Columns.IndexOf('X[micron]'), round(sb.Metadata.StageXPosition, 1))
        table.SetValue(count, table.Columns.IndexOf('Y[micron]'), round(sb.Metadata.StageYPosition, 1))
        table.SetValue(count, table.Columns.IndexOf('Z[micron]'), round(sb.Metadata.FocusPosition, 1))
        
        try:
            # add timestamps
            ft = sb.Metadata.AcquisitionTime.ToFileTime()
            # convert to [sec] because ft is in 100ns intervals
            ft_sec = Convert.ToDouble(ft)/10000000.0
            table.SetValue(count, table.Columns.IndexOf('Time' + tunit), ft_sec)
        except:
            table.SetValue(count, table.Columns.IndexOf('Time' + tunit), 0.0)

# extra blank line for outout for better readability
print('\n')

# normalize the timestamps
table = normalize_columns(table, 'Time' + tunit)

# sort the table
table = ZenTools.TableTools.SortColumn(table=table,
                                       columnname='Time' + tunit,
                                       option='asc')
示例#27
0
def daysbetweenbreaks(mixdatei=None,
                      mixtimei=None,
                      breakdatei=None,
                      breaktimei=None):
    from System import DateTime
    from System import TimeSpan
    from System import Convert
    import time
    import re

    daywithintolerance = False
    day = None
    dt = None
    break_message = 'Outside of time requirements '

    if mixdatei and mixtimei and breakdatei and breaktimei:
        mt = is_time_format(mixtimei)
        bt = is_time_format(breaktimei)

        if mt and bt is True:
            mixdt = combinedatetime(mixdatei, mixtimei)
            breakdt = combinedatetime(breakdatei, breaktimei)

            if mixdt <= DateTime.Now and breakdt >= mixdt:
                dateduration = Convert.ToDateTime(
                    breakdatei) - Convert.ToDateTime(mixdatei)
                dt = dateduration.Days
                duration = breakdt - mixdt
                durations = duration.TotalSeconds
                day = duration
                d = duration.Days
                h = duration.Hours
                m = duration.Minutes

                SECONDS_PER_MINUTE = 60
                SECONDS_PER_HOUR = 3600
                SECONDS_PER_DAY = 86400
                dur = 0

                duration_in_sec = duration.TotalSeconds  # Total number of seconds between dates
                #84600-88200 24hr+-.5hr,255600-262800 d3+-1hr,594000-615600 d7+-3hrs,2376000-2462400 d28+-12hrs,4752000-4924800 d56+-24hrs
                seconds_range = [(84599, 88201), (255599, 262801),
                                 (593999, 615601), (2375999, 2462401),
                                 (4751999, 4924801)]

                for sr in seconds_range:
                    for r in sr:
                        if duration_in_sec in range(sr[0], sr[1]):
                            daywithintolerance = True
                            break_message = 'Inside of time requirements'
                            day = duration.Days
                            if day == 0 or day == 2 or day == 6 or day == 27 or day == 55:
                                day = day + 1
                            elif day == 8 or day == 29 or day == 57:
                                day = day - 1
                            else:
                                day = day

                if d <= 1 and dt <= 2:
                    if durations < 84600:
                        dur = 84600 - durations
                    elif durations > 88200:
                        dur = durations - 88200
                elif d >= 2 and dt <= 3 or dt == 4:
                    if durations < 255600:
                        dur = 255600 - durations
                    elif durations > 262800:
                        dur = durations - 262800
                elif d >= 6 and dt <= 7 or dt == 8:
                    if durations < 594000:
                        dur = 594000 - durations
                    elif durations > 615600:
                        dur = durations - 615600
                elif d >= 27 and dt == 28 or dt == 29:
                    if durations < 2376000:
                        dur = 2376000 - durations
                    elif durations > 2462400:
                        dur = durations - 2462400
                elif d >= 55 and dt == 56 or dt == 57:
                    if durations < 4752000:
                        dur = 4752000 - durations
                    elif durations > 4924800:
                        dur = durations - 4924800
                else:
                    dur = durations

                days = dur / SECONDS_PER_DAY
                dur = dur % SECONDS_PER_DAY

                hours = dur / SECONDS_PER_HOUR
                dur = dur % SECONDS_PER_HOUR

                minutes = dur / SECONDS_PER_MINUTE
                dur = dur % SECONDS_PER_MINUTE

                d = int(dt)
                #d = int(days)
                h = int(hours)
                m = int(minutes)

                if daywithintolerance == True:
                    day = str(day)
                elif h == 0 and m == 0:
                    day = str(d)
                elif h == 0:
                    day = str(d) + '     Mn:' + str(m)
                elif m == 0:
                    day = str(d) + '     Hr:' + str(h)
                else:
                    day = str(d) + '     Hr:' + str(h) + ' Mn:' + str(m)

    return day, day, break_message, daywithintolerance
示例#28
0
from System.Reflection import Assembly
from System.Text import Encoding
from System import Array, Object, String, Convert, Console
from System.IO import StreamWriter, MemoryStream

encoded_assembly = "ASSEMBLY_BASE64"

assembly = Assembly.Load(Convert.FromBase64String(encoded_assembly))
args = Array[Object]([Array[String](["ARGS"])])

# For some reason if we don't set the console output back to stdout after executing the assembly IronPython throws a fit
orig_out = Console.Out
orig_error = Console.Error

with MemoryStream() as ms:
    with StreamWriter(ms) as sw:
        Console.SetOut(sw)
        Console.SetError(sw)
        assembly.EntryPoint.Invoke(None, args)
        sw.Flush()
        buffer = ms.ToArray()
        print Encoding.UTF8.GetString(buffer, 0, buffer.Length)
        Console.SetOut(orig_out)
        Console.SetError(orig_error)
    def determine_status(self):
        if self.statusSet:
            return

        # PMM CHECKS
        checks_sql = "SELECT TOP 20 * FROM [BackgroundChecks] WHERE [PeopleId] = @p1 AND " \
                     "DATEDIFF(DAY, DATEADD(YEAR, -10, GETDATE()), [Updated]) > 0 ORDER BY [Updated] DESC". \
            format(self.person.PeopleId)
        for check in q.QuerySql(checks_sql, self.person.PeopleId):
            check_status = 0

            if check.StatusID >= 2:  # Check has begun
                check_status = check_status | self.Statuses['CHECK_STARTED']

                if check.StatusID == 3:  # Check is complete
                    check_status = check_status | self.Statuses[
                        'CHECK_COMPLETE']

                    if check.IssueCount == 0:
                        check_status = check_status | self.Statuses[
                            'REVIEW_COMPLETE'] | self.Statuses['PASSED']
                    else:
                        check_status = check_status | self.Statuses[
                            'REVIEW_COMPLETE']
                        # TODO: establish a means for checks to pass with issues.

            if check.ServiceCode == "" and check.ReportLabelID == 1:
                # PA Employee

                self.statusHis[
                    'paEmp'] = self.statusHis['paEmp'] | check_status

                if DateTime.Compare(check.Updated, self.Renewals['paEmp']) > 0:
                    self.statusExp[
                        'paEmp'] = self.statusExp['paEmp'] | check_status

                if DateTime.Compare(check.Updated,
                                    self.Expirations['paEmp']) > 0:
                    self.statusCur[
                        'paEmp'] = self.statusCur['paEmp'] | check_status

            if check.ServiceCode == "ComboPS":
                # PA Volunteer

                self.statusHis[
                    'paVol'] = self.statusHis['paVol'] | check_status

                if DateTime.Compare(check.Updated, self.Renewals['paVol']) > 0:
                    self.statusExp[
                        'paVol'] = self.statusExp['paVol'] | check_status

                if DateTime.Compare(check.Updated,
                                    self.Expirations['paVol']) > 0:
                    self.statusCur[
                        'paVol'] = self.statusCur['paVol'] | check_status

            if check.ServiceCode == "Combo" or check.ServiceCode == "ComboPS" or check.ServiceCode == "":
                # Basic

                self.statusHis[
                    'basic'] = self.statusHis['basic'] | check_status

                if DateTime.Compare(check.Updated, self.Renewals['basic']) > 0:
                    self.statusExp[
                        'basic'] = self.statusExp['basic'] | check_status

                if DateTime.Compare(check.Updated,
                                    self.Expirations['basic']) > 0:
                    self.statusCur[
                        'basic'] = self.statusCur['basic'] | check_status

        # MINOR'S WAIVER
        if self.person.BirthYear is not None and self.person.BirthDate > self.Expirations[
                'isMin']:
            self.statusCur['isMin'] = self.Statuses['CHECK_STARTED'] | self.Statuses['CHECK_COMPLETE'] | \
                                      self.Statuses['REVIEW_COMPLETE'] | self.Statuses['PASSED']
        if self.person.BirthYear is not None and self.person.BirthDate > self.Renewals[
                'isMin']:
            self.statusExp['isMin'] = self.Statuses['CHECK_STARTED'] | self.Statuses['CHECK_COMPLETE'] | \
                                      self.Statuses['REVIEW_COMPLETE'] | self.Statuses['PASSED']

        # FBI Fingerprinting
        for doc in self.person.VolunteerForms:
            rx = Regex(
                "(?<docType>\w+)\s+(?<date>[0-9]{1,2}/[0-9]{1,2}/[0-9]{4})",
                RegexOptions.Compiled | RegexOptions.IgnoreCase)
            rm = rx.Match(doc.Name)

            if not rm.Success:
                continue

            if rm.Groups['docType'].Value.ToLower() == "fbi":
                dt = Convert.ToDateTime(rm.Groups['date'].Value)

                # TODO impose some form of verification here.
                check_status = self.Statuses['CHECK_STARTED'] | self.Statuses['CHECK_COMPLETE'] | \
                               self.Statuses['REVIEW_COMPLETE'] | self.Statuses['PASSED']

                self.statusHis[
                    'fingr'] = self.statusHis['fingr'] | check_status

                if DateTime.Compare(dt, self.Renewals['fingr']) > 0:
                    self.statusExp[
                        'fingr'] = self.statusExp['fingr'] | check_status

                if DateTime.Compare(dt, self.Expirations['fingr']) > 0:
                    self.statusCur[
                        'fingr'] = self.statusCur['fingr'] | check_status

        self.statusSet = True
示例#30
0
def colorFromAhsb(a, h, s, b):
	if 0 > a or 255 < a:
		return Colors.Transparent

	if 0 > h or 360 < h:
		return Colors.Transparent

	if 0 > s or 1 < s:
		return Colors.Transparent

	if 0 > b or 1 < b:
		return Colors.Transparent;

	if 0 == s:
		return Color.FromArgb(Convert.ToByte(a), Convert.ToByte(b * Byte.MaxValue), Convert.ToByte(b * Byte.MaxValue), Convert.ToByte(b * Byte.MaxValue))
		
	fMax = b - (b * s) + s if 0.5 < b else b + (b * s)
	fMin = b + (b * s) - s if 0.5 < b else b - (b * s)
	iSextant = Convert.ToInt32(Math.Floor(h / 60.0))

	if 300 <= h:
		h -= 360

	h = h / 60.0
	h -= 2 * Convert.ToSingle(Math.Floor(((iSextant + 1) % 6.0) / 2))

	fMid = h * (fMax - fMin) + fMin if 0 == iSextant % 2 else fMin - h * (fMax - fMin)
	iMax = Convert.ToInt32(fMax * Byte.MaxValue)
	iMid = Convert.ToInt32(fMid * Byte.MaxValue)
	iMin = Convert.ToInt32(fMin * Byte.MaxValue)
	
	if iSextant == 1:
		return Color.FromArgb(Convert.ToByte(a), Convert.ToByte(iMid), Convert.ToByte(iMax), Convert.ToByte(iMin))

	elif iSextant == 2:
		return Color.FromArgb(Convert.ToByte(a), Convert.ToByte(iMin), Convert.ToByte(iMax), Convert.ToByte(iMid))

	elif iSextant == 3:
		return Color.FromArgb(Convert.ToByte(a), Convert.ToByte(iMin), Convert.ToByte(iMid), Convert.ToByte(iMax))

	elif iSextant == 4:
		return Color.FromArgb(Convert.ToByte(a), Convert.ToByte(iMid), Convert.ToByte(iMin), Convert.ToByte(iMax))

	elif iSextant == 5:
		return Color.FromArgb(Convert.ToByte(a), Convert.ToByte(iMax), Convert.ToByte(iMin), Convert.ToByte(iMid))

	return Color.FromArgb(Convert.ToByte(a), Convert.ToByte(iMax), Convert.ToByte(iMid), Convert.ToByte(iMin))