/// <summary> /// Main constructor. /// </summary> /// <param name="KeyID"> /// A <see cref="System.String"/>, the primary key ID. /// </param> /// <param name="SignKey"> /// A <see cref="System.String"/>, the signing key ID. /// </param> /// <param name="SignDate"> /// A <see cref="System.String"/>, the signature date (seconds from Epoch) /// </param> public Signature(string KeyID, string SignKey, string SignDate) { // sig:::17:F4B4B0CC797EBFAB:1223678701::::Enrico Zini <*****@*****.**>:10x: // Console.WriteLine(String.Format("Key: {0} - SignKey: {1} - SignDate: {2}", KeyID, Key, Date)); GPG gpg = new GPG(KeyID, Commands.List); gpg.Exec(); foreach (string line in gpg.Output.Split('\n')) { RecordType tag = Utils.GetRecordType(Utils.GetField(line, 0)); if (tag == RecordType.Signature) { string key = Utils.GetField(line, 4); string date = Utils.GetField(line, 5); if ((key == SignKey) && (date == SignDate)) { this._algorithm = Utils.GetAlgorithm(Convert.ToInt32(Utils.GetField(line, 3))); this._user = Utils.ParseUsername(Utils.GetField(line, 9)); this._signingKey = SignKey; this._signingDate = SignDate; // TODO: also parse the "10x" above? The docs give very poor info: /* * 11. Field: Signature class. This is a 2 digit hexnumber followed by * either the letter 'x' for an exportable signature or the * letter 'l' for a local-only signature. * The class byte of an revocation key is also given here, * 'x' and 'l' ist used the same way. */ } } } }
public void SetCurrentlySelected(ListViewItem lvi, ComputeDevice computeDevice) { // should not happen ever if (lvi == null) return; _computeDevice = computeDevice; var algorithm = lvi.Tag as Algorithm; if (algorithm != null) { _selected = true; _currentlySelectedAlgorithm = algorithm; _currentlySelectedLvi = lvi; this.Enabled = lvi.Checked; groupBoxSelectedAlgorithmSettings.Text = String.Format(International.GetText("AlgorithmsListView_GroupBox"), algorithm.GetName()); ; field_LessThreads.Enabled = _computeDevice.DeviceGroupType == DeviceGroupType.CPU; if (field_LessThreads.Enabled) { field_LessThreads.EntryText = algorithm.LessThreads.ToString(); } fieldBoxBenchmarkSpeed.EntryText = ParseDoubleDefault(algorithm.BenchmarkSpeed); richTextBoxExtraLaunchParameters.Text = ParseStringDefault(algorithm.ExtraLaunchParameters); this.Update(); } else { // TODO this should not be null } }
static void Main(string[] args) { var line = Console.ReadLine(); var segments = line.Split(' '); var Rows = Convert.ToInt32(segments[0]); var Columns = Convert.ToInt32(segments[1]); var rotations = Convert.ToInt32(segments[2]); var matrix = new int[Rows][]; for (int i = 0; i < Rows; i++) { line = Console.ReadLine(); segments = line.Split(' '); matrix[i] = new int[segments.Length]; for (int t = 0; t < segments.Length; t++) { matrix[i][t] = Convert.ToInt32(segments[t]); } } var algorithm = new Algorithm(); algorithm.Process(matrix, rotations); }
public Generator(string data) { byte[] d = Convert.FromBase64String(data); string strXML = Encoding.UTF8.GetString(d); XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(strXML); XmlNode root = doc.SelectSingleNode("/vmp-lm-product"); if (root == null) throw new ArgumentException("Invalid data: not a product information string"); XmlNode attrProduct = root.SelectSingleNode("@product"); if (attrProduct == null) throw new ArgumentException("Invalid data: information about product is missed"); pProductCode = Convert.FromBase64String(attrProduct.Value); if (pProductCode.Length != 8) throw new ArgumentException("Invalid data: product code has incorrect length"); XmlNode nodeAlgo = root.SelectSingleNode("@algorithm"); if (nodeAlgo == null) throw new ArgumentException("Invalid data: missed encryption algorithm"); switch (nodeAlgo.Value) { case "RSA": algo = new AlgorithmRSA(root); break; default: throw new ArgumentException("Invalid data: unsupported encryption algorithm"); } }
public static void ShowResults(Algorithm.MMatrixAlgorithm algorithm) { ResultsForm form = new ResultsForm(); form.m_Algorithm = algorithm; form.ShowDialog(); }
public void Main() { var m = new Algorithm(); m.TemplateMethod(new ClassA()); m.TemplateMethod(new ClassB()); }
public override void Start(Algorithm miningAlgorithm, string url, string username) { CurrentMiningAlgorithm = miningAlgorithm; if (miningAlgorithm == null) return; string algo = ""; string apiBind = ""; string intensity = ""; if (CurrentMiningAlgorithm.NiceHashID != AlgorithmType.CryptoNight) { algo = "--algo=" + miningAlgorithm.MinerName; apiBind = " --api-bind=" + APIPort.ToString(); intensity = getIntensityString(); } IsAPIReadException = CurrentMiningAlgorithm.NiceHashID == AlgorithmType.CryptoNight; LastCommandLine = algo + " --url=" + url + " --userpass="******":" + Algorithm.PasswordDefault + apiBind + " " + miningAlgorithm.ExtraLaunchParameters + intensity + " --devices "; LastCommandLine += GetDevicesCommandString(); Path = GetOptimizedMinerPath(miningAlgorithm.NiceHashID); ProcessHandle = _Start(); }
static void Main(string[] args) { var t = Convert.ToInt32(Console.ReadLine()); var algorithm = new Algorithm(); var nodes = new int[t][]; for (int i = 0; i < t; i++) { var childNodes = Console.ReadLine().Split(' '); nodes[i] = new int[] { Convert.ToInt32(childNodes[0]), Convert.ToInt32(childNodes[1]) }; } algorithm.BuildTree(nodes); var s = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < s; i++) { var swaps = Convert.ToInt32(Console.ReadLine()); algorithm.SwapTree(swaps); algorithm.PrintTreeInOrder(); } }
/// <summary> /// Creates a new private key. /// </summary> /// <param name="keyProvider">The provider for the key. <see cref="KeyProviders"/> contains different types of providers.</param> /// <param name="keyName">The name of the key to persist. Use <c>null</c> to create an ephemeral key.</param> /// <param name="algorithm">The algorithm of the key. Not all providers support all algorithms.</param> /// <param name="keyUsage">Specifies the purpose of the key. This is not appicable to CNG algorithms.</param> /// <param name="keySize">The size of the key. Only valid for RSA keys.</param> /// <param name="overwrite">True to overwrite the provider's exisint private key, otherwise false.</param> /// <returns>A new private key.</returns> public static PrivateKey CreateNew(KeyProviderBase keyProvider, string keyName, Algorithm algorithm, KeyUsage keyUsage, int? keySize = null, bool overwrite = false) { var keySizeValue = keySize ?? 2048; KeySpec keySpec; var handle = keyProvider.CreateKey(keyName, keySizeValue, algorithm, overwrite, keyUsage, out keySpec); return new PrivateKey(handle, keyProvider, keySpec); }
public void GetHashFile(Algorithm algorithm, bool useNullFile) { FileInfo file = null; if (!useNullFile) { string tempFile = Path.GetTempFileName(); using (var sw = new StreamWriter(tempFile, false)) { for (int i = 0; i < 100; i++) { sw.Write(GenerateText(10, 500)); sw.Write(" "); } } file = new FileInfo(tempFile); } string hashed = DataHashing.Compute(algorithm, file); Assert.IsTrue(DataHashing.Validate(algorithm, file, hashed)); if (!useNullFile) { file.Delete(); } }
protected override string GetBenchmarkCommandStringPart(ComputeDevice benchmarkDevice, Algorithm algorithm) { return " --opencl --opencl-platform " + GPUPlatformNumber + " " + algorithm.ExtraLaunchParameters + " --benchmark-warmup 40 --benchmark-trial 20" + " --opencl-devices "; }
public MiningAlgorithm(ComputeDevice dev, Algorithm algo) { this.AlgoRef = algo; // init speed that will be avaraged later this.AvaragedSpeed = algo.BenchmarkSpeed; this.MinerPath = MinerPaths.GetOptimizedMinerPath(dev, algo); }
public EncryptedAttribute( string key, string salt, Algorithm algorithm = Crypt.Algorithm.Rijndael ) { var db = new Rfc2898DeriveBytes( key, Encoding.ASCII.GetBytes( salt ), 2 ); this.Algorithm = algorithm; this.Key = db.GetBytes( KeySize( this.Algorithm ) / 8 ); this.Vector = db.GetBytes( 16 ); }
// create miner creates new miners based on device type and algorithm/miner path public static Miner CreateMiner(ComputeDevice device, Algorithm algorithm) { var minerPath = MinerPaths.GetOptimizedMinerPath(device, algorithm); if (minerPath != MinerPaths.NONE) { return CreateMiner(device.DeviceType, minerPath); } return null; }
public Symmetric(Algorithm mode, int keySize) { if (IsKeySizeValid(keySize, mode) == false) throw new ArgumentException("The given keySize is invalid.", "keySize"); this._Mode = mode; this._KeySize = keySize; Init(); }
public static void ShowResults(Algorithm.DynAlgorithm algorithm) { ResultsForm form = new ResultsForm(); form.m_Algorithm = algorithm; form.edtResults.Text = algorithm.GetResults(); form.ShowDialog(); }
public SolutionStepCompletedEventArgs(string step, bool finished, Algorithm moves, int milliseconds, SolutionStepType type = SolutionStepType.Standard) { this.Step = step; this.Finished = finished; this.Algorithm = moves; this.Milliseconds = milliseconds; this.Type = type; }
public void Copy(Work work) { hashStart = work.hashStart; hashCount = work.hashCount; hashAlgorithm = work.hashAlgorithm; Array.Copy(work.target, target, 8); Array.Copy(work.data, data, 32); }
public void GetHash(Algorithm algorithm, bool useNullString, bool useNullEncoding) { string normalText = useNullString ? null : GenerateText(100, 500); Encoding encoding = useNullEncoding ? null : Encoding.UTF8; string hashed = DataHashing.Compute(algorithm, normalText, encoding); Assert.IsTrue(DataHashing.Validate(algorithm, normalText, hashed, encoding)); }
public EncryptedAttribute( Algorithm algorithm = Crypt.Algorithm.Rijndael ) { var key = AlpacaConfiguration.Settings.EncryptionKey; var salt = AlpacaConfiguration.Settings.EncryptionSalt; var db = new Rfc2898DeriveBytes( key, Encoding.ASCII.GetBytes( salt ), 2 ); this.Algorithm = algorithm; this.Key = db.GetBytes( KeySize( this.Algorithm ) / 8 ); this.Vector = db.GetBytes( 16 ); }
// *** METHODS *** /// <summary> /// Returns the solution for the transferred Rubik /// </summary> /// <param name="cube">Defines the Rubik to be solved</param> protected virtual void Solve(Rubik cube) { Rubik = cube.DeepClone(); Algorithm = new Algorithm(); InitStandardCube(); GetSolution(); RemoveUnnecessaryMoves(); }
protected override string GetBenchmarkCommandStringPart(Algorithm algorithm) { return " --benchmark-warmup 40 --benchmark-trial 20" + " " + ExtraLaunchParametersParser.ParseForMiningSetup( MiningSetup, DeviceType.NVIDIA) + " --cuda --cuda-devices "; }
public static void Main(string[] args) { if(args.Length != 2) { Console.WriteLine("Please use 2 arguments: splits/train# splits/test#"); return; } string train = args[0]; string test = args[1]; string dir = Path.GetDirectoryName(Path.GetDirectoryName(train)); string dataPath = Path.Combine(dir, "data"); //DateTime start = DateTime.Now; // First, pull in all of the training files and store it in memory string[] files = File.ReadAllLines(train); Dictionary<string, string> examples = new Dictionary<string, string>(files.Length); foreach (string file in files) examples.Add(file, File.ReadAllText(Path.Combine(dataPath, file))); // Next, grab all of the test files and reall it all files = File.ReadAllLines(test); Dictionary<string, string> tests = new Dictionary<string, string>(files.Length); foreach (string file in files) tests.Add(file, File.ReadAllText(Path.Combine(dataPath, file))); Algorithm algo = new Algorithm(); /* * Train the naive bayes algorithm to place weights on words * and classify these words for various labels based on * the training data. */ algo.LearnNaiveBayesText(examples, LABELS); /* * Classify the test data based on the trained algorithm. */ algo.Classify(tests, LABELS); //Console.WriteLine("This took: {0:s}", (DateTime.Now - start)); // Output the results (can be pipe-directed to a file) foreach (KeyValuePair<string, string> entry in algo.classification) Console.WriteLine(entry.Key + " " + entry.Value); //Test.TestPath(); //Test.TestSet(); //Test.TestRegex(); //Test.TestDictionarySort(); //Console.WriteLine("Done, press enter to exit."); //Console.ReadLine(); }
protected override string GetBenchmarkCommandStringPart(Algorithm algorithm) { return " --opencl --opencl-platform " + GPUPlatformNumber + " " + ExtraLaunchParametersParser.ParseForMiningSetup( MiningSetup, DeviceType.AMD) + " --benchmark-warmup 40 --benchmark-trial 20" + " --opencl-devices "; }
protected override string GetStartCommandStringPart(Algorithm miningAlgorithm, string url, string username) { // set directory WorkingDirectory = ""; return " --opencl --opencl-platform " + GPUPlatformNumber + " " + miningAlgorithm.ExtraLaunchParameters + " -S " + url.Substring(14) + " -O " + username + ":" + Algorithm.PasswordDefault + " --api-port " + APIPort.ToString() + " --opencl-devices "; }
public static string Decrypt(this string identifier, Algorithm algorithm, string key, EncodingType encType) { Cypher cypher = new Cypher(); cypher.EncryptionAlgorithm = algorithm; cypher.Encoding = encType; if (key != null) cypher.Key = key; return cypher.Decrypt(identifier); }
/*-------------------------------------------------------------------------------------------------------------*/ /** <summary> * Sets the current algorithm used in the scene. </summary> * <param name="algorithm"> The <see cref="Algorithm"/> object to initiate </param> */ public static void Start_algorithm(Algorithm algorithm) { //set this to the current algorithm SceneController.algorithm = algorithm; //remove the start menu from the scene gui_controller.Remove_display ("StartMenu"); //start setting up the scene with the algorithm algorithm.Initiate_algorithm(); }
public Symmetric(Algorithm mode, int keySize, string salt) { if (String.IsNullOrEmpty(salt)) throw new ArgumentException("salt is null or empty.", "salt"); if (IsKeySizeValid(keySize, mode) == false) throw new ArgumentException("The given keySize is invalid.", "keySize"); this._Mode = mode; this._KeySize = keySize; this._Salt = salt; Init(); }
public bool VerifyHash(string plainText, Algorithm hashAlgorithm, string hashValue) { // Convert base64-encoded hash value into a byte array. var hashWithSaltBytes = Convert.FromBase64String(hashValue); // We must know size of hash (without salt). int hashSizeInBits; // Size of hash is based on the specified algorithm. switch (hashAlgorithm) { case Algorithm.SHA1: hashSizeInBits = 160; break; case Algorithm.SHA256: hashSizeInBits = 256; break; case Algorithm.SHA384: hashSizeInBits = 384; break; case Algorithm.SHA512: hashSizeInBits = 512; break; default: // Must be MD5 hashSizeInBits = 128; break; } // Convert size of hash from bits to bytes. var hashSizeInBytes = hashSizeInBits / 8; // Make sure that the specified hash value is long enough. if (hashWithSaltBytes.Length < hashSizeInBytes) return false; // Allocate array to hold original salt bytes retrieved from hash. var saltBytes = new byte[hashWithSaltBytes.Length - hashSizeInBytes]; // Copy salt from the end of the hash to the new array. for (var i = 0; i < saltBytes.Length; i++) saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i]; // Compute a new hash string. var expectedHashString = Hash(plainText, hashAlgorithm, saltBytes); // If the computed hash matches the specified hash, // the plain text value must be correct. return (hashValue == expectedHashString); }
public void GenerateTestData() { Clear(); int lenght = 100;//--******!! int max = 10; dataPoints = new DataP3[lenght]; Algorithm.GenerateTestData(ref dataPoints, lenght, max); if (algorithm == null) algorithm = Algorithm.getInstance(ref dataPoints); else algorithm.Init(ref dataPoints); }
public static string ParseForMiningPairs(List <MiningPair> MiningPairs, DeviceType deviceType, bool showLog = true) { _showLog = showLog; MinerBaseType minerBaseType = MinerBaseType.NONE; AlgorithmType algorithmType = AlgorithmType.NONE; if (MiningPairs.Count > 0) { var algo = MiningPairs[0].Algorithm; if (algo != null) { algorithmType = algo.NiceHashID; minerBaseType = algo.MinerBaseType; } } MinerType minerType = GetMinerType(deviceType, minerBaseType, algorithmType); MinerOptionPackage minerOptionPackage = ExtraLaunchParameters.GetMinerOptionPackageForMinerType(minerType); List <MiningPair> setMiningPairs = MiningPairs.ConvertAll((mp) => mp); // handle exceptions and package parsing // CPU exception if (deviceType == DeviceType.CPU && minerType != MinerType.Xmrig) { CheckAndSetCPUPairs(setMiningPairs); } // ethminer exception if (MinerType.ethminer_OCL == minerType || MinerType.ethminer_CUDA == minerType) { // use if missing compute device for correct mapping // init fakes workaround var cdevs_mappings = new List <MiningPair>(); { int id = -1; var fakeAlgo = new Algorithm(MinerBaseType.ethminer, AlgorithmType.DaggerHashimoto, "daggerhashimoto"); foreach (var pair in setMiningPairs) { while (++id != pair.Device.ID) { var fakeCdev = new ComputeDevice(id); cdevs_mappings.Add(new MiningPair(fakeCdev, fakeAlgo)); } cdevs_mappings.Add(pair); } } // reset setMiningPairs setMiningPairs = cdevs_mappings; } // sgminer exception handle intensity types if (MinerType.sgminer == minerType) { // rawIntensity overrides xintensity, xintensity overrides intensity var sgminer_intensities = new List <MinerOption>() { new MinerOption("Intensity", "-I", "--intensity", "d", MinerOptionFlagType.MultiParam, ","), // default is "d" check if -1 works new MinerOption("Xintensity", "-X", "--xintensity", "-1", MinerOptionFlagType.MultiParam, ","), // default none new MinerOption("Rawintensity", "", "--rawintensity", "-1", MinerOptionFlagType.MultiParam, ","), // default none }; var contains_intensity = new Dictionary <MinerOptionType, bool>() { { "Intensity", false }, { "Xintensity", false }, { "Rawintensity", false }, }; // check intensity and xintensity, the latter overrides so change accordingly foreach (var cDev in setMiningPairs) { foreach (var intensityOption in sgminer_intensities) { if (!string.IsNullOrEmpty(intensityOption.ShortName) && cDev.CurrentExtraLaunchParameters.Contains(intensityOption.ShortName)) { cDev.CurrentExtraLaunchParameters = cDev.CurrentExtraLaunchParameters.Replace(intensityOption.ShortName, intensityOption.LongName); contains_intensity[intensityOption.Type] = true; } if (cDev.CurrentExtraLaunchParameters.Contains(intensityOption.LongName)) { contains_intensity[intensityOption.Type] = true; } } } // replace if (contains_intensity["Intensity"] && contains_intensity["Xintensity"]) { LogParser("Sgminer replacing --intensity with --xintensity"); foreach (var cDev in setMiningPairs) { cDev.CurrentExtraLaunchParameters = cDev.CurrentExtraLaunchParameters.Replace("--intensity", "--xintensity"); } } if (contains_intensity["Xintensity"] && contains_intensity["Rawintensity"]) { LogParser("Sgminer replacing --xintensity with --rawintensity"); foreach (var cDev in setMiningPairs) { cDev.CurrentExtraLaunchParameters = cDev.CurrentExtraLaunchParameters.Replace("--xintensity", "--rawintensity"); } } } string ret = ""; string general = Parse(setMiningPairs, minerOptionPackage.GeneralOptions, false, minerOptionPackage.TemperatureOptions); // temp control and parse if (ConfigManager.GeneralConfig.DisableAMDTempControl) { LogParser("DisableAMDTempControl is TRUE, temp control parameters will be ignored"); ret = general; } else { LogParser("AMD parsing temperature control parameters"); // temp = Parse(setMiningPairs, minerOptionPackage.TemperatureOptions, true, minerOptionPackage.GeneralOptions); string temp = Parse(setMiningPairs, minerOptionPackage.TemperatureOptions, false, minerOptionPackage.GeneralOptions); ret = general + " " + temp; } return(ret); }
// benchmark stuff protected override string BenchmarkCreateCommandLine(Algorithm algorithm, int time) { string ret = " -a " + this.MiningSetup.MinerName + " -b " + time + " " + GetDevicesCommandString(); return(ret); }
// new decoupled benchmarking routines #region Decoupled benchmarking routines protected override string BenchmarkCreateCommandLine(Algorithm algorithm, int time) { string url = Globals.GetLocationUrl(algorithm.NiceHashID, Globals.MiningLocation[ConfigManager.GeneralConfig.ServiceLocation], this.ConectionType); string alg = url.Substring(url.IndexOf("://") + 3, url.IndexOf(".") - url.IndexOf("://") - 3); string port = url.Substring(url.IndexOf(".com:") + 5, url.Length - url.IndexOf(".com:") - 5); var username = GetUsername(Globals.GetBitcoinUser(), ConfigManager.GeneralConfig.WorkerName.Trim()); var apiBind = " --api-bind 127.0.0.1:" + ApiPort; var algo = "--algo " + MiningSetup.MinerName; var commandLine = ""; if (File.Exists("bin_3rdparty\\CryptoDredge\\" + GetLogFileName())) { File.Delete("bin_3rdparty\\CryptoDredge\\" + GetLogFileName()); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.Blake2s)) { commandLine = "--algo blake2s" + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o stratum+tcp://blake2s.eu.mine.zpool.ca:5766" + " -u 1JqFnUR3nDFCbNUmWiQ4jX6HRugGzX55L2" + " -p c=BTC " + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 3; Total = 0.0d; return(commandLine); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.X16R)) { commandLine = "--algo x16r" + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o stratum+tcp://x16r.eu.mine.zpool.ca:3636" + " -u 1JqFnUR3nDFCbNUmWiQ4jX6HRugGzX55L2" + " -p c=BTC " + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 3; Total = 0.0d; return(commandLine); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.Lyra2z)) { commandLine = "--algo lyra2z" + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o stratum+tcp://lyra2z.eu.mine.zpool.ca:4553" + " -u 1JqFnUR3nDFCbNUmWiQ4jX6HRugGzX55L2" + " -p c=BTC " + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 3; Total = 0.0d; return(commandLine); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.Lyra2REv2)) { commandLine = "--algo lyra2v2" + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o stratum+tcp://lyra2v2.eu.mine.zpool.ca:4533" + " -u 1JqFnUR3nDFCbNUmWiQ4jX6HRugGzX55L2" + " -p c=BTC " + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 2; Total = 0.0d; return(commandLine); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.Lyra2REv3)) { commandLine = "--algo lyra2v3" + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o stratum+tcp://lyra2v3.eu.mine.zpool.ca:4550" + " -u 1JqFnUR3nDFCbNUmWiQ4jX6HRugGzX55L2" + " -p c=BTC " + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 2; Total = 0.0d; return(commandLine); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.NeoScrypt)) { commandLine = "--algo neoscrypt --retry-pause 5" + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o stratum+tcp://neoscrypt.na.mine.zpool.ca:4233" + " -u 1JqFnUR3nDFCbNUmWiQ4jX6HRugGzX55L2" + " -p c=BTC " + //no support for failover pools? " -o stratum+tcp://neoscrypt.jp.mine.zpool.ca:4233" + " -u 1JqFnUR3nDFCbNUmWiQ4jX6HRugGzX55L2" + " -p c=BTC " + " -o stratum+tcp://neoscrypt.sea.mine.zpool.ca:4233" + " -u 1JqFnUR3nDFCbNUmWiQ4jX6HRugGzX55L2" + " -p c=BTC " + " -o stratum+tcp://neoscrypt.eu.mine.zpool.ca:4233" + " -u 1JqFnUR3nDFCbNUmWiQ4jX6HRugGzX55L2" + " -p c=BTC " + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 2; Total = 0.0d; return(commandLine); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.Skunk)) { commandLine = "--algo skunk" + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + // " -o stratum+tcp://hdac.moricpool.com:3333" + " -u HGr2JYPDMgYr9GzS9TcadBxxkyxo4v9XAJ" + " -p x " + "-o stratum+tcp://skunk.eu.mine.zpool.ca:8433 -u 1JqFnUR3nDFCbNUmWiQ4jX6HRugGzX55L2 -p c=BTC" + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 2; Total = 0.0d; return(commandLine); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.CryptoNightHeavy)) { commandLine = "--algo cnheavy" + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + " --url=stratum+tcp://" + alg + ".hk.nicehash.com:" + port + " " + " -u " + username + " -p x " + " --url=stratum+tcp://" + alg + ".in.nicehash.com:" + port + " " + " -u " + username + " -p x " + //" -o stratum+tcp://loki.miner.rocks:5555" + " -u L95cF8XmPzzhBA1tkiL1NMijNNbj58vs1iJExK84oi2LKc6RQm2q1Z4PmDxYB7sicHVXY1J5YV9yg6vkMxKpuCK1L1SwoDi"+ " -p w=" + ConfigManager.GeneralConfig.WorkerName.Trim() + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 3; Total = 0.0d; return(commandLine); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.CryptoNightV8)) { /* * if (File.Exists("bin_3rdparty\\CryptoDredgeV8\\"+ GetLogFileName())) * File.Delete("bin_3rdparty\\CryptoDredgeV8\\" + GetLogFileName()); */ algo = "--algo cnv8"; commandLine = algo + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + " --url=stratum+tcp://" + alg + ".hk.nicehash.com:" + port + " " + " -u " + username + " -p x " + " --url=stratum+tcp://" + alg + ".in.nicehash.com:" + port + " " + " -u " + username + " -p x " + // " -o stratum+tcp://xmr-usa.dwarfpool.com:8005" + " -u 42fV4v2EC4EALhKWKNCEJsErcdJygynt7RJvFZk8HSeYA9srXdJt58D9fQSwZLqGHbijCSMqSP4mU7inEEWNyer6F7PiqeX." + ConfigManager.GeneralConfig.WorkerName.Trim() + " -p x " + // " -o stratum+tcp://xmr-eu.dwarfpool.com:8005" + " -u 42fV4v2EC4EALhKWKNCEJsErcdJygynt7RJvFZk8HSeYA9srXdJt58D9fQSwZLqGHbijCSMqSP4mU7inEEWNyer6F7PiqeX."+ ConfigManager.GeneralConfig.WorkerName.Trim() + " -p x " + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 3; Total = 0.0d; return(commandLine); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.MTP)) { algo = "--algo mtp"; commandLine = algo + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o stratum+tcp://xzc.2miners.com:8080" + " -u aMGfYX8ARy4wKE57fPxkEBcnNuHegDBweE." + ConfigManager.GeneralConfig.WorkerName.Trim() + " -p x " + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 3; Total = 0.0d; return(commandLine); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.GrinCuckaroo29)) { algo = "--algo cuckaroo29"; commandLine = algo + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o stratum+tcp://grin.sparkpool.com:6666" + " -u [email protected]/" + ConfigManager.GeneralConfig.WorkerName.Trim() + " -p x " + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 3; Total = 0.0d; return(commandLine); } if (MiningSetup.CurrentAlgorithmType.Equals(AlgorithmType.CuckooCycle)) { algo = "--algo aeternity"; commandLine = algo + " --url=stratum+tcp://" + alg + ".eu.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o stratum+tcp://ae.f2pool.com:7898" + " -u ak_2f9AMwztStKs5roPmT592wTbUEeTyqRgYVZNrc5TyZfr94m7fM." + ConfigManager.GeneralConfig.WorkerName.Trim() + " -p x " + " --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 3; Total = 0.0d; return(commandLine); } commandLine = algo + " -o " + url + " -u " + username + " -p x " + " --url=stratum+tcp://" + alg + ".hk.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o " + alg + ".jp.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o " + alg + ".in.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o " + alg + ".br.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o " + alg + ".usa.nicehash.com:" + port + " " + " -u " + username + " -p x " + " -o " + alg + ".eu.nicehash.com:" + port + " -u " + username + " -p x " + " -o " + url + " -u " + username + " -p x --log " + GetLogFileName() + apiBind + " -d " + GetDevicesCommandString() + " " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA) + " "; TotalCount = 2; Total = 0.0d; return(commandLine); }
/// <summary> /// Generates a string that can be set to an Authorization header. /// </summary> public string GenerateResponseHeader(HTTPRequest request, Credentials credentials, bool isProxy = false) { try { switch (Type) { case AuthenticationTypes.Basic: return(string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", credentials.UserName, credentials.Password))))); case AuthenticationTypes.Digest: { NonceCount++; string HA1 = string.Empty; // The cnonce-value is an opaque quoted string value provided by the client and used by both client and server to avoid chosen plaintext attacks, to provide mutual // authentication, and to provide some message integrity protection. string cnonce = new System.Random(request.GetHashCode()).Next(int.MinValue, int.MaxValue).ToString("X8"); string ncvalue = NonceCount.ToString("X8"); switch (Algorithm.TrimAndLower()) { case "md5": HA1 = string.Format("{0}:{1}:{2}", credentials.UserName, Realm, credentials.Password).CalculateMD5Hash(); break; case "md5-sess": if (string.IsNullOrEmpty(this.HA1Sess)) { this.HA1Sess = string.Format("{0}:{1}:{2}:{3}:{4}", credentials.UserName, Realm, credentials.Password, Nonce, ncvalue).CalculateMD5Hash(); } HA1 = this.HA1Sess; break; default: //throw new NotSupportedException("Not supported hash algorithm found in Web Authentication: " + Algorithm); return(string.Empty); } // A string of 32 hex digits, which proves that the user knows a password. Set according to the qop value. string response = string.Empty; // The server sent QoP-value can be a list of supported methodes(if sent at all - in this case it's null). // The rfc is not specify that this is a space or comma separeted list. So it can be "auth, auth-int" or "auth auth-int". // We will first check the longer value("auth-int") then the short one ("auth"). If one matches we will reset the qop to the exact value. string qop = this.QualityOfProtections != null?this.QualityOfProtections.TrimAndLower() : null; // When we authenticate with a proxy and we want to tunnel the request, we have to use the CONNECT method instead of the // request's, as the proxy will not know about the request itself. string method = isProxy ? "CONNECT" : request.MethodType.ToString().ToUpper(); // When we authenticate with a proxy and we want to tunnel the request, the uri must match what we are sending in the CONNECT request's // Host header. string uri = isProxy ? request.CurrentUri.Host + ":" + request.CurrentUri.Port : request.CurrentUri.GetRequestPathAndQueryURL(); if (qop == null) { string HA2 = string.Concat(request.MethodType.ToString().ToUpper(), ":", request.CurrentUri.GetRequestPathAndQueryURL()).CalculateMD5Hash(); response = string.Format("{0}:{1}:{2}", HA1, Nonce, HA2).CalculateMD5Hash(); } else if (qop.Contains("auth-int")) { qop = "auth-int"; byte[] entityBody = request.GetEntityBody(); if (entityBody == null) { entityBody = VariableSizedBufferPool.NoData; //string.Empty.GetASCIIBytes(); } string HA2 = string.Format("{0}:{1}:{2}", method, uri, entityBody.CalculateMD5Hash()).CalculateMD5Hash(); response = string.Format("{0}:{1}:{2}:{3}:{4}:{5}", HA1, Nonce, ncvalue, cnonce, qop, HA2).CalculateMD5Hash(); } else if (qop.Contains("auth")) { qop = "auth"; string HA2 = string.Concat(method, ":", uri).CalculateMD5Hash(); response = string.Format("{0}:{1}:{2}:{3}:{4}:{5}", HA1, Nonce, ncvalue, cnonce, qop, HA2).CalculateMD5Hash(); } else //throw new NotSupportedException("Unrecognized Quality of Protection value found: " + this.QualityOfProtections); { return(string.Empty); } string result = string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", cnonce=\"{4}\", response=\"{5}\"", credentials.UserName, Realm, Nonce, uri, cnonce, response); if (qop != null) { result += String.Concat(", qop=\"", qop, "\", nc=", ncvalue); } if (!string.IsNullOrEmpty(Opaque)) { result = String.Concat(result, ", opaque=\"", Opaque, "\""); } return(result); } // end of case "digest": default: break; } } catch { } return(string.Empty); }
public virtual float GetSimilarityPercent(T left, T right) { return(Algorithm.GetSimilarity(left, right)); }
public AlgorithmContainer(Algorithm algorithm, PluginContainer pluginContainer, ComputeDevice computeDevice) { PluginContainer = pluginContainer; Algorithm = algorithm; ComputeDevice = computeDevice; }
public override void Move(Algorithm algorithm) { throw new NotImplementedException(); }
public static void ImportWithFormatMin(Algorithm a) { Assert.Throws <ArgumentException>("format", () => PublicKey.Import(a, ReadOnlySpan <byte> .Empty, (KeyBlobFormat)int.MinValue)); }
static void Main(string[] args) { Console.WriteLine("Usage: Analysis (des|aes) inputPath"); // check command-line parameters if (args.Length != 2) { Console.WriteLine("Incorrect input parameters."); return; } // check for algorithm Algorithm algorithm = Algorithm.Invalid; switch (args[0].ToLower()) { case "des": algorithm = Algorithm.DES; break; case "aes": algorithm = Algorithm.AES; break; default: Console.WriteLine("Incorrect encryption algorithm: {0}", args[0]); return; } // check for input file FileInfo inFile = new FileInfo(args[1]); if (!inFile.Exists) { Console.WriteLine("Unable to find input file: {0}", args[0]); return; } // and open using (FileStream inStream = inFile.OpenRead()) { // get output directory DirectoryInfo outDir = Directory.CreateDirectory(Path.Combine(inFile.DirectoryName, "output", inFile.Name)); // bit frequency (0/1) using (FileStream outStream = File.Create(Path.Combine(outDir.FullName, "bit.csv"))) { BitAnalysis(inStream, outStream); } // letter frequency (1gram), digram through 8-gram analysis for (int i = 1; i <= 3; i++) { using (FileStream outStream = File.Create(Path.Combine(outDir.FullName, i + "grams.csv"))) { NgramAnalysis(inStream, outStream, i); } } // block (8-byte or 16-byte) analysis using (FileStream outStream = File.Create(Path.Combine(outDir.FullName, "block.csv"))) { BlockAnalysis(inStream, outStream, (int)algorithm); } } return; }
/// <summary> /// </summary> /// <param name="username"> /// </param> /// <param name="password"> /// </param> /// <param name="method"> /// </param> /// <returns> /// </returns> /// <exception cref="ArgumentException"> /// </exception> public string CalculateResponse(string username, string password, string method) { /* * MD5 * A1 = username-value ":" realm-value ":" passwd * * MD5-sess * A1 = md5(username-value ":" realm-value ":" passwd) ":" nonce-value ":" cnonce-value * * qop not peresent or auth * A2 = Method ":" digest-uri-value * * qop auth-int * A2 = Method ":" digest-uri-value ":" md5h(entity-body) * * qop present * response = md5h(md5h(A1) ":" nonce-value ":" nc-value ":" cnonce-value ":" qop-value ":" md5h(A2)) * * qop not present * response = md5h(md5h(A1) ":" nonce-value ":" md5h(A2)) * */ string a1 = string.Empty; string a2 = string.Empty; // Create A1 if (string.IsNullOrEmpty(Algorithm) || Algorithm.ToLower() == "md5-sess") { a1 = ComputeMd5(username + ":" + Realm + ":" + password, false) + ":" + Nonce + ":" + Cnonce; } else if (Algorithm.ToLower() == "md5") { a1 = username + ":" + Realm + ":" + password; } else { throw new ArgumentException("Invalid Algorithm value '" + Algorithm + "' !"); } // Create A2 if (Qop == string.Empty || Qop.ToLower() == "auth") { a2 = method + ":" + DigestUri; } else { throw new ArgumentException("Invalid qop value '" + Qop + "' !"); } // Calculate response value. // qop present if (!string.IsNullOrEmpty(Qop)) { return (ComputeMd5( ComputeMd5(a1, true) + ":" + Nonce + ":" + Nc + ":" + Cnonce + ":" + Qop + ":" + ComputeMd5(a2, true), true)); } // qop not present else { return(ComputeMd5(ComputeMd5(a1, true) + ":" + Nonce + ":" + ComputeMd5(a2, true), true)); } }
[Test] public void MaxElement_IntEnumeratorPredicate() { int value = Algorithm.MaxElement(GetIntEnumerator(), Functional.Compare); Assert.AreEqual(100, value); }
[Test] public void MaxElement_IntEnumeratorPredicate() { int value = Algorithm.MaxElement(GetIntEnumerator(), GreaterThanInt); Assert.AreEqual(100, value); }
[Test] public void MaxElement_IntEnumeratorComparer() { int value = Algorithm.MaxElement(GetIntEnumerator(), Comparer <int> .Default); Assert.AreEqual(100, value); }
/// <summary> /// Calculates 'rspauth' value. /// </summary> /// <param name="userName">User name.</param> /// <param name="password">Password.</param> /// <returns>Returns 'rspauth' value.</returns> public string CalculateRspAuth(string userName, string password) { /* RFC 2617 3.2.3. * The optional response digest in the "response-auth" directive * supports mutual authentication -- the server proves that it knows the * user's secret, and with qop=auth-int also provides limited integrity * protection of the response. The "response-digest" value is calculated * as for the "request-digest" in the Authorization header, except that * if "qop=auth" or is not specified in the Authorization header for the * request, A2 is * * A2 = ":" digest-uri-value * * and if "qop=auth-int", then A2 is * * A2 = ":" digest-uri-value ":" H(entity-body) * * where "digest-uri-value" is the value of the "uri" directive on the * Authorization header in the request. The "cnonce-value" and "nc- * value" MUST be the ones for the client request to which this message * is the response. The "response-auth", "cnonce", and "nonce-count" * directives MUST BE present if "qop=auth" or "qop=auth-int" is * specified. */ string a1 = ""; string a2 = ""; // Create A1 if (Algorithm == "" || Algorithm.ToLower() == "md5") { a1 = userName + ":" + Realm + ":" + password; } else if (Algorithm.ToLower() == "md5-sess") { a1 = Core.ComputeMd5(userName + ":" + Realm + ":" + password, false) + ":" + Nonce + ":" + CNonce; } else { throw new ArgumentException("Invalid Algorithm value '" + Algorithm + "' !"); } // Create A2 if (Qop == "" || Qop.ToLower() == "auth") { a2 = ":" + Uri; } else { throw new ArgumentException("Invalid qop value '" + Qop + "' !"); } // Calculate response value. // qop present if (!string.IsNullOrEmpty(Qop)) { return (Core.ComputeMd5( Core.ComputeMd5(a1, true) + ":" + Nonce + ":" + NonceCount.ToString("x8") + ":" + CNonce + ":" + Qop + ":" + Core.ComputeMd5(a2, true), true)); } // qop not present else { return (Core.ComputeMd5( Core.ComputeMd5(a1, true) + ":" + Nonce + ":" + Core.ComputeMd5(a2, true), true)); } }
private void SolveCrossTopLayer() { // Step 1: Get edges with the color of the top face IEnumerable <Cube> topEdges = Rubik.Cubes.Where(c => c.IsEdge).Where(c => c.Position.HasFlag(CubeFlag.TopLayer)); // Step 2: Check if the cube is insoluble if (topEdges.Count(tE => tE.Faces.First(f => f.Position == FacePosition.Top).Color == Rubik.TopColor) % 2 != 0) { return; } var correctEdges = topEdges.Where(c => c.Faces.First(f => f.Position == FacePosition.Top).Color == Rubik.TopColor); var solveTopCrossAlgorithmI = new Algorithm("F R U R' U' F'"); var solveTopCrossAlgorithmII = new Algorithm("F S R U R' U' F' S'"); // Step 3: Solve the cross on the top layer if (Rubik.CountEdgesWithCorrectOrientation() == 0) { SolverAlgorithm(solveTopCrossAlgorithmI); correctEdges = topEdges.Where(c => c.Faces.First(f => f.Position == FacePosition.Top).Color == Rubik.TopColor); } if (Rubik.CountEdgesWithCorrectOrientation() == 2) { var firstCorrect = correctEdges.First(); var secondCorrect = correctEdges.First(f => f != firstCorrect); bool opposite = false; foreach (CubeFlag flag in firstCorrect.Position.GetFlags()) { CubeFlag pos = CubeFlagService.GetOppositeFlag(flag); if (secondCorrect.Position.HasFlag(pos) && pos != CubeFlag.None) { opposite = true; break; } } if (opposite) { while (correctEdges.Count(c => c.Position.HasFlag(CubeFlag.RightSlice)) != 1) { SolverMove(CubeFlag.TopLayer, true); } SolverAlgorithm(solveTopCrossAlgorithmI); } else { while (correctEdges.Count(c => c.Position.HasFlag(CubeFlag.RightSlice) || c.Position.HasFlag(CubeFlag.FrontSlice)) != 2) { SolverMove(CubeFlag.TopLayer, true); } SolverAlgorithm(solveTopCrossAlgorithmII); } } // Step 4: Move the edges of the cross to their target positions while (topEdges.Count(c => c.Position.Flags == GetTargetFlags(c)) < 4) { IEnumerable <Cube> correctEdges2 = topEdges.Where(c => c.Position.Flags == GetTargetFlags(c)); while (correctEdges2.Count() < 2) { SolverMove(CubeFlag.TopLayer, true); } CubeFlag rightSlice = CubeFlagService.FromFacePosition(correctEdges2.First().Faces .First(f => f.Position != FacePosition.Top && f.Color != Color.Black).Position); SolverMove(CubeFlag.TopLayer, false); if (correctEdges2.Count(c => c.Position.HasFlag(rightSlice)) == 0) { SolverMove(CubeFlag.TopLayer, true); } else { SolverMove(CubeFlag.TopLayer, true); rightSlice = CubeFlagService.FromFacePosition( correctEdges2 .First(cE => !cE.Position.HasFlag(rightSlice)) .Faces .First(f => f.Position != FacePosition.Top && f.Color != Color.Black ) .Position ); } // Algorithm: R U R' U R U U R' SolverAlgorithm( "{0} U {0}' U {0} U U {0}'", CubeFlagService.ToNotationString(rightSlice) ); while (correctEdges2.Count() < 2) { SolverMove(CubeFlag.TopLayer, true); } } }
public static void ImportEmpty(Algorithm a, KeyBlobFormat format) { Assert.Throws <FormatException>(() => PublicKey.Import(a, ReadOnlySpan <byte> .Empty, format)); }
public string GetAddress(string serviceFullName) { var addresses = _getAddresses(serviceFullName); return(Algorithm.Balance <string>(addresses)); //如果有多个地址,那么均衡使用某一个地址 }
public static void TryImportWithFormatMax(Algorithm a) { Assert.Throws <ArgumentException>("format", () => PublicKey.TryImport(a, ReadOnlySpan <byte> .Empty, (KeyBlobFormat)int.MaxValue, out PublicKey pk)); }
/// <summary> /// Process the synchronous result events, sampling and message reading. /// This method is triggered from the algorithm manager thread. /// </summary> /// <remarks>Prime candidate for putting into a base class. Is identical across all result handlers.</remarks> public void ProcessSynchronousEvents(bool forceProcess = false) { if (Algorithm == null) { return; } var time = Algorithm.UtcTime; if (time > _nextSample || forceProcess) { //Set next sample time: 4000 samples per backtest _nextSample = time.Add(ResamplePeriod); //Sample the portfolio value over time for chart. SampleEquity(time, Math.Round(Algorithm.Portfolio.TotalPortfolioValue, 4)); //Also add the user samples / plots to the result handler tracking: SampleRange(Algorithm.GetChartUpdates()); //Sample the asset pricing: foreach (var kvp in Algorithm.Securities) { var security = kvp.Value; SampleAssetPrices(security.Symbol, time, security.Price); } } //Send out the debug messages: var endTime = DateTime.UtcNow.AddMilliseconds(250).Ticks; while (Algorithm.DebugMessages.Count > 0 && DateTime.UtcNow.Ticks < endTime) { string message; if (Algorithm.DebugMessages.TryDequeue(out message)) { DebugMessage(message); } } //Send out the error messages: endTime = DateTime.UtcNow.AddMilliseconds(250).Ticks; while (Algorithm.ErrorMessages.Count > 0 && DateTime.UtcNow.Ticks < endTime) { string message; if (Algorithm.ErrorMessages.TryDequeue(out message)) { ErrorMessage(message); } } //Send out the log messages: endTime = DateTime.UtcNow.AddMilliseconds(250).Ticks; while (Algorithm.LogMessages.Count > 0 && DateTime.UtcNow.Ticks < endTime) { string message; if (Algorithm.LogMessages.TryDequeue(out message)) { LogMessage(message); } } //Set the running statistics: foreach (var pair in Algorithm.RuntimeStatistics) { RuntimeStatistic(pair.Key, pair.Value); } }
public static void TryImportEmpty(Algorithm a, KeyBlobFormat format) { Assert.False(PublicKey.TryImport(a, ReadOnlySpan <byte> .Empty, format, out PublicKey pk)); Assert.Null(pk); }
public override void Start(Algorithm miningAlgorithm, string url, string username) { Helpers.ConsolePrint(MinerTAG(), "Starting MinerEtherumOCL, checking existing MinerEtherumOCL to stop"); base.Start(miningAlgorithm, url, username, MinerEtherumOCLList); }
public void NullableInput() { var algo = new Algorithm(null, prefixCalculator); }
public abstract void Move(Algorithm algorithm);
/// <summary> /// A very weak hash (only 32bits) intended for use as a pre-calculated identifier; odds of /// collision are 1 in 4 billion so don't use for a set of objects that's too large /// </summary> /// <param name="stringToHash">The string to hash</param> /// <param name="alg">SHA1 (default) or MD5</param> /// <returns>The first 32 bits of the SHA-1 hash</returns> public static Int32 HashString32(string stringToHash, Boolean unicode = false, Algorithm alg = Algorithm.SHA1) { return(( Int32 )(HashString64(stringToHash, unicode, alg))); }
protected override string GetBenchmarkCommandStringPart(ComputeDevice benchmarkDevice, Algorithm algorithm) { return(" --opencl --opencl-platform " + GPUPlatformNumber + " " + algorithm.ExtraLaunchParameters + " --benchmark-warmup 40 --benchmark-trial 20" + " --opencl-devices "); }
public static string[] PlanPath( string problem, string domain, Algorithm algorithm = Algorithm.GBFS, Direction direction = Direction.Backward, Heuristic heuristic = Heuristic.H1Plus, int verbosity = 1, float costWeight = 5.0f, ScheduleStep[] schedule = null) { /* * usage: * hsp <flags>* [ <algorithm> | -S <schedule> ] * <problem.pddl> <domain.pddl> */ List <string> arguments = new List <string> { "hsp" }; arguments.AddRange( $"-v {verbosity} -w {costWeight}".Split(' ')); if (schedule != null) { /* * <schedule> is a colon separated <option> list where each option has * [<direction>,<heuristic>,<msecs>]. */ string scheduleString = string.Join(":", schedule.Select(s => $"[{s.dir:g},".ToLower() + $"{s.heuristic:g},".ToLower() + $"{s.milliseconds}]" )); arguments.Add("-S"); arguments.Add(scheduleString); } else { arguments.AddRange(( $"-a {algorithm:g}".ToLower() + $" -d {direction:g}".ToLower() + $" -h {heuristic:g}".ToLower() ).Split(' ')); } arguments.Add(problem); arguments.Add(domain); string[] argArray = arguments.ToArray(); IntPtr ptr = IntPtr.Zero; int count; using (StreamWriter outStream = NativeMethods.RedirectConsoleToFile("solution.txt")) { count = NativeMethods.Plan(arguments.Count, argArray, out ptr); NativeMethods.ResetConsole(); } return(NativeMethods.MarshalStringArray(ptr, count)); }
static TypeInfo() { using (new BenchmarkedRegion("Static constructor")) { var typeInfoById = new Dictionary <short, TypeInfo>(); var typeInfoByType = new Dictionary <Type, TypeInfo>(); foreach (var preset in GetPresets()) { var info = new TypeInfo(preset.Key, --_minId, preset.Value); typeInfoById.Add(info.Id, info); typeInfoByType.Add(info.Type, info); } var config = (TypeMappingConfig)ConfigurationManager.GetSection(TypeMappingConfig.SectionName); int maxId = -1; if (config == null) { _log.ErrorFormat("Missing configuration section: '{0}'", TypeMappingConfig.SectionName); } else { foreach (var typeInfoConfig in config.Types) { if (string.IsNullOrEmpty(typeInfoConfig.Name)) { _log.ErrorFormat("'name' not defined for type with id: {0}", typeInfoConfig.Id); continue; } Type type; try { type = Type.GetType(typeInfoConfig.Name, false); } catch (Exception ex) { _log.Error(string.Format("Failed to resolve type id {0}", typeInfoConfig.Id), ex); continue; } if (type == null) { _log.WarnFormat("Couldn't resolve type name {0} for type id {1}", typeInfoConfig.Name, typeInfoConfig.Id); continue; } var typeInfo = new TypeInfo(type, typeInfoConfig.Id, typeInfoConfig.WellEstablished); if (typeInfoById.ContainsKey(typeInfoConfig.Id)) { _log.ErrorFormat("A type with id {0} is already defined. This type will be ignored.", typeInfoConfig.Id); continue; } if (typeInfoByType.ContainsKey(type)) { _log.ErrorFormat("An id, {0}, is already defined for type {1}; type id {2} will be skipped.", typeInfoByType[type].Id, type, typeInfoConfig.Id); continue; } typeInfoById[typeInfo.Id] = typeInfo; typeInfoByType[type] = typeInfo; if (maxId < typeInfo.Id) { maxId = typeInfo.Id; } } } _typeInfoById = new TypeInfo[maxId + 1 - _minId]; foreach (var pair in typeInfoById) { _typeInfoById[pair.Key - _minId] = pair.Value; } _typeInfoByType = Algorithm.LazyIndexer <Type, TypeInfo>(type => { TypeInfo result; if (typeInfoByType.TryGetValue(type, out result)) { return(result); } return(new TypeInfo(type)); }); _typeInfoByTypeName = Algorithm.LazyIndexer <string, TypeInfo>(typeName => _typeInfoByType(Type.GetType(typeName, true))); ThreadPool.QueueUserWorkItem(LogTypeIdGaps, _typeInfoById); } }
private void AddEventHandler(Algorithm handler) { handler.PropertyChanged += AlgorithmPropertyChangedHandler; }
[Test] public void MaxElement_IntEnumerator() { int value = Algorithm.MaxElement(GetIntEnumerator()); Assert.AreEqual(100, value); }
public static bool IsAlgoMiningCapable(Algorithm algo) { return(algo != null && algo.Enabled && algo.BenchmarkSpeed > 0); }