示例#1
2
文件: main.cs 项目: TerraTeddy95/CR
        public override void Initialize()
        {
            string path = Path.Combine(TShock.SavePath, "CodeReward1_9.json");
            Config = Config.Read(path);
            if (!File.Exists(path))
            {
                Config.Write(path);
            }
            Commands.ChatCommands.Add(new Command(Permissions.codereward, Cmds.functionCmd, "codereward"));
            Commands.ChatCommands.Add(new Command(Permissions.codereward, Cmds.functionCmd, "crt"));
            Variables.ALL = Config.ALL;

            //Events
            ServerApi.Hooks.ServerChat.Register(this, Chat.onChat);

            string version = "1.3.0.8 (1.9)";
            System.Net.WebClient wc = new System.Net.WebClient();
            string webData = wc.DownloadString("http://textuploader.com/al9u6/raw");
            if (version != webData)
            {
                Console.WriteLine("[CodeReward] New version is available!: " + webData);
            }

            System.Timers.Timer timer = new System.Timers.Timer(Variables.ALL.Interval * (60 * 1000));
            timer.Elapsed += run;
            timer.Start();
        }
        public string GenerateOutput(HttpContext context, Config c)
        {
            StringBuilder sb = new StringBuilder();

            //Figure out CustomErrorsMode
            System.Configuration.Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
            CustomErrorsSection section = (configuration != null) ? section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors") : null;
            CustomErrorsMode mode = (section != null) ? section.Mode : CustomErrorsMode.RemoteOnly;
            //What is diagnostics enableFor set to?
            DiagnosticMode dmode = c.get<DiagnosticMode>("diagnostics.enableFor", DiagnosticMode.None);
            //Is it set all all?
            bool diagDefined = (c.get("diagnostics.enableFor",null) != null);
            //Is it available from localhost.
            bool availLocally = (!diagDefined && mode == CustomErrorsMode.RemoteOnly) || (dmode == DiagnosticMode.Localhost);

            sb.AppendLine("The Resizer diagnostics page is " + (availLocally ? "only available from localhost." : "disabled."));
            sb.AppendLine();
            if (diagDefined) sb.AppendLine("This is because <diagnostics enableFor=\"" + dmode.ToString() + "\" />.");
            else sb.AppendLine("This is because <customErrors mode=\"" + mode.ToString() + "\" />.");
            sb.AppendLine();
            sb.AppendLine("To override for localhost access, add <diagnostics enableFor=\"localhost\" /> in the <resizer> section of Web.config.");
            sb.AppendLine();
            sb.AppendLine("To ovveride for remote access, add <diagnostics enableFor=\"allhosts\" /> in the <resizer> section of Web.config.");
            sb.AppendLine();
            return sb.ToString();
        }
        public static KeyValuePair<string, BranchConfig> GetBranchConfiguration(Commit currentCommit, IRepository repository, bool onlyEvaluateTrackedBranches, Config config, Branch currentBranch, IList<Branch> excludedInheritBranches = null)
        {
            var matchingBranches = LookupBranchConfiguration(config, currentBranch);

            if (matchingBranches.Length == 0)
            {
                var branchConfig = new BranchConfig();
                ConfigurationProvider.ApplyBranchDefaults(config, branchConfig);
                return new KeyValuePair<string, BranchConfig>(string.Empty, branchConfig);
            }
            if (matchingBranches.Length == 1)
            {
                var keyValuePair = matchingBranches[0];
                var branchConfiguration = keyValuePair.Value;

                if (branchConfiguration.Increment == IncrementStrategy.Inherit)
                {
                    return InheritBranchConfiguration(onlyEvaluateTrackedBranches, repository, currentCommit, currentBranch, keyValuePair, branchConfiguration, config, excludedInheritBranches);
                }

                return keyValuePair;
            }

            const string format = "Multiple branch configurations match the current branch branchName of '{0}'. Matching configurations: '{1}'";
            throw new Exception(string.Format(format, currentBranch.Name, string.Join(", ", matchingBranches.Select(b => b.Key))));
        }
示例#4
0
        public void TestProducerPublish()
        {
            var topicName = "publish" + DateTime.Now.Unix();
            const int msgCount = 10;

            var config = new Config();
            var w = new Producer("127.0.0.1:4150", new ConsoleLogger(LogLevel.Debug), config);
            try
            {
                for (int i = 0; i < msgCount; i++)
                {
                    w.Publish(topicName, "publish_test_case");
                }

                w.Publish(topicName, "bad_test_case");

                readMessages(topicName, msgCount);
            }
            finally
            {
                w.Stop();
                _nsqdHttpClient.DeleteTopic(topicName);
                _nsqLookupdHttpClient.DeleteTopic(topicName);
            }
        }
示例#5
0
文件: Idler.cs 项目: Kidify/L4p
 private Idler(ILogFile log, Config config)
 {
     _log = log.WrapIfNull();
     _counters = MyCounters.New<Counters>(log);
     _config = config;
     _jobs = new IdlerAction[0];
 }
示例#6
0
        /// <summary>
        /// Sets the default proxy for every HTTP request.
        /// If the caller would like to know if the call throws any exception, the second parameter should be set to true
        /// </summary>
        /// <param name="settings">proxy settings.</param>
        /// <param name="throwExceptions">If set to <c>true</c> throw exceptions.</param>
        public static void SetDefaultProxy(Config.ProxySettings settings, bool throwExceptions = false)
        {
            try
            {
                IWebProxy proxy = null;
                switch(settings.Selection) {
                    case Config.ProxySelection.SYSTEM:
                        proxy = WebRequest.GetSystemWebProxy();
                        break;
                    case Config.ProxySelection.CUSTOM:
                        proxy = new WebProxy(settings.Server);
                        break;
                }

                if (settings.LoginRequired && proxy != null) {
                    proxy.Credentials = new NetworkCredential(settings.Username, Crypto.Deobfuscate(settings.ObfuscatedPassword));
                }

                WebRequest.DefaultWebProxy = proxy;
            }
            catch (Exception e)
            {
                if (throwExceptions) {
                    throw;
                }

                Logger.Warn("Failed to set the default proxy, please check your proxy config: ", e);
            }
        }
示例#7
0
    // =============================================================================
    // =============================================================================
    // METHODS UNITY ---------------------------------------------------------------
    void Awake()
    {
        Config = GameObject.FindWithTag( "Config" ).GetComponent<Config>();
        Trans = transform;

        CC = gameObject.GetComponent<CharacterController>();
    }
示例#8
0
 public void ConnectToBrokerAsClient(Config nbConfig)
 {
     subscriber = new Subscriber(nbConfig);
     subscriber.NotificationHandlers = new BrokerConnectionNotifier.NotificationEventHandler[]{
         OnNotification
                     };
 }
示例#9
0
        public static void Initialize(string file)
        {
            config = new Config(file);

            if (config != null)
            {
                IsInitialized = true;

                LogLevel       = (LogType)config.Read("Log.Level", 0x7, true);
                LogDirectory   = config.Read("Log.Directory", "Logs/World");
                LogConsoleFile = config.Read("Log.Console.File", "");
                LogPacketFile  = config.Read("Log.Packet.File", "");

                LogWriter fl = null;

                if (LogConsoleFile != "")
                {
                    if (!Directory.Exists(LogDirectory))
                        Directory.CreateDirectory(LogDirectory);

                    fl = new LogWriter(LogDirectory, LogConsoleFile);
                }

                Log.Initialize(LogLevel, fl);

                if (LogPacketFile != "")
                    PacketLog.Initialize(LogDirectory, LogPacketFile);
            }

            ReadConfig();
        }
示例#10
0
        public void _BeforeTest()
        {
            MockContext = new MockContext();

            Settings =
            SettingKeys.DefaultValues.ToDictionary( kvp => kvp.Key, kvp => new Config { Id = kvp.Key, Value = kvp.Value } );

            MockContext.SettingsRepoMock.Setup( x => x.Set( It.IsAny<string>(), It.IsAny<string>() ) ).Callback<string, string>( ( key, value ) =>
            {
                Settings[key] = new Config { Id = key, Value = value };
            } );
            MockContext.SettingsRepoMock.Setup( x => x.GetById( It.IsAny<string>() ) ).Returns<string>( cfg => Settings[cfg] );

            MockContext.AppThemesMock.SetupGet( x => x.Accents ).Returns( new[]
            {
                new ColorItem {Name = "Red"},
                new ColorItem {Name = "Blue"},
                new ColorItem {Name = "Green"}
            } );
            MockContext.AppThemesMock.SetupGet( x => x.Themes ).Returns( new[]
            {
                new ColorItem {Name = "BaseDark"},
                new ColorItem {Name = "None"},
                new ColorItem {Name = "BaseLight"}
            } );
        }
    public void BranchCreatedAfterFastForwardMergeShouldInheritCorrectly()
    {
        var config = new Config
        {
            Branches =
            {
                { "unstable", new BranchConfig { Increment = IncrementStrategy.Minor } }
            }
        };

        using (var fixture = new EmptyRepositoryFixture(config))
        {
            fixture.Repository.MakeATaggedCommit("1.0.0");
            fixture.Repository.CreateBranch("unstable");
            fixture.Repository.Checkout("unstable");

            //Create an initial feature branch
            var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123");
            fixture.Repository.Checkout("feature/JIRA-123");
            fixture.Repository.MakeCommits(1);

            //Merge it
            fixture.Repository.Checkout("unstable");
            fixture.Repository.Merge(feature123, Constants.SignatureNow());

            //Create a second feature branch
            fixture.Repository.CreateBranch("feature/JIRA-124");
            fixture.Repository.Checkout("feature/JIRA-124");
            fixture.Repository.MakeCommits(1);

            fixture.AssertFullSemver("1.1.0-JIRA-124.1+2");
        }
    }
示例#12
0
    public bool GetButtonDown( Config.Device device )
    {
        if ( device == Config.Device.Keyboard && ButtonMouse != MouseKey.None )
        {
            bool mouse;
            int buttonNumber = (int) ButtonMouse;

            if ( ButtonMouse == MouseKey.WheelUp )
            {
                mouse = Input.GetAxis ( "Mouse ScrollWheel" ) > 0;
            }
            else if ( ButtonMouse == MouseKey.WheelDown )
            {
                mouse = Input.GetAxis ( "Mouse ScrollWheel" ) < 0;
            }
            else
            {
                mouse = Input.GetMouseButtonDown ( buttonNumber );
            }

            return Input.GetButtonDown ( ButtonKeyboard ) || mouse;
        }

        string button = GetCurrentButton ( device );
        if ( button.Length == 0 )
        {
            return false;
        }

        return Input.GetButtonDown ( button );
    }
示例#13
0
 public IPlugin Install(Configuration.Config c)
 {
     this.c = c;
     c.Plugins.add_plugin(this);
     c.Pipeline.PreHandleImage += Pipeline_PreHandleImage;
     return this;
 }
示例#14
0
 private void Config_SettingsSaved(Config settings, string filePath, bool result)
 {
     if (result)
     {
         Program.ConfigEdited = false;
     }
 }
示例#15
0
    public static void Main(string[] args)
    {
        GazeResults gaze_results = GazeReader.run(
                               new List<string> { "data/gazedata1.xml" })[0];
        foreach (GazeData gaze_data in gaze_results.gazes)
        {
          foreach (PropertyDescriptor descriptor in TypeDescriptor.
                                                GetProperties(gaze_data))
          {
        Console.Write("{0}={1}; ", descriptor.Name,
                      descriptor.GetValue(gaze_data));
          }
          Console.WriteLine("");
        }

        Config config = new Config();
        SourceCodeEntitiesFileCollection collection = SrcMLCodeReader.run(
          config.src2srcml_path, "data/java/");
        foreach (SourceCodeEntitiesFile file in collection)
        {
          Console.WriteLine(file.FileName  + ":");
          foreach (SourceCodeEntity entity in file)
          {
        Console.Write(" - ");
        foreach (PropertyDescriptor descriptor in TypeDescriptor.
                                                  GetProperties(entity))
        {
          Console.Write("{0}={1}; ", descriptor.Name,
                        descriptor.GetValue(entity));
        }
        Console.WriteLine("");
          }
        }
    }
示例#16
0
        protected override StepResult HandleResult(string result, Queue<ConfigInitWizardStep> steps, Config config, string workingDirectory)
        {
            int parsed;
            if (int.TryParse(result, out parsed))
            {
                if (parsed == 0)
                {
                    steps.Enqueue(new EditConfigStep(Console, FileSystem));
                    return StepResult.Ok();
                }

                try
                {
                    var foundBranch = OrderedBranches(config).ElementAt(parsed - 1);
                    var branchConfig = foundBranch.Value;
                    if (branchConfig == null)
                    {
                        branchConfig = new BranchConfig();
                        config.Branches.Add(foundBranch.Key, branchConfig);
                    }
                    steps.Enqueue(new ConfigureBranch(foundBranch.Key, branchConfig, Console, FileSystem));
                    return StepResult.Ok();
                }
                catch (ArgumentOutOfRangeException)
                { }
            }

            return StepResult.InvalidResponseSelected();
        }
示例#17
0
        protected override string GetPrompt(Config config, string workingDirectory)
        {
            return @"Which branch would you like to configure:

0) Go Back
" + string.Join("\r\n", OrderedBranches(config).Select((c, i) => string.Format("{0}) {1}", i + 1, c.Key)));
        }
示例#18
0
        private static MinificationResult MinifyCss(Config config, string file)
        {
            string content = File.ReadAllText(file);
            var settings = CssOptions.GetSettings(config);

            if (config.Minify.ContainsKey("enabled") && config.Minify["enabled"].ToString().Equals("false", StringComparison.OrdinalIgnoreCase))
                return null;

            var minifier = new Minifier();

            // Remove control characters which AjaxMin can't handle
            content = Regex.Replace(content, @"[\u0000-\u0009\u000B-\u000C\u000E-\u001F]", string.Empty);

            string result = minifier.MinifyStyleSheet(content, settings);

            if (!string.IsNullOrEmpty(result))
            {
                string minFile = GetMinFileName(file);
                bool containsChanges = FileHelpers.HasFileContentChanged(minFile, result);

                OnBeforeWritingMinFile(file, minFile, containsChanges);

                if (containsChanges)
                {
                    File.WriteAllText(minFile, result, new UTF8Encoding(true));
                }

                OnAfterWritingMinFile(file, minFile, containsChanges);

                GzipFile(config, minFile, containsChanges);
            }

            return new MinificationResult(result, null);
        }
示例#19
0
 public Arguments()
 {
     Authentication = new Authentication();
     OverrideConfig = new Config();
     Output = OutputType.Json;
     UpdateAssemblyInfoFileName = new HashSet<string>();
 }
示例#20
0
        public static void Generate(Config config, Stream stream)
        {
            if (config == null)
                throw new ArgumentNullException("config");
            using (var bs = new BufferedStream(stream))
            using (var sw = new StreamWriter(bs, new System.Text.UTF8Encoding(false)))
            {
                sw.NewLine = "\n";

                //sw.WriteLine("# Generated by SpudConf {0}", Assembly.GetExecutingAssembly().GetName().Version);
                //sw.WriteLine(@"#! author = ""{0}""", Properties.Settings.Default.UserName);
                //sw.WriteLine(@"#! date = ""{0}""", DateTime.Now.ToFileTimeUtc());
                foreach (var c in config)
                {
                    foreach (var co in c.Value.Comments)
                    {
                        if (co.Equals("whitespace"))
                        {
                            sw.WriteLine();
                        }
                        else
                        {
                            sw.WriteLine("#{0}", co);
                        }
                    }
                    foreach (var m in c.Value.Metadata)
                    {
                        sw.WriteLine("#!{0} = \"{1}\"", m.Key, m.Value);
                    }
                    sw.WriteLine("{0} = \"{1}\"", c.Key, c.Value.Value);
                }
            }
        }
示例#21
0
 public static ChangeSet GenerateChangeSet(Config oldConfig, Config newConfig)
 {
     var cs = new ChangeSet();
     foreach (var n in oldConfig)
     {
         var oldKey = n.Key;
         if (newConfig.ContainsKey(oldKey))
         {
             var newNode = newConfig[oldKey];
             if (n.Value != newNode)
             {
                 cs.Add(new ConfigChange() { Type = ChangeType.Modified, Key = oldKey, Old = n.Value, New = newNode });
             }
         }
         else
         {
             cs.Add(new ConfigChange() { Type = ChangeType.Removed, Key = oldKey, Old = n.Value, New = null });
         }
     }
     foreach (var n in newConfig)
     {
         var newKey = n.Key;
         if (!oldConfig.ContainsKey(newKey))
         {
             cs.Add(new ConfigChange() { Type = ChangeType.Added, Key = newKey, Old = null, New = newConfig[newKey] });
         }
     }
     return cs;
 }
示例#22
0
        private static MinificationResult MinifyJavaScript(Config config, string file)
        {
            string content = File.ReadAllText(file);
            var settings = JavaScriptOptions.GetSettings(config);

            if (config.Minify.ContainsKey("enabled") && config.Minify["enabled"].ToString().Equals("false", StringComparison.OrdinalIgnoreCase))
                return null;

            var minifier = new Minifier();

            string ext = Path.GetExtension(file);
            string minFile = file.Substring(0, file.LastIndexOf(ext)) + ".min" + ext;
            string mapFile = minFile + ".map";

            string result = minifier.MinifyJavaScript(content, settings);

            bool containsChanges = FileHelpers.HasFileContentChanged(minFile, result);

            if (!string.IsNullOrEmpty(result))
            {
                OnBeforeWritingMinFile(file, minFile, containsChanges);

                if (containsChanges)
                {
                    File.WriteAllText(minFile, result, new UTF8Encoding(true));
                }

                OnAfterWritingMinFile(file, minFile, containsChanges);

                GzipFile(config, minFile, containsChanges);
            }

            return new MinificationResult(result, null);
        }
示例#23
0
        public void TestBackoffStrategyCoerce()
        {
            var c = new Config();

            c.Set("backoff_strategy", "exponential");
            Assert.AreEqual(typeof(ExponentialStrategy), c.BackoffStrategy.GetType());

            c.Set("backoff_strategy", "");
            Assert.AreEqual(typeof(ExponentialStrategy), c.BackoffStrategy.GetType());

            c.Set("backoff_strategy", null);
            Assert.IsNull(c.BackoffStrategy);

            c.Set("backoff_strategy", "full_jitter");
            Assert.AreEqual(typeof(FullJitterStrategy), c.BackoffStrategy.GetType());

            Assert.Throws<Exception>(() => c.Set("backoff_strategy", "invalid"));

            var fullJitterStrategy = new FullJitterStrategy();
            c.Set("backoff_strategy", fullJitterStrategy);
            Assert.AreEqual(fullJitterStrategy, c.BackoffStrategy);

            var exponentialStrategy = new ExponentialStrategy();
            c.Set("backoff_strategy", exponentialStrategy);
            Assert.AreEqual(exponentialStrategy, c.BackoffStrategy);

            Assert.Throws<Exception>(() => c.Set("backoff_strategy", new object()));
        }
示例#24
0
        public CopyClient(Config config, OAuthToken authToken)
        {
            Config = config;
            AuthToken = authToken;

            InitManagers();
        }
        public IMailboxManager CreateMailboxManager(Config.EmailSettings emailSettings)
        {
            var credentials = new EWSConnectionManger.Credentials
            {
                EmailAddress = emailSettings.EWSMailboxAddress,
                UserName = emailSettings.EWSUsername,
                Password = DPAPIHelper.ReadDataFromFile(emailSettings.EWSPasswordFile)
            };

            var exchangeService = _connectionManger.GetConnection(credentials);
            var postProcessor = GetPostProcesor(emailSettings, exchangeService.Service);

            switch (emailSettings.ServiceType)
            {
                case Config.EmailSettings.MailboxServiceType.EWSByFolder:
                    return new FolderMailboxManager(
                        exchangeService.Service, 
                        emailSettings.IncomingFolder,
                        postProcessor);

                case Config.EmailSettings.MailboxServiceType.EWSByRecipients:

                    return new RecipientsMailboxManager(
                        exchangeService.Router,
                        ParseDelimitedList(emailSettings.Recipients, ';'),
                        postProcessor);

                default:
                    throw new BadConfigException(
                        "EmailSettings.ServiceType",
                        string.Format("Invalid mailbox service type defined in config ({0})", emailSettings.ServiceType));
            }
        }
示例#26
0
 public DataModel(string name, string caption, DataType type)
 {
     this.Name = name;
     this.Caption = string.IsNullOrEmpty(caption) ? name: caption;
     this.Type = type;
     Config = new Config();
 }
    public void BranchCreatedAfterFastForwardMergeShouldInheritCorrectly()
    {
        var config = new Config();
        config.Branches.Add("unstable", config.Branches["develop"]);

        using (var fixture = new EmptyRepositoryFixture(config))
        {
            fixture.Repository.MakeATaggedCommit("1.0.0");
            fixture.Repository.CreateBranch("unstable");
            fixture.Repository.Checkout("unstable");

            //Create an initial feature branch
            var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123");
            fixture.Repository.Checkout("feature/JIRA-123");
            fixture.Repository.MakeCommits(1);

            //Merge it
            fixture.Repository.Checkout("unstable");
            fixture.Repository.Merge(feature123, SignatureBuilder.SignatureNow());

            //Create a second feature branch
            fixture.Repository.CreateBranch("feature/JIRA-124");
            fixture.Repository.Checkout("feature/JIRA-124");
            fixture.Repository.MakeCommits(1);

            fixture.AssertFullSemver("1.1.0-JIRA-124.1+2");
        }
    }
示例#28
0
        private void RunCompilerProcess(Config config, FileInfo info)
        {
            string arguments = ConstructArguments(config);

            ProcessStartInfo start = new ProcessStartInfo
            {
                WorkingDirectory = info.Directory.FullName,
                UseShellExecute = false,
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = true,
                FileName = "cmd.exe",
                Arguments = $"/c \"\"{Path.Combine(_path, "node_modules\\.bin\\stylus.cmd")}\" {arguments} \"{info.FullName}\"\"",
                StandardOutputEncoding = Encoding.UTF8,
                StandardErrorEncoding = Encoding.UTF8,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
            };

            start.EnvironmentVariables["PATH"] = _path + ";" + start.EnvironmentVariables["PATH"];

            using (Process p = Process.Start(start))
            {
                var stdout = p.StandardOutput.ReadToEndAsync();
                var stderr = p.StandardError.ReadToEndAsync();
                p.WaitForExit();

                _output = stdout.Result.Trim();
                _error = stderr.Result.Trim();
            }
        }
示例#29
0
        public ConfigViewModel(Config config = null)
        {
            Config = config ?? new Config();

            ConfigPaths = new ObservableCollection<string>(Directory
                .EnumerateFiles("Mappings", "*.xml", SearchOption.AllDirectories));
        }
        public LocalFileSystemVolume( Config.IConnectorConfig config, ICryptoService cryptoService,
			IImageEditorService imageEditorService )
        {
            _config = config;
            _cryptoService = cryptoService;
            _imageEditorService = imageEditorService;
        }
示例#31
0
 private void openModelFolderBtn_Click(object sender, EventArgs e)
 {
     Process.Start("explorer.exe", Config.Get("modelPath"));
 }
示例#32
0
        private void LogicW()
        {
            var t = TargetSelector.GetTarget(W.Range, TargetSelector.DamageType.Magical);

            if (t.IsValidTarget())
            {
                if (Program.Combo && Player.Mana > RMANA + WMANA)
                {
                    W.Cast();
                }
                else if (Program.Farm && Player.Mana > RMANA + QMANA + WMANA && Config.Item("harrasW", true).GetValue <bool>() && Config.Item("harras" + t.ChampionName).GetValue <bool>())
                {
                    W.Cast();
                }
                else if (W.GetDamage(t) + W.GetDamage(t, 1) + Q.GetDamage(t) * 2 > t.Health - OktwCommon.GetIncomingDamage(t))
                {
                    W.Cast();
                }
            }
            else if (Program.LaneClear && QMissile == null && (Player.ManaPercent > Config.Item("Mana", true).GetValue <Slider>().Value&& Config.Item("farmW", true).GetValue <bool>() && Player.Mana > RMANA + WMANA))
            {
                var minionList = Cache.GetMinions(Player.ServerPosition, W.Range, MinionTeam.Enemy);
                foreach (var minion in minionList.Where(minion => minion.Health < W.GetDamage(minion)))
                {
                    W.Cast();
                }
            }
        }
示例#33
0
        public DeploySearchIndexes()
        {
            Deployment = true;

            OutputModules = new ModuleList
            {
                new ThrowException(Config.FromSettings(x => x.ContainsKey("ALGOLIA_TOKEN") ? null : "The setting ALGOLIA_TOKEN must be defined")),

                // Projects

                /*
                 * new ReplaceDocuments(nameof(Projects.Projects)),
                 * new UpdateSearchIndex(
                 *  ApplicationId,
                 *  Config.FromSetting<string>("ALGOLIA_TOKEN"),
                 *  "projects",
                 *  Config.FromValue<IEnumerable<string>>(new[]
                 *  {
                 *      SiteKeys.Key,
                 *      SiteKeys.Title,
                 *      SiteKeys.Description,
                 *      SiteKeys.StargazersCount,
                 *      SiteKeys.Tags
                 *  })),
                 *
                 * // Blogs
                 * new ReplaceDocuments(nameof(Blogs.Blogs)),
                 * new UpdateSearchIndex(
                 *  ApplicationId,
                 *  Config.FromSetting<string>("ALGOLIA_TOKEN"),
                 *  "blogs",
                 *  Config.FromValue<IEnumerable<string>>(new[]
                 *  {
                 *      SiteKeys.Key,
                 *      SiteKeys.Title,
                 *      SiteKeys.Description
                 *  })),
                 *
                 * // Posts
                 * new ReplaceDocuments(nameof(Posts)),
                 * new FilterDocuments(Config.FromDocument(doc => doc.ContainsKey(SiteKeys.FeedItems) && doc.GetString(SiteKeys.Language) == "English")),
                 * new ExecuteConfig(Config.FromDocument((doc, ctx) => doc
                 *  .Get<IEnumerable<FeedItem>>(SiteKeys.FeedItems)
                 *  .Select(x => ctx.CreateDocument(new MetadataItems
                 *  {
                 *      { SiteKeys.Title, x.Title },
                 *      { SiteKeys.Link, x.Link },
                 *      { SiteKeys.Published, x.Published }
                 *  })))),
                 * new UpdateSearchIndex(
                 *  ApplicationId,
                 *  Config.FromSetting<string>("ALGOLIA_TOKEN"),
                 *  "posts",
                 *  Config.FromValue<IEnumerable<string>>(new[]
                 *  {
                 *      SiteKeys.Title,
                 *      SiteKeys.Link,
                 *      SiteKeys.Published
                 *  })),
                 *
                 * // Broadcasts
                 * new ReplaceDocuments(nameof(Broadcasts.Broadcasts)),
                 * new UpdateSearchIndex(
                 *  ApplicationId,
                 *  Config.FromSetting<string>("ALGOLIA_TOKEN"),
                 *  "broadcasts",
                 *  Config.FromValue<IEnumerable<string>>(new[]
                 *  {
                 *      SiteKeys.Key,
                 *      SiteKeys.Title,
                 *      SiteKeys.Description
                 *  })),
                 *
                 * // Episodes
                 * new ReplaceDocuments(nameof(Episodes)),
                 * new FilterDocuments(Config.FromDocument(doc => doc.ContainsKey(SiteKeys.FeedItems) && doc.GetString(SiteKeys.Language) == "English")),
                 * new ExecuteConfig(Config.FromDocument((doc, ctx) => doc
                 *  .Get<IEnumerable<FeedItem>>(SiteKeys.FeedItems)
                 *  .Select(x => ctx.CreateDocument(new MetadataItems
                 *  {
                 *      { SiteKeys.Title, x.Title },
                 *      { SiteKeys.Link, x.Link },
                 *      { SiteKeys.Published, x.Published }
                 *  })))),
                 * new UpdateSearchIndex(
                 *  ApplicationId,
                 *  Config.FromSetting<string>("ALGOLIA_TOKEN"),
                 *  "episodes",
                 *  Config.FromValue<IEnumerable<string>>(new[]
                 *  {
                 *      SiteKeys.Title,
                 *      SiteKeys.Link,
                 *      SiteKeys.Published
                 *  })),
                 *
                 * // Resources
                 * new ReplaceDocuments(nameof(Resources.Resources)),
                 * new UpdateSearchIndex(
                 *  ApplicationId,
                 *  Config.FromSetting<string>("ALGOLIA_TOKEN"),
                 *  "resources",
                 *  Config.FromValue<IEnumerable<string>>(new[]
                 *  {
                 *      SiteKeys.Website,
                 *      SiteKeys.Title,
                 *      SiteKeys.Description,
                 *      SiteKeys.Tags
                 *  })),
                 */
            };
        }
示例#34
0
 public Negamax(int playerNumber, int boardSize, Config playerConfig) : base(playerNumber, boardSize, playerConfig)
 {
     Setup(boardSize, playerNumber, playerConfig);
 }
示例#35
0
 public MakeExcelFile(Config config, ErrorLogging error)
 {
     _config = config;
     _error  = error;
 }
示例#36
0
        private void Drawing_OnDraw(EventArgs args)
        {
            if (Config.Item("qRange", true).GetValue <bool>())
            {
                if (Config.Item("onlyRdy", true).GetValue <bool>())
                {
                    if (Q.IsReady())
                    {
                        Utility.DrawCircle(Player.Position, Q.Range, System.Drawing.Color.Cyan, 1, 1);
                    }
                }
                else
                {
                    Utility.DrawCircle(Player.Position, Q.Range, System.Drawing.Color.Cyan, 1, 1);
                }
            }

            if (Config.Item("wRange", true).GetValue <bool>())
            {
                if (Config.Item("onlyRdy", true).GetValue <bool>())
                {
                    if (W.IsReady())
                    {
                        Utility.DrawCircle(Player.Position, W.Range, System.Drawing.Color.Orange, 1, 1);
                    }
                }
                else
                {
                    Utility.DrawCircle(Player.Position, W.Range, System.Drawing.Color.Orange, 1, 1);
                }
            }

            if (Config.Item("eRange", true).GetValue <bool>())
            {
                if (Config.Item("onlyRdy", true).GetValue <bool>())
                {
                    if (E.IsReady())
                    {
                        Utility.DrawCircle(Player.Position, E.Range, System.Drawing.Color.Yellow, 1, 1);
                    }
                }
                else
                {
                    Utility.DrawCircle(Player.Position, E.Range, System.Drawing.Color.Yellow, 1, 1);
                }
            }

            if (Config.Item("noti", true).GetValue <bool>())
            {
                var t = TargetSelector.GetTarget(1500, TargetSelector.DamageType.Physical);

                if (t.IsValidTarget())
                {
                    var comboDmg = 0f;
                    if (R.IsReady())
                    {
                        comboDmg += R.GetDamage(t) * 3;
                    }
                    if (Q.IsReady())
                    {
                        comboDmg += Q.GetDamage(t) * 2;
                    }
                    if (W.IsReady())
                    {
                        comboDmg += W.GetDamage(t) + W.GetDamage(t, 1);
                    }
                    if (comboDmg > t.Health)
                    {
                        Drawing.DrawText(Drawing.Width * 0.1f, Drawing.Height * 0.5f, System.Drawing.Color.Red, "COMBO KILL " + t.ChampionName + " have: " + t.Health + "hp");
                        drawLine(t.Position, Player.Position, 10, System.Drawing.Color.Yellow);
                    }
                }
            }
        }
示例#37
0
        private void LogicE()
        {
            foreach (var enemy in HeroManager.Enemies.Where(enemy => enemy.IsValidTarget(E.Range) && E.GetDamage(enemy) + Q.GetDamage(enemy) + W.GetDamage(enemy) + OktwCommon.GetEchoLudenDamage(enemy) > enemy.Health))
            {
                Program.CastSpell(E, enemy);
            }
            var t = Orbwalker.GetTarget() as Obj_AI_Hero;

            if (!t.IsValidTarget())
            {
                t = TargetSelector.GetTarget(E.Range, TargetSelector.DamageType.Magical);
            }
            if (t.IsValidTarget())
            {
                if (Program.Combo && Player.Mana > RMANA + EMANA && Config.Item("Eon" + t.ChampionName, true).GetValue <bool>())
                {
                    Program.CastSpell(E, t);
                }
                else if (Program.Farm && Config.Item("harrasE", true).GetValue <bool>() && Config.Item("harras" + t.ChampionName).GetValue <bool>() && Player.Mana > RMANA + EMANA + WMANA + EMANA)
                {
                    Program.CastSpell(E, t);
                }
                else if (OktwCommon.GetKsDamage(t, E) > t.Health)
                {
                    Program.CastSpell(E, t);
                }
                if (Player.Mana > RMANA + EMANA)
                {
                    foreach (var enemy in HeroManager.Enemies.Where(enemy => enemy.IsValidTarget(E.Range) && !OktwCommon.CanMove(enemy) && Config.Item("Eon" + enemy.ChampionName, true).GetValue <bool>()))
                    {
                        E.Cast(enemy);
                    }
                }
            }
        }
示例#38
0
        private void LogicQ()
        {
            var t = TargetSelector.GetTarget(Q.Range, TargetSelector.DamageType.Magical);

            if (t.IsValidTarget())
            {
                missileManager.Target = t;
                if (EMissile == null || !EMissile.IsValid)
                {
                    if (Program.Combo && Player.Mana > RMANA + QMANA)
                    {
                        Program.CastSpell(Q, t);
                    }
                    else if (Program.Farm && Player.Mana > RMANA + WMANA + QMANA + QMANA && Config.Item("harrasQ", true).GetValue <bool>() && Config.Item("harras" + t.ChampionName).GetValue <bool>() && OktwCommon.CanHarras())
                    {
                        Program.CastSpell(Q, t);
                    }
                    else if (Q.GetDamage(t) * 2 + OktwCommon.GetEchoLudenDamage(t) > t.Health - OktwCommon.GetIncomingDamage(t))
                    {
                        Q.Cast(t, true);
                    }
                }
                if (!Program.None && Player.Mana > RMANA + WMANA)
                {
                    foreach (var enemy in HeroManager.Enemies.Where(enemy => enemy.IsValidTarget(Q.Range) && !OktwCommon.CanMove(enemy)))
                    {
                        Q.Cast(enemy, true);
                    }
                }
            }
            else if (Program.LaneClear && Player.ManaPercent > Config.Item("Mana", true).GetValue <Slider>().Value&& Config.Item("farmQ", true).GetValue <bool>() && Player.Mana > RMANA + QMANA)
            {
                var minionList   = Cache.GetMinions(Player.ServerPosition, Q.Range);
                var farmPosition = Q.GetLineFarmLocation(minionList, Q.Width);
                if (farmPosition.MinionsHit > Config.Item("LCminions", true).GetValue <Slider>().Value)
                {
                    Q.Cast(farmPosition.Position);
                }
            }
        }
示例#39
0
        private void LogicR()
        {
            var dashPosition = Player.Position.Extend(Game.CursorPos, 450);

            if (Player.Distance(Game.CursorPos) < 450)
            {
                dashPosition = Game.CursorPos;
            }

            if (dashPosition.CountEnemiesInRange(800) > 2)
            {
                return;
            }

            if (Config.Item("autoR2", true).GetValue <bool>())
            {
                if (Player.HasBuff("AhriTumble"))
                {
                    var BuffTime = OktwCommon.GetPassiveTime(Player, "AhriTumble");
                    if (BuffTime < 3)
                    {
                        R.Cast(dashPosition);
                    }

                    var posPred = missileManager.CalculateReturnPos();
                    if (posPred != Vector3.Zero)
                    {
                        if (missileManager.Missile.SData.Name == "AhriOrbReturn" && Player.Distance(posPred) > 200)
                        {
                            R.Cast(posPred);
                            Program.debug("AIMMMM");
                        }
                    }
                }
            }

            if (Config.Item("autoR", true).GetValue <bool>())
            {
                var t = TargetSelector.GetTarget(450 + R.Range, TargetSelector.DamageType.Magical);
                if (t.IsValidTarget())
                {
                    var comboDmg = R.GetDamage(t) * 3;
                    if (Q.IsReady())
                    {
                        comboDmg += Q.GetDamage(t) * 2;
                    }
                    if (W.IsReady())
                    {
                        comboDmg += W.GetDamage(t) + W.GetDamage(t, 1);
                    }
                    if (t.CountAlliesInRange(600) < 2 && comboDmg > t.Health && t.Position.Distance(Game.CursorPos) < t.Position.Distance(Player.Position) && dashPosition.Distance(t.ServerPosition) < 500)
                    {
                        R.Cast(dashPosition);
                    }

                    foreach (var target in HeroManager.Enemies.Where(target => target.IsMelee && target.IsValidTarget(300)))
                    {
                        R.Cast(dashPosition);
                    }
                }
            }
        }
示例#40
0
        public void LoadOKTW()
        {
            Q = new Spell(SpellSlot.Q, 870);
            W = new Spell(SpellSlot.W, 580);
            E = new Spell(SpellSlot.E, 950);
            R = new Spell(SpellSlot.R, 600);

            Q.SetSkillshot(0.25f, 90, 1550, false, SkillshotType.SkillshotLine);
            E.SetSkillshot(0.25f, 60, 1550, true, SkillshotType.SkillshotLine);

            missileManager = new Core.MissileReturn("AhriOrbMissile", "AhriOrbReturn", Q);

            Config.SubMenu(Player.ChampionName).SubMenu("Draw").AddItem(new MenuItem("noti", "Show notification & line", true).SetValue(true));
            Config.SubMenu(Player.ChampionName).SubMenu("Draw").AddItem(new MenuItem("onlyRdy", "Draw only ready spells", true).SetValue(true));
            Config.SubMenu(Player.ChampionName).SubMenu("Draw").AddItem(new MenuItem("qRange", "Q range", true).SetValue(false));
            Config.SubMenu(Player.ChampionName).SubMenu("Draw").AddItem(new MenuItem("wRange", "W range", true).SetValue(false));
            Config.SubMenu(Player.ChampionName).SubMenu("Draw").AddItem(new MenuItem("eRange", "E range", true).SetValue(false));
            Config.SubMenu(Player.ChampionName).SubMenu("Draw").AddItem(new MenuItem("rRange", "R range", true).SetValue(false));
            Config.SubMenu(Player.ChampionName).SubMenu("Draw").AddItem(new MenuItem("Qhelp", "Show Q helper", true).SetValue(true));

            Config.SubMenu(Player.ChampionName).SubMenu("Q Config").AddItem(new MenuItem("autoQ", "Auto Q", true).SetValue(true));
            Config.SubMenu(Player.ChampionName).SubMenu("Q Config").AddItem(new MenuItem("harrasQ", "Harass Q", true).SetValue(true));
            Config.SubMenu(Player.ChampionName).SubMenu("Q Config").AddItem(new MenuItem("aimQ", "Auto aim Q missile", true).SetValue(true));

            Config.SubMenu(Player.ChampionName).SubMenu("W Config").AddItem(new MenuItem("autoW", "Auto W", true).SetValue(true));
            Config.SubMenu(Player.ChampionName).SubMenu("W Config").AddItem(new MenuItem("harrasW", "Harass W", true).SetValue(true));

            Config.SubMenu(Player.ChampionName).SubMenu("E Config").AddItem(new MenuItem("autoE", "Auto E", true).SetValue(true));
            Config.SubMenu(Player.ChampionName).SubMenu("E Config").AddItem(new MenuItem("harrasE", "Harras E", true).SetValue(true));

            foreach (var enemy in HeroManager.Enemies)
            {
                Config.SubMenu(Player.ChampionName).SubMenu("E Config").SubMenu("Use E on").AddItem(new MenuItem("Eon" + enemy.ChampionName, enemy.ChampionName, true).SetValue(true));
            }

            foreach (var enemy in HeroManager.Enemies)
            {
                Config.SubMenu(Player.ChampionName).SubMenu("E Config").SubMenu("Gapcloser").AddItem(new MenuItem("Egapcloser" + enemy.ChampionName, enemy.ChampionName, true).SetValue(true));
            }

            Config.SubMenu(Player.ChampionName).SubMenu("R Config").AddItem(new MenuItem("autoR", "R KS ", true).SetValue(true));
            Config.SubMenu(Player.ChampionName).SubMenu("R Config").AddItem(new MenuItem("autoR2", "auto R fight logic + aim Q", true).SetValue(true));

            foreach (var enemy in HeroManager.Enemies)
            {
                Config.SubMenu(Player.ChampionName).SubMenu("Harras").AddItem(new MenuItem("harras" + enemy.ChampionName, enemy.ChampionName).SetValue(true));
            }

            Config.SubMenu(Player.ChampionName).SubMenu("Farm").AddItem(new MenuItem("farmQ", "Lane clear Q", true).SetValue(true));
            Config.SubMenu(Player.ChampionName).SubMenu("Farm").AddItem(new MenuItem("farmW", "Lane clear W", true).SetValue(false));
            Config.SubMenu(Player.ChampionName).SubMenu("Farm").AddItem(new MenuItem("Mana", "LaneClear Mana", true).SetValue(new Slider(80, 100, 0)));
            Config.SubMenu(Player.ChampionName).SubMenu("Farm").AddItem(new MenuItem("LCminions", "LaneClear minimum minions", true).SetValue(new Slider(2, 10, 0)));
            Config.SubMenu(Player.ChampionName).SubMenu("Farm").AddItem(new MenuItem("jungleQ", "Jungle clear Q", true).SetValue(true));
            Config.SubMenu(Player.ChampionName).SubMenu("Farm").AddItem(new MenuItem("jungleW", "Jungle clear W", true).SetValue(true));

            Game.OnUpdate += Game_OnGameUpdate;
            Interrupter2.OnInterruptableTarget += Interrupter2_OnInterruptableTarget;
            AntiGapcloser.OnEnemyGapcloser     += AntiGapcloser_OnEnemyGapcloser;
            Drawing.OnDraw      += Drawing_OnDraw;
            GameObject.OnCreate += SpellMissile_OnCreateOld;
            GameObject.OnDelete += Obj_SpellMissile_OnDelete;
        }
 public ReplaceDocuments(Config<IEnumerable<IDocument>> documents)
     : base(new ExecuteConfig(documents))
 {
 }
        /// <summary>
        /// Do your analysis. This method is called once per segment (typically one-minute segments).
        /// </summary>
        public override RecognizerResults Recognize(AudioRecording recording, Config configuration, TimeSpan segmentStartOffset, Lazy <IndexCalculateResult[]> getSpectralIndexes, DirectoryInfo outputDirectory, int?imageWidth)
        {
            string speciesName            = configuration[AnalysisKeys.SpeciesName] ?? "<no species>";
            string abbreviatedSpeciesName = configuration[AnalysisKeys.AbbreviatedSpeciesName] ?? "<no.sp>";

            int minHz = configuration.GetInt(AnalysisKeys.MinHz);
            int maxHz = configuration.GetInt(AnalysisKeys.MaxHz);

            // BETTER TO CALCULATE THIS. IGNORE USER!
            // double frameOverlap = Double.Parse(configDict[Keys.FRAME_OVERLAP]);

            // duration of DCT in seconds
            double dctDuration = configuration.GetDouble(AnalysisKeys.DctDuration);

            // minimum acceptable value of a DCT coefficient
            double dctThreshold = configuration.GetDouble(AnalysisKeys.DctThreshold);

            // ignore oscillations below this threshold freq
            int minOscilFreq = configuration.GetInt(AnalysisKeys.MinOscilFreq);

            // ignore oscillations above this threshold freq
            int maxOscilFreq = configuration.GetInt(AnalysisKeys.MaxOscilFreq);

            // min duration of event in seconds
            double minDuration = configuration.GetDouble(AnalysisKeys.MinDuration);

            // max duration of event in seconds
            double maxDuration = configuration.GetDouble(AnalysisKeys.MaxDuration);

            // min score for an acceptable event
            double eventThreshold = configuration.GetDouble(AnalysisKeys.EventThreshold);

            if (recording.WavReader.SampleRate != 22050)
            {
                throw new InvalidOperationException("Requires a 22050Hz file");
            }

            // The default was 512 for Canetoad.
            // Framesize = 128 seems to work for Littoria fallax.
            const int FrameSize     = 128;
            double    windowOverlap = Oscillations2012.CalculateRequiredFrameOverlap(
                recording.SampleRate,
                FrameSize,
                maxOscilFreq);

            //windowOverlap = 0.75; // previous default

            // i: MAKE SONOGRAM
            var sonoConfig = new SonogramConfig
            {
                SourceFName   = recording.BaseName,
                WindowSize    = FrameSize,
                WindowOverlap = windowOverlap,

                //NoiseReductionType = NoiseReductionType.NONE,
                NoiseReductionType      = NoiseReductionType.None,
                NoiseReductionParameter = 0.1,
            };

            // sonoConfig.NoiseReductionType = SNR.Key2NoiseReductionType("STANDARD");
            TimeSpan     recordingDuration = recording.Duration;
            int          sr           = recording.SampleRate;
            double       freqBinWidth = sr / (double)sonoConfig.WindowSize;
            BaseSonogram sonogram     = new SpectrogramStandard(sonoConfig, recording.WavReader);
            int          rowCount     = sonogram.Data.GetLength(0);
            int          colCount     = sonogram.Data.GetLength(1);

            // double[,] subMatrix = MatrixTools.Submatrix(sonogram.Data, 0, minBin, (rowCount - 1), maxbin);

            // ######################################################################
            // ii: DO THE ANALYSIS AND RECOVER SCORES OR WHATEVER
            // This window is used to smooth the score array before extracting events.
            // A short window (e.g. 3) preserves sharper score edges to define events but also keeps noise.
            int scoreSmoothingWindow = 13;

            Oscillations2012.Execute(
                (SpectrogramStandard)sonogram,
                minHz,
                maxHz,
                dctDuration,
                minOscilFreq,
                maxOscilFreq,
                dctThreshold,
                eventThreshold,
                minDuration,
                maxDuration,
                scoreSmoothingWindow,
                out var scores,
                out var acousticEvents,
                out var hits,
                segmentStartOffset);

            acousticEvents.ForEach(ae =>
            {
                ae.SpeciesName            = speciesName;
                ae.SegmentDurationSeconds = recordingDuration.TotalSeconds;
                ae.SegmentStartSeconds    = segmentStartOffset.TotalSeconds;
                ae.Name = abbreviatedSpeciesName;
            });

            var plot  = new Plot(this.DisplayName, scores, eventThreshold);
            var plots = new List <Plot> {
                plot
            };

            this.WriteDebugImage(recording, outputDirectory, sonogram, acousticEvents, plots, hits);

            return(new RecognizerResults()
            {
                Sonogram = sonogram,
                Hits = hits,
                Plots = plots,
                Events = acousticEvents,
            });
        }
示例#43
0
 private void simpleButton1_Click(object sender, EventArgs e)
 {
     Config.NewKeyValue("MaCa", MaCa);
     this.DialogResult = DialogResult.OK;
 }
 public ReplaceDocuments(params string[] pipelines)
     : base(new ExecuteConfig(Config.FromContext(ctx => ctx.Outputs.FromPipelines(pipelines))))
 {
 }
示例#45
0
        public void ReadConfig()
        {
            try
            {
                var mCam          = new HmdMatrix34_t();
                var readCamMatrix = false;

                object c     = config; // box
                var    lines = System.IO.File.ReadAllLines(configPath);
                foreach (var line in lines)
                {
                    var split = line.Split('=');
                    if (split.Length == 2)
                    {
                        var key = split[0];
                        if (key == "m")
                        {
                            var values = split[1].Split(',');
                            if (values.Length == 12)
                            {
                                mCam.m0       = float.Parse(values[0]);
                                mCam.m1       = float.Parse(values[1]);
                                mCam.m2       = float.Parse(values[2]);
                                mCam.m3       = float.Parse(values[3]);
                                mCam.m4       = float.Parse(values[4]);
                                mCam.m5       = float.Parse(values[5]);
                                mCam.m6       = float.Parse(values[6]);
                                mCam.m7       = float.Parse(values[7]);
                                mCam.m8       = float.Parse(values[8]);
                                mCam.m9       = float.Parse(values[9]);
                                mCam.m10      = float.Parse(values[10]);
                                mCam.m11      = float.Parse(values[11]);
                                readCamMatrix = true;
                            }
                        }
#if !UNITY_METRO
                        else if (key == "disableStandardAssets")
                        {
                            var field = c.GetType().GetField(key);
                            if (field != null)
                            {
                                field.SetValue(c, bool.Parse(split[1]));
                            }
                        }
                        else
                        {
                            var field = c.GetType().GetField(key);
                            if (field != null)
                            {
                                field.SetValue(c, float.Parse(split[1]));
                            }
                        }
#endif
                    }
                }
                config = (Config)c; //unbox

                // Convert calibrated camera matrix settings.
                if (readCamMatrix)
                {
                    var t = new SteamVR_Utils.RigidTransform(mCam);
                    config.x = t.pos.x;
                    config.y = t.pos.y;
                    config.z = t.pos.z;
                    var angles = t.rot.eulerAngles;
                    config.rx = angles.x;
                    config.ry = angles.y;
                    config.rz = angles.z;
                }
            }
            catch { }

            // Clear target so AttachToCamera gets called to pick up any changes.
            target = null;
#if !UNITY_METRO
            // Listen for changes.
            if (watcher == null)
            {
                var fi = new System.IO.FileInfo(configPath);
                watcher = new System.IO.FileSystemWatcher(fi.DirectoryName, fi.Name);
                watcher.NotifyFilter        = System.IO.NotifyFilters.LastWrite;
                watcher.Changed            += new System.IO.FileSystemEventHandler(OnChanged);
                watcher.EnableRaisingEvents = true;
            }
        }
        public static JordanWignerEncodingData GetQSharpData(string filename, string wavefunctionLabel, Config configuration)
        {
            using var reader = File.OpenText(filename);
            var broombridge = BroombridgeSerializer.Deserialize(reader).First();

            var orbHam = broombridge.OrbitalIntegralHamiltonian;

            var ferHam = orbHam.ToFermionHamiltonian(configuration.UseIndexConvention);

            var pauHam = ferHam.ToPauliHamiltonian();

            var hamiltonian = pauHam.ToQSharpFormat();

            var inputStates = broombridge.InitialStates ?? new Dictionary <string, FermionWavefunction <SpinOrbital> >();

            // If no states are provided, use the Hartree--Fock state.
            // As fermion operators the fermion Hamiltonian are already indexed by, we now apply the desired
            // spin-orbital -> integer indexing convention.
            FermionWavefunction <int> wavefunction = inputStates.ContainsKey(wavefunctionLabel)
                ? inputStates[wavefunctionLabel].ToIndexing(configuration.UseIndexConvention)
                : ferHam.CreateHartreeFockState(broombridge.NElectrons);

            var qSharpData = Microsoft.Quantum.Chemistry.QSharpFormat.Convert.ToQSharpFormat(hamiltonian, wavefunction.ToQSharpFormat());

            return(qSharpData);
        }
示例#47
0
 internal void Main()
 {
     Logger  = base.Logger;
     Enabled = Config.Bind("Config", "Pose Quick Loading", false, "Whether poses in Studio will be loaded by clicking on them. Vanilla behavior requires you to select the pose and then press load.");
     Harmony.CreateAndPatchAll(typeof(Hooks));
 }
示例#48
0
        /*  Ctor
         *      -----------------------------------------------------------------------------------------------*/

        /// <summary>
        ///
        /// </summary>
        public LengthValidation(Config config)
        {
            this.Apply(config);
        }
示例#49
0
 public PipelineBuilder WithPostProcessConfig(Config <object> config)
 {
     _actions.Add(x => x.WithPostProcessConfig(config));
     return(this);
 }
示例#50
0
 public void LoadEsrganOptions()
 {
     Config.LoadGuiElement(alpha);
     Config.LoadComboxIndex(seamlessMode);
 }
示例#51
0
        /*  Ctor
         *      -----------------------------------------------------------------------------------------------*/

        /// <summary>
        ///
        /// </summary>
        public TimeField(Config config)
        {
            this.Apply(config);
        }
示例#52
0
 public BlockchainMailbox(Akka.Actor.Settings settings, Config config)
     : base(settings, config)
 {
 }
示例#53
0
 // The default Razor delay has always been 50ms, but for CUO, that delay isn't needed since it isn't
 // passing messages back and forth.
 public MacroTimer() : base(TimeSpan.FromMilliseconds(Config.GetBool("MacroActionDelay") ? 50 : 0),
                            TimeSpan.FromMilliseconds(Config.GetBool("MacroActionDelay") ? 50 : 0))
 {
 }
 public DeviceGroupRepository(Config config, Client client = null) : base(config, client)
 {
 }
示例#55
0
 public PipelineBuilder WithOutputConfig(Config <object> config)
 {
     _actions.Add(x => x.WithOutputConfig(config));
     return(this);
 }
示例#56
0
    private string UpdateFiles()
    {
        string             text  = "";
        HttpFileCollection files = HttpContext.Current.Request.Files;
        string             text2 = DateTime.Now.ToString("yyMMdd");
        string             text3 = base.Server.MapPath("~/Files/Common/");
        string             str   = "~/Files/Common/" + text2 + "/";

        text3 += text2;
        if (!Directory.Exists(text3))
        {
            FileSystemManager.CreateFolder(text2, base.Server.MapPath("~/Files/Common"));
        }
        try
        {
            string str2 = "";
            if (this.Attachword.Visible)
            {
                foreach (RepeaterItem repeaterItem in this.rpt.Items)
                {
                    HtmlInputCheckBox htmlInputCheckBox = repeaterItem.FindControl("chk") as HtmlInputCheckBox;
                    if (htmlInputCheckBox.Checked)
                    {
                        str2 = str2 + htmlInputCheckBox.Value + "|";
                    }
                }
            }
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile httpPostedFile = files[i];
                if (Config.IsValidFile(httpPostedFile))
                {
                    string fileName = Path.GetFileName(httpPostedFile.FileName);
                    string str3     = str + fileName;
                    string text4    = text3 + "\\" + fileName;
                    if (File.Exists(text4))
                    {
                        string text5 = string.Concat(new object[]
                        {
                            DateTime.Now.ToString("HHmmssfff"),
                            Utils.CreateRandomStr(3),
                            this.Uid,
                            i
                        });
                        text4 = string.Concat(new string[]
                        {
                            text3,
                            "\\",
                            text5,
                            "@",
                            Utils.GetFileExtension(fileName)
                        });
                        str3 = str + text5 + "@" + Utils.GetFileExtension(fileName);
                    }
                    httpPostedFile.SaveAs(text4);
                    text = text + str3 + "|";
                }
            }
            text = str2 + text;
        }
        catch (IOException ex)
        {
            throw;
        }
        return(text);
    }
        public static String strReplaceCenter(Config config, String request, Hashtable replaceList)
        {
            //修改随机值
            request = Regex.Replace(request, "(\\<Rand\\>[.\\s\\S]*?\\<\\/Rand\\>)", System.Guid.NewGuid().ToString("N"));
            //找到需要处理的字符
            MatchCollection mc  = Regex.Matches(request, "(?<=(\\<Encode\\>))[.\\s\\S]*?(?=(\\<\\/Encode\\>))");
            String          str = "";

            foreach (Match m in mc)
            {
                str = m.Value;
                str = bypassUseBetweentAnd(config, str);
                if (config.reaplaceBeforURLEncode || config.isOpenURLEncoding == false)
                {
                    //替换字符
                    str = ReplaceString(replaceList, str);
                    if (config.inculdeStr)
                    {
                        String split = " ";
                        ///*!包含分隔符*/
                        String val = getValue(replaceList, " ");
                        if (!"".Equals(val))
                        {
                            split = val;
                        }
                        str = IncludeString(str);
                    }
                    if (config.useUnicode)
                    {
                        //unicode
                        str = Tools.String2Unicode(str);
                    }
                    else
                    {
                        if (config.isOpenURLEncoding)
                        {
                            //URL编码
                            str = urlEncoding(str, config.urlencodeCount);
                        }
                    }
                }
                else
                {
                    if (config.inculdeStr)
                    {
                        ///*!包含*/
                        str = IncludeString(str);
                    }

                    if (config.useUnicode)
                    {
                        str = Tools.String2Unicode(str);
                    }
                    else
                    {
                        //unicode
                        if (config.isOpenURLEncoding)
                        {
                            //URL编码
                            str = urlEncoding(str, config.urlencodeCount);
                        }
                    }

                    //替换字符
                    str = ReplaceString(replaceList, str);
                }
                //随机大小写
                if (config.keyReplace > 0)
                {
                    String splitstr = " ";
                    if (config.isOpenURLEncoding)
                    {
                        splitstr = "%20";
                    }
                    str = toLowerOrUpperCase(str, splitstr, config.keyReplace);
                }
                //base64处理
                if (config.base64Count > 0)
                {
                    str = base64Encoding(str, config.base64Count);
                }

                //hex处理
                if (config.usehex)
                {
                    str = Tools.strToHex(str, "UTF-8");
                }

                //替换request
                request = request.Replace("<Encode>" + m.Value + "</Encode>", str);
            }
            return(request);
        }
        public static String bypassUseBetweentAnd(Config config, String paylaod)
        {
            if (config.useBetweenByPass)
            {
                MatchCollection mc = Regex.Matches(paylaod, @"(?<str>[\>\<\=]+)(?<len>\d+)");;
                if (mc.Count <= 0)
                {
                    return(paylaod);
                }
                int offset = 0;
                foreach (Match mt in mc)
                {
                    String mstr   = mt.Groups["str"].Value;
                    int    findex = mt.Index;
                    String is16   = "";
                    if (findex != 0 && findex < paylaod.Length - mt.Length - offset)
                    {
                        is16 = paylaod.Substring(findex + offset, mt.Length + 1);
                    }
                    if (is16.Contains("0x"))
                    {
                        //判断是否存在16进制情况,有则跳出
                        continue;
                    }
                    else
                    {
                        int len = Tools.convertToInt(mt.Groups["len"].Value);

                        if (mstr.Contains(">="))
                        {
                            String rp = " not between 0 and " + (len - 1);
                            paylaod = paylaod.Remove(findex + offset, mt.Length).Insert(findex + offset, rp);
                            offset += rp.Length - mt.Length;
                        }
                        else if (mstr.Equals("<="))
                        {
                            String rp = " between 0 and " + len;
                            paylaod = paylaod.Remove(findex, mt.Length).Insert(findex, rp);
                        }
                        else if (mstr.Equals(">"))
                        {
                            String rp = " not between 0 and " + len;
                            paylaod = paylaod.Remove(findex + offset, mt.Length).Insert(findex + offset, rp);
                            offset += rp.Length - mt.Length;
                        }
                        else if (mstr.Equals("="))
                        {
                            String rp = " between " + len + " and " + len;
                            paylaod = paylaod.Remove(findex + offset, mt.Length).Insert(findex + offset, rp);
                            offset += rp.Length - mt.Length;
                        }

                        else if (mstr.Equals("<"))
                        {
                            String rp = " between 0 and " + (len - 1);
                            paylaod = paylaod.Remove(findex, mt.Length).Insert(findex, rp);
                            offset += rp.Length - mt.Length;
                        }
                    }
                }
            }
            return(paylaod);
        }
        /*  Ctor
         *      -----------------------------------------------------------------------------------------------*/

        /// <summary>
        ///
        /// </summary>
        public CommandFill(Config config)
        {
            this.Apply(config);
        }
示例#60
0
 /// <summary>
 /// 初始化复选框渲染器
 /// </summary>
 /// <param name="config">配置</param>
 public CheckBoxRender(Config config) : base(config)
 {
     _config = config;
 }