Пример #1
0
 //-------------------------------------------------------------------------
 public ProcessingTempFrameFile(CancellationToken cancellationToken, OcrAppConfig defaults, string fileName, List<string> errorFiles, IOHelper ioHelper, ref string lastSheetId)
 {
     this.defaults = defaults;
     this.fileName = fileName;
     this.errorFiles = errorFiles;
     this.ioHelper = ioHelper;
     this.cancellationToken = cancellationToken;
     this.lastSheetIdentifier = lastSheetId;
     string shId;
     Working(out shId);
     lastSheetId = shId;
 }
        internal void StartUSBCloneEngine(string destinationDirectory)
        {
            this.destinationDirectory = destinationDirectory;
            ioHelper = new IOHelper();

            insertQuery = new WqlEventQuery(UsbDetectionQuery);
            insertWatcher = new ManagementEventWatcher(insertQuery);

            insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);

            insertWatcher.Start();
        }
Пример #3
0
 public FormEditParam(object title, object value, decimal minValue, decimal maxValue, IOHelper ioHelper)
 {
     InitializeComponent();
     this.label1.Text = string.Format("{0}", title);
     this.Text = string.Format(L.R("FormEditParam.Text", "{0}修改"), title);
     this.spinEdit1.EditValue = value;
     this.spinEdit1.Properties.MaxValue = maxValue;
     this.spinEdit1.Properties.MinValue = minValue;
     this.ioHelper = ioHelper;
     this.title = title;
     this.oldValue = Convert.ToInt32(value);
 }
Пример #4
0
 private MySqlConnection GetGoatDBConnection()
 {
     if (connection == null)
     {
         //set the physical path to the SQLite database
         //var connectionstring = "SERVER=localhost;PORT=3306;DATABASE=webgoat_coins;UID=root;PWD=root";
         var iohelper = new IOHelper(server);
         string connectionstring = iohelper.GetDBConfigString();
         connection = new MySqlConnection(connectionstring);
     }
     if(connection.State == ConnectionState.Closed) connection.Open();
     return connection;
 }
Пример #5
0
		protected void Page_Load (object sender, EventArgs e)
		{
            if(!Page.IsPostBack)
            {
                IOHelper iohelper = new IOHelper(Server);
                var values = iohelper.GetDBConfigDictionary();
                txtServer.Text = values["SERVER"];
                txtPort.Text = values["PORT"];
                txtDatabase.Text = values["DATABASE"];
                txtUserName.Text = values["UID"];
                txtPassword.Text = values["PWD"];
            }

            PanelSuccess.Visible = false;
            PanelError.Visible = false;
            
            PanelRebuildSuccess.Visible = false;
            //PanelRebuildFailure.Visible = false;

		}
Пример #6
0
        /// <summary>
        /// Main constructor
        /// </summary>
        /// <param name="p">the client's process object</param>
        public Client(Process p)
        {
            process = p;
            process.Exited += new EventHandler(process_Exited);
            process.EnableRaisingEvents = true;

            // Wait until we can really access the process
            process.WaitForInputIdle();

            while (process.MainWindowHandle == IntPtr.Zero)
            {
                process.Refresh();
                System.Threading.Thread.Sleep(5);
            }

            // Save a copy of the handle so the process doesn't have to be opened
            // every read/write operation
            processHandle = Util.WinApi.OpenProcess(Util.WinApi.PROCESS_ALL_ACCESS, 0, (uint)process.Id);

            pathFinder = new Tibia.Util.AStarPathFinder(this);
            contextMenu = new ContextMenu(this);

            memory = new MemoryHelper(this);
            window = new WindowHelper(this);
            io = new IOHelper(this);
            login = new LoginHelper(this);
            dll = new DllHelper(this);
            input = new InputHelper(this);
            player = new PlayerHelper(this);

            icon = new Icon(this);
            skin = new Skin(this);

            // Save the start time (it isn't changing)
            startTime = Memory.ReadInt32(Addresses.Client.StartTime);
        }
        private void AddTranslation(string sourceFile)
        {
            LogHelper.Info <ClientDependecyCheckMigration>("Processing {0} Language", () => sourceFile);

            if (!File.Exists(sourceFile))
            {
                return;
            }

            var sourceDoc = new XmlDocument();

            sourceDoc.Load(sourceFile);

            var fileName   = Path.GetFileName(sourceFile);
            var targetFile = IOHelper.MapPath(string.Format("~/Config/Lang/{0}", fileName));

            LogHelper.Info <ClientDependecyCheckMigration>("Looking for {0}", () => targetFile);
            if (File.Exists(targetFile))
            {
                LogHelper.Info <ClientDependecyCheckMigration>(
                    "Source: = {0} Target: {1}", () => sourceFile, () => targetFile);
                try
                {
                    var targetDoc = new XmlDocument();
                    targetDoc.Load(targetFile);

                    var areas = sourceDoc.DocumentElement.SelectNodes("//area");

                    foreach (XmlNode area in areas)
                    {
                        var areaName = area.Attributes["alias"];

                        var targetArea = targetDoc.SelectSingleNode(
                            string.Format("//area [@alias='{0}']", areaName.Value));

                        if (targetArea == null)
                        {
                            // no area - just add what we have to the file.
                            var import = targetDoc.ImportNode(area, true);
                            targetDoc.DocumentElement.AppendChild(import);
                        }
                        else
                        {
                            // we have the ares - we need to write in what we have
                            foreach (XmlNode areaKey in area.ChildNodes)
                            {
                                if (areaKey.NodeType == XmlNodeType.Element)
                                {
                                    var keyToFind = areaKey.Attributes["alias"];

                                    var targetKey = targetArea.SelectSingleNode(
                                        string.Format("./key [@alias='{0}']", keyToFind.Value));

                                    LogHelper.Info <ClientDependecyCheckMigration>("Looking for {0}", () => string.Format("./key [@alias='{0}']", keyToFind.Value));

                                    if (targetKey == null)
                                    {
                                        LogHelper.Info <ClientDependecyCheckMigration>("Adding New");
                                        var keyImport = targetDoc.ImportNode(areaKey, true);
                                        targetArea.AppendChild(keyImport);
                                    }
                                }
                            }
                        }
                    }

                    targetDoc.Save(targetFile);
                }
                catch (Exception ex)
                {
                    LogHelper.Error <ClientDependecyCheckMigration>("Failed to add the language bits to the language files", ex);
                }
            }
        }
Пример #8
0
        IEnumerator DownXML(object parm)
        {
            LoadHelper loadHelper = parm as LoadHelper;
            string     xmlText    = IOHelper.OpenText(loadHelper.Url);

            //if (needDecrupt)
            //{
            //    xmlText = AESManager.AESDecrypt(xmlText);
            //}
            yield return(null);

            Regex           regex           = new Regex("<object .*/>");
            MatchCollection matchCollection = regex.Matches(xmlText);
            string          pattern         = "([A-Za-z0-9_-]*?=\".*?\"){1}";
            int             totalRow        = matchCollection.Count;

            yield return(null);

            for (int i = 0; i < totalRow; i++)
            {
                MatchCollection             mc  = Regex.Matches(matchCollection[i].Value, pattern, RegexOptions.IgnoreCase);
                Dictionary <string, string> dic = new Dictionary <string, string>();
                if (mc.Count > 0)
                {
                    for (int j = 0; j < mc.Count; j++)
                    {
                        string   str      = mc[j].Value.Replace("\"", "");
                        string[] keyValue = str.Split('=');
                        string   key      = keyValue[0];
                        string   value    = keyValue[1];
                        if (dic.ContainsKey(key))
                        {
                            string error = string.Format("{0} has exist key:{1},Row index is:{2}", loadHelper.FileName, key, j);
                            Debug.LogError(error);
                        }
                        else
                        {
                            dic.Add(key, value);
                        }
                    }
                }
                if (loadHelper.XMLResolver != null)
                {
                    try
                    {
                        loadHelper.XMLResolver(dic);
                    }
                    catch (Exception ex)
                    {
                        string info = string.Empty;
                        foreach (KeyValuePair <string, string> keyValue in dic)
                        {
                            info += keyValue.Key + ":" + keyValue.Value + " ";
                        }
                        string error = string.Format("Resolver {0}.xml wrong:row index {1}---{2} exception:{3}", loadHelper.FileName, i, info, ex.ToString());
                        Debug.LogError(error);
                    }
                }
                else
                {
                    Debug.LogError("Resolver" + loadHelper.FileName + ".xml error:XMLResolver is null");
                }
            }
            yield return(null);

            if (loadHelper.CompleteHandler != null)
            {
                loadHelper.CompleteHandler(new LoadedData(xmlText, loadHelper.Url, loadHelper.OriginalUrl));
                GameObject.Destroy(this.gameObject);
            }
        }
Пример #9
0
 /// <summary>
 /// 保存邮件配置
 /// </summary>
 /// <param name="configInfo">邮件配置信息</param>
 /// <returns>是否保存结果</returns>
 public bool SaveEmailConfig(EmailConfigInfo configInfo)
 {
     return(SaveConfigInfo(configInfo, IOHelper.GetMapPath(_emailconfigfilepath)));
 }
Пример #10
0
 /// <summary>
 /// 保存商城基本配置
 /// </summary>
 /// <param name="configInfo">商城基本配置信息</param>
 /// <returns>是否保存结果</returns>
 public bool SaveMallConfig(MallConfigInfo configInfo)
 {
     return(SaveConfigInfo(configInfo, IOHelper.GetMapPath(_mallconfigfilepath)));
 }
Пример #11
0
 /// <summary>
 /// 将配置信息保存到文件中
 /// </summary>
 /// <param name="configInfo">配置信息</param>
 /// <param name="configInfoFile">保存路径</param>
 /// <returns>是否保存成功</returns>
 private bool SaveConfigInfo(IConfigInfo configInfo, string configInfoFile)
 {
     return(IOHelper.SerializeToXml(configInfo, configInfoFile));
 }
Пример #12
0
 /// <summary>
 /// 获得RabbitMQ订单配置
 /// </summary>
 public RabbitMQOrderConfigInfo GetRabbitMQOrderConfig()
 {
     return((RabbitMQOrderConfigInfo)LoadConfigInfo(typeof(RabbitMQOrderConfigInfo), IOHelper.GetMapPath(_rabbitmqorderconfigfilepath)));
 }
Пример #13
0
 /// <summary>
 /// 获得Memcached会话状态配置
 /// </summary>
 public MemcachedSessionConfigInfo GetMemcachedSessionConfig()
 {
     return((MemcachedSessionConfigInfo)LoadConfigInfo(typeof(MemcachedSessionConfigInfo), IOHelper.GetMapPath(_memcachedsessionconfigfilepath)));
 }
 private static void ClearFiles()
 {
     TestHelper.DeleteDirectory(IOHelper.MapPath("FileSysTests"));
     TestHelper.DeleteDirectory(IOHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs"));
 }
Пример #15
0
 /// <summary>
 /// 获得事件配置
 /// </summary>
 /// <returns></returns>
 public EventConfigInfo GetEventConfig()
 {
     return((EventConfigInfo)LoadConfigInfo(typeof(EventConfigInfo), IOHelper.GetMapPath(_eventconfigfilepath)));
 }
Пример #16
0
 /// <summary>
 /// 获得Redis非关系型数据库配置
 /// </summary>
 public RedisNOSQLConfigInfo GetRedisNOSQLConfig()
 {
     return((RedisNOSQLConfigInfo)LoadConfigInfo(typeof(RedisNOSQLConfigInfo), IOHelper.GetMapPath(_redisnosqlconfigfilepath)));
 }
        public void ShadowScopeComplete()
        {
            var logger = Mock.Of <ILogger>();

            var path     = IOHelper.MapPath("FileSysTests");
            var shadowfs = IOHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs");

            Directory.CreateDirectory(path);
            Directory.CreateDirectory(shadowfs);

            var scopedFileSystems = false;

            var phy = new PhysicalFileSystem(path, "ignore");

            var container   = Mock.Of <IFactory>();
            var fileSystems = new FileSystems(container, logger)
            {
                IsScoped = () => scopedFileSystems
            };
            var fs = fileSystems.GetFileSystem <FS>(phy);
            var sw = (ShadowWrapper)fs.InnerFileSystem;

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo")))
                sw.AddFile("sub/f1.txt", ms);
            Assert.IsTrue(phy.FileExists("sub/f1.txt"));

            string id;

            // explicit shadow without scope does not work
            sw.Shadow(id = ShadowWrapper.CreateShadowId());
            Assert.IsTrue(Directory.Exists(shadowfs + "/" + id));
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo")))
                sw.AddFile("sub/f2.txt", ms);
            Assert.IsTrue(phy.FileExists("sub/f2.txt"));
            sw.UnShadow(true);
            Assert.IsTrue(phy.FileExists("sub/f2.txt"));
            Assert.IsFalse(Directory.Exists(shadowfs + "/" + id));

            // shadow with scope but no complete does not complete
            scopedFileSystems = true; // pretend we have a scope
            var scope = new ShadowFileSystems(fileSystems, id = ShadowWrapper.CreateShadowId());

            Assert.IsTrue(Directory.Exists(shadowfs + "/" + id));
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo")))
                sw.AddFile("sub/f3.txt", ms);
            Assert.IsFalse(phy.FileExists("sub/f3.txt"));
            var dirs = Directory.GetDirectories(shadowfs);

            Assert.AreEqual(1, dirs.Length);
            Assert.AreEqual((shadowfs + "/" + id).Replace('\\', '/'), dirs[0].Replace('\\', '/'));
            dirs = Directory.GetDirectories(dirs[0]);
            var typedDir = dirs.FirstOrDefault(x => x.Replace('\\', '/').EndsWith("/x"));

            Assert.IsNotNull(typedDir);
            dirs = Directory.GetDirectories(typedDir);
            var suid      = fileSystems.Paths[typeof(FS)];
            var scopedDir = dirs.FirstOrDefault(x => x.Replace('\\', '/').EndsWith("/" + suid)); // this is where files go

            Assert.IsNotNull(scopedDir);
            scope.Dispose();
            scopedFileSystems = false;
            Assert.IsFalse(phy.FileExists("sub/f3.txt"));
            TestHelper.TryAssert(() => Assert.IsFalse(Directory.Exists(shadowfs + "/" + id)));

            // shadow with scope and complete does complete
            scopedFileSystems = true; // pretend we have a scope
            scope             = new ShadowFileSystems(fileSystems, id = ShadowWrapper.CreateShadowId());
            Assert.IsTrue(Directory.Exists(shadowfs + "/" + id));
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo")))
                sw.AddFile("sub/f4.txt", ms);
            Assert.IsFalse(phy.FileExists("sub/f4.txt"));
            Assert.AreEqual(1, Directory.GetDirectories(shadowfs).Length);
            scope.Complete();
            scope.Dispose();
            scopedFileSystems = false;
            TestHelper.TryAssert(() => Assert.AreEqual(0, Directory.GetDirectories(shadowfs).Length));
            Assert.IsTrue(phy.FileExists("sub/f4.txt"));
            Assert.IsFalse(Directory.Exists(shadowfs + "/" + id));

            // test scope for "another thread"

            scopedFileSystems = true; // pretend we have a scope
            scope             = new ShadowFileSystems(fileSystems, id = ShadowWrapper.CreateShadowId());
            Assert.IsTrue(Directory.Exists(shadowfs + "/" + id));
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo")))
                sw.AddFile("sub/f5.txt", ms);
            Assert.IsFalse(phy.FileExists("sub/f5.txt"));

            // pretend we're another thread w/out scope
            scopedFileSystems = false;
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo")))
                sw.AddFile("sub/f6.txt", ms);
            scopedFileSystems = true;                    // pretend we have a scope

            Assert.IsTrue(phy.FileExists("sub/f6.txt")); // other thread has written out to fs
            scope.Complete();
            scope.Dispose();
            scopedFileSystems = false;
            Assert.IsTrue(phy.FileExists("sub/f5.txt"));
            TestHelper.TryAssert(() => Assert.IsFalse(Directory.Exists(shadowfs + "/" + id)));
        }
Пример #18
0
 /// <summary>
 /// 获得Memcached购物车配置
 /// </summary>
 public MemcachedCartConfigInfo GetMemcachedCartConfig()
 {
     return((MemcachedCartConfigInfo)LoadConfigInfo(typeof(MemcachedCartConfigInfo), IOHelper.GetMapPath(_memcachedcartconfigfilepath)));
 }
        public void ShadowScopeCompleteWithDirectoryConflict()
        {
            var logger = Mock.Of <ILogger>();

            var path     = IOHelper.MapPath("FileSysTests");
            var shadowfs = IOHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs");

            Directory.CreateDirectory(path);

            var scopedFileSystems = false;

            var phy = new PhysicalFileSystem(path, "ignore");

            var container   = Mock.Of <IFactory>();
            var fileSystems = new FileSystems(container, logger)
            {
                IsScoped = () => scopedFileSystems
            };
            var fs = fileSystems.GetFileSystem <FS>(phy);
            var sw = (ShadowWrapper)fs.InnerFileSystem;

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo")))
                sw.AddFile("sub/f1.txt", ms);
            Assert.IsTrue(phy.FileExists("sub/f1.txt"));

            string id;

            scopedFileSystems = true; // pretend we have a scope
            var scope = new ShadowFileSystems(fileSystems, id = ShadowWrapper.CreateShadowId());

            Assert.IsTrue(Directory.Exists(shadowfs + "/" + id));
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo")))
                sw.AddFile("sub/f2.txt", ms);
            Assert.IsFalse(phy.FileExists("sub/f2.txt"));

            // pretend we're another thread w/out scope
            scopedFileSystems = false;
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("bar")))
                sw.AddFile("sub/f2.txt/f2.txt", ms);
            scopedFileSystems = true;                           // pretend we have a scope

            Assert.IsTrue(phy.FileExists("sub/f2.txt/f2.txt")); // other thread has written out to fs

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo")))
                sw.AddFile("sub/f3.txt", ms);
            Assert.IsFalse(phy.FileExists("sub/f3.txt"));

            scope.Complete();

            try
            {
                // no way this can work since we're trying to write a file
                // but there's now a directory with the same name on the real fs
                scope.Dispose();
                Assert.Fail("Expected AggregateException.");
            }
            catch (AggregateException ae)
            {
                Assert.AreEqual(1, ae.InnerExceptions.Count);
                var e = ae.InnerExceptions[0];
                Assert.IsNotNull(e.InnerException);
                Assert.IsInstanceOf <AggregateException>(e);
                ae = (AggregateException)e;

                Assert.AreEqual(1, ae.InnerExceptions.Count);
                e = ae.InnerExceptions[0];
                Assert.IsNotNull(e.InnerException);
                Assert.IsInstanceOf <Exception>(e.InnerException);
            }

            // still, the rest of the changes has been applied ok
            Assert.IsTrue(phy.FileExists("sub/f3.txt"));
        }
Пример #20
0
        private readonly string _rabbitmqorderconfigfilepath    = "/App_Data/rabbitmqorder.config";    //RabbitMQ订单配置信息文件路径

        #endregion

        #region 帮助方法

        /// <summary>
        /// 从文件中加载配置信息
        /// </summary>
        /// <param name="configInfoType">配置信息类型</param>
        /// <param name="configInfoFile">配置信息文件路径</param>
        /// <returns>配置信息</returns>
        private IConfigInfo LoadConfigInfo(Type configInfoType, string configInfoFile)
        {
            return((IConfigInfo)IOHelper.DeserializeFromXML(configInfoType, configInfoFile));
        }
Пример #21
0
 /// <summary>
 /// 保存短信配置
 /// </summary>
 /// <param name="configInfo">短信配置信息</param>
 /// <returns>是否保存结果</returns>
 public bool SaveSMSConfig(SMSConfigInfo configInfo)
 {
     return(SaveConfigInfo(configInfo, IOHelper.GetMapPath(_smsconfigfilepath)));
 }
Пример #22
0
 /// <summary>
 /// 获得关系数据库配置
 /// </summary>
 public RDBSConfigInfo GetRDBSConfig()
 {
     return((RDBSConfigInfo)LoadConfigInfo(typeof(RDBSConfigInfo), IOHelper.GetMapPath(_rdbsconfigfilepath)));
 }
Пример #23
0
 /// <summary>
 /// 获得短信配置
 /// </summary>
 public SMSConfigInfo GetSMSConfig()
 {
     return((SMSConfigInfo)LoadConfigInfo(typeof(SMSConfigInfo), IOHelper.GetMapPath(_smsconfigfilepath)));
 }
Пример #24
0
 /// <summary>
 /// 获得商城基本配置
 /// </summary>
 public MallConfigInfo GetMallConfig()
 {
     return((MallConfigInfo)LoadConfigInfo(typeof(MallConfigInfo), IOHelper.GetMapPath(_mallconfigfilepath)));
 }
Пример #25
0
 /// <summary>
 /// 保存积分配置
 /// </summary>
 /// <param name="configInfo">积分配置信息</param>
 /// <returns>是否保存结果</returns>
 public bool SaveCreditConfig(CreditConfigInfo configInfo)
 {
     return(SaveConfigInfo(configInfo, IOHelper.GetMapPath(_creditconfigfilepath)));
 }
Пример #26
0
 /// <summary>
 /// 获得邮件配置
 /// </summary>
 public EmailConfigInfo GetEmailConfig()
 {
     return((EmailConfigInfo)LoadConfigInfo(typeof(EmailConfigInfo), IOHelper.GetMapPath(_emailconfigfilepath)));
 }
Пример #27
0
 /// <summary>
 /// 获得积分配置
 /// </summary>
 /// <returns></returns>
 public CreditConfigInfo GetCreditConfig()
 {
     return((CreditConfigInfo)LoadConfigInfo(typeof(CreditConfigInfo), IOHelper.GetMapPath(_creditconfigfilepath)));
 }
        /// <summary>
        /// The RegEx matches any HTML attribute values that start with a tilde (~), those that match are passed to ResolveUrl to replace the tilde with the application path.
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        /// <remarks>
        /// When used with a Virtual-Directory set-up, this would resolve all URLs correctly.
        /// The recommendation is that the "ResolveUrlsFromTextString" option (in umbracoSettings.config) is set to false for non-Virtual-Directory installs.
        /// </remarks>
        public static string ResolveUrlsFromTextString(string text)
        {
            if (UmbracoConfig.For.UmbracoSettings().Content.ResolveUrlsFromTextString == false)
            {
                return(text);
            }

            using (var timer = DisposableTimer.DebugDuration(typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete"))
            {
                // find all relative urls (ie. urls that contain ~)
                var tags = ResolveUrlPattern.Matches(text);
                LogHelper.Debug(typeof(IOHelper), "After regex: " + timer.Stopwatch.ElapsedMilliseconds + " matched: " + tags.Count);
                foreach (Match tag in tags)
                {
                    var url = "";
                    if (tag.Groups[1].Success)
                    {
                        url = tag.Groups[1].Value;
                    }

                    // The richtext editor inserts a slash in front of the url. That's why we need this little fix
                    //                if (url.StartsWith("/"))
                    //                    text = text.Replace(url, ResolveUrl(url.Substring(1)));
                    //                else
                    if (String.IsNullOrEmpty(url) == false)
                    {
                        var resolvedUrl = (url.Substring(0, 1) == "/") ? IOHelper.ResolveUrl(url.Substring(1)) : IOHelper.ResolveUrl(url);
                        text = text.Replace(url, resolvedUrl);
                    }
                }
            }

            return(text);
        }
Пример #29
0
 /// <summary>
 /// 保存事件配置
 /// </summary>
 /// <param name="configInfo">事件配置信息</param>
 /// <returns>是否保存成功</returns>
 public bool SaveEventConfig(EventConfigInfo configInfo)
 {
     return(SaveConfigInfo(configInfo, IOHelper.GetMapPath(_eventconfigfilepath)));
 }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            double n = io.NextDouble();
            double t = io.NextDouble();
            n *= Math.Pow(1.000000011,t);
            io.WriteLine(n,18);

            io.Dispose();
        }
Пример #31
0
 /// <summary>
 /// Gets the mapped path to the server.
 /// </summary>
 /// <param name="path">The path.</param>
 /// <param name="useHttpContext">if set to <c>true</c> [use HTTP context].</param>
 /// <returns>Returns the physical file path that corresponds to the specified virtual path on the web server.</returns>
 public static string MapPath(string path, bool useHttpContext)
 {
     return(IOHelper.MapPath(path, useHttpContext));
 }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            int n = io.NextInt();
            BigInteger ans = 1;
            for (int i = n; i >= n-4; i--) {
                ans *= i;
            }
            io.WriteLine(ans*comb(n,5));

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            long n = long.Parse(io.NextToken());
            io.WriteLine(n / 2520);

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            int n=io.NextInt(),m=io.NextInt();
            int[] d = new int[n + 1];
            int[] lastShow = new int[n + 1];
            List<int>[] G = new List<int>[n + 1];
            for (int i = 1; i <= n; i++) {
                d[i] = io.NextInt();
                G[i] = new List<int>();
            }
            for (int i = 0; i < m; i++) {
                int a = io.NextInt(), b = io.NextInt();
                G[a].Add(b); G[b].Add(a);
            }
            long ans = 0;
            int maxLast = 0;
            for (int i = 1; i <= n; i++) {
                foreach (int e in G[d[i]]) {
                    maxLast = Math.Max(maxLast, lastShow[e]);
                }
                ans += i - maxLast;
                lastShow[d[i]] = i;
            }
            io.WriteLine(ans);
            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            //reference:http://www.contracosta.edu/legacycontent/math/stararea.htm
            double n=io.NextDouble(), r=io.NextDouble();
            double bigAng = (180.0 - 360.0 / n) / 2;
            bigAng = bigAng / 180.0 * Math.PI;
            double S_bottom = 2 * r * Math.Cos(bigAng);
            double height = r * Math.Sin(bigAng);
            double ans = n * S_bottom * height / 2;

            double smallAng = ((180.0 - 360.0 / n) - 180.0 / n) / 2;
            smallAng = smallAng / 180.0 * Math.PI;
            double height_small = Math.Tan(smallAng) * (S_bottom / 2);
            ans -= n * S_bottom * height_small / 2;

            io.WriteLine(ans, 18);

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);
            //放弃用位运算优化了,不是很好写,写出来就要是个和C++ bitset差不多的类了

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            n = io.NextInt();
            m = io.NextInt();
            mp = new string[n];
            for (int i = 0; i < n; i++) mp[i] = io.NextToken();
            rec = new int[n, m];
            sz = new int[n * m + 5];
            qx = new int[n * m];
            qy = new int[n * m];
            int cid = 0;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (rec[i, j] == 0 && mp[i][j] != '*') {
                        ++cid;
                        sz[cid] = bfs(i, j, cid);
                    }
                }
            }

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (mp[i][j] == '.') {
                        io.Write('.');
                    } else {
                        HashSet<int> l=new HashSet<int>();
                        int ans = 1;
                        for (int k = 0; k < 4; k++) {
                            int tx = i + di[k, 0];
                            int ty = j + di[k, 1];
                            if (tx >= 0 && tx < n && ty >= 0 && ty < m) {
                                if (mp[tx][ty] != '*' && l.Contains(rec[tx,ty])==false) {
                                    ans += sz[rec[tx, ty]];
                                    l.Add(rec[tx, ty]);
                                }
                            }
                        }
                        ans %= 10;
                        io.Write(ans);
                    }
                }
                if (i != n - 1) io.WriteLine("");
            }

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            int n = io.NextInt(),m=io.NextInt();
            int[] nextDiff = new int[n];
            int[] d = new int[n];
            for (int i = 0; i < n;i++ ) d[i] = io.NextInt();
            nextDiff[n - 1] = -1;
            for (int i = n - 2; i >= 0; i--)
                nextDiff[i] = d[i] == d[i + 1] ? nextDiff[i + 1] : i + 1;

            for (; m-- > 0; ) {
                int L=io.NextInt(), R=io.NextInt(), X=io.NextInt();
                --L; --R;
                if (d[L] != X) io.WriteLine(L+1);
                else io.WriteLine(nextDiff[L] > R ||nextDiff[L]<0 ? -1 : nextDiff[L]+1);
            }

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            string str = io.NextToken();
            int h = int.Parse(str[0] + "" + str[1]), m = int.Parse(str[3] + "" + str[4]);

            DateTime dt = new DateTime(1900, 1, 1, h, m, 0);
            int span = io.NextInt();
            dt = dt.AddMinutes(span);

            io.WriteLine(string.Format("{0:D2}:{1:D2}", dt.Hour, dt.Minute));

            io.Dispose();
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            Exception ex = new Exception();

            if (!cms.businesslogic.packager.Settings.HasFileAccess(ref ex))
            {
                fb.Style.Add("margin-top", "7px");
                fb.type = global::umbraco.uicontrols.Feedback.feedbacktype.error;
                fb.Text = "<strong>" + ui.Text("errors", "filePermissionsError") + ":</strong><br/>" + ex.Message;
            }

            string category = Request.QueryString["category"];
            string repoGuid = Request.QueryString["repoGuid"];

            cms.businesslogic.packager.repositories.Repository repo = cms.businesslogic.packager.repositories.Repository.getByGuid(repoGuid);
            string url = repo.RepositoryUrl;

            Panel1.Text = "Browse repository: " + repo.Name;

            if (!string.IsNullOrEmpty(category))
            {
                category = "&category=" + category;
            }

            iframeGen.Text = string.Format("<iframe id=\"repoFrame\" frameborder=\"1\" style=\"border: none; display: block\" src=\"{0}?repoGuid={1}{2}&callback={3}:{4}{5}/developer/Packages/proxy.htm?/{6}/developer/Packages/installer.aspx?repoGuid={7}&version=v45&fullVersion={8}.{9}.{10}&useLegacySchema={11}&dotnetVersion={12}&trustLevel={13}\"></iframe>", url, repoGuid, category, Request.ServerVariables["SERVER_NAME"], Request.ServerVariables["SERVER_PORT"], IOHelper.ResolveUrl(SystemDirectories.Umbraco), IOHelper.ResolveUrl(SystemDirectories.Umbraco).Trim('/'), repoGuid, GlobalSettings.VersionMajor, GlobalSettings.VersionMinor, GlobalSettings.VersionPatch, UmbracoSettings.UseLegacyXmlSchema.ToString(), Environment.Version, BusinessLogic.Utils.TypeFinder.GetCurrentTrustLevel());
        }
Пример #41
0
        /// <summary>
        /// Builds the various services
        /// </summary>
        private void BuildServiceCache(
            IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider,
            IUnitOfWorkProvider fileUnitOfWorkProvider,
            BasePublishingStrategy publishingStrategy,
            CacheHelper cache,
            RepositoryFactory repositoryFactory,
            ILogger logger,
            IEventMessagesFactory eventMessagesFactory)
        {
            var provider     = dbUnitOfWorkProvider;
            var fileProvider = fileUnitOfWorkProvider;

            if (_migrationEntryService == null)
            {
                _migrationEntryService = new Lazy <IMigrationEntryService>(() => new MigrationEntryService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_externalLoginService == null)
            {
                _externalLoginService = new Lazy <IExternalLoginService>(() => new ExternalLoginService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_publicAccessService == null)
            {
                _publicAccessService = new Lazy <IPublicAccessService>(() => new PublicAccessService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_taskService == null)
            {
                _taskService = new Lazy <ITaskService>(() => new TaskService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_domainService == null)
            {
                _domainService = new Lazy <IDomainService>(() => new DomainService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_auditService == null)
            {
                _auditService = new Lazy <IAuditService>(() => new AuditService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_localizedTextService == null)
            {
                _localizedTextService = new Lazy <ILocalizedTextService>(() => new LocalizedTextService(
                                                                             new Lazy <LocalizedTextServiceFileSources>(() =>
                {
                    var mainLangFolder   = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Umbraco + "/config/lang/"));
                    var appPlugins       = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.AppPlugins));
                    var configLangFolder = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Config + "/lang/"));

                    var pluginLangFolders = appPlugins.Exists == false
                            ? Enumerable.Empty <LocalizedTextServiceSupplementaryFileSource>()
                            : appPlugins.GetDirectories()
                                            .SelectMany(x => x.GetDirectories("Lang"))
                                            .SelectMany(x => x.GetFiles("*.xml", SearchOption.TopDirectoryOnly))
                                            .Where(x => Path.GetFileNameWithoutExtension(x.FullName).Length == 5)
                                            .Select(x => new LocalizedTextServiceSupplementaryFileSource(x, false));

                    //user defined langs that overwrite the default, these should not be used by plugin creators
                    var userLangFolders = configLangFolder.Exists == false
                            ? Enumerable.Empty <LocalizedTextServiceSupplementaryFileSource>()
                            : configLangFolder
                                          .GetFiles("*.user.xml", SearchOption.TopDirectoryOnly)
                                          .Where(x => Path.GetFileNameWithoutExtension(x.FullName).Length == 10)
                                          .Select(x => new LocalizedTextServiceSupplementaryFileSource(x, true));

                    return(new LocalizedTextServiceFileSources(
                               logger,
                               cache.RuntimeCache,
                               mainLangFolder,
                               pluginLangFolders.Concat(userLangFolders)));
                }),
                                                                             logger));
            }


            if (_notificationService == null)
            {
                _notificationService = new Lazy <INotificationService>(() => new NotificationService(provider, _userService.Value, _contentService.Value, logger));
            }

            if (_serverRegistrationService == null)
            {
                _serverRegistrationService = new Lazy <IServerRegistrationService>(() => new ServerRegistrationService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_userService == null)
            {
                _userService = new Lazy <IUserService>(() => new UserService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_memberService == null)
            {
                _memberService = new Lazy <IMemberService>(() => new MemberService(provider, repositoryFactory, logger, eventMessagesFactory, _memberGroupService.Value, _dataTypeService.Value));
            }

            if (_contentService == null)
            {
                _contentService = new Lazy <IContentService>(() => new ContentService(provider, repositoryFactory, logger, eventMessagesFactory, publishingStrategy, _dataTypeService.Value, _userService.Value));
            }

            if (_mediaService == null)
            {
                _mediaService = new Lazy <IMediaService>(() => new MediaService(provider, repositoryFactory, logger, eventMessagesFactory, _dataTypeService.Value, _userService.Value));
            }

            if (_contentTypeService == null)
            {
                _contentTypeService = new Lazy <IContentTypeService>(() => new ContentTypeService(provider, repositoryFactory, logger, eventMessagesFactory, _contentService.Value, _mediaService.Value));
            }

            if (_dataTypeService == null)
            {
                _dataTypeService = new Lazy <IDataTypeService>(() => new DataTypeService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_fileService == null)
            {
                _fileService = new Lazy <IFileService>(() => new FileService(fileProvider, provider, repositoryFactory));
            }

            if (_localizationService == null)
            {
                _localizationService = new Lazy <ILocalizationService>(() => new LocalizationService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_packagingService == null)
            {
                _packagingService = new Lazy <IPackagingService>(() => new PackagingService(logger, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _macroService.Value, _dataTypeService.Value, _fileService.Value, _localizationService.Value, _userService.Value, repositoryFactory, provider));
            }

            if (_entityService == null)
            {
                _entityService = new Lazy <IEntityService>(() => new EntityService(
                                                               provider, repositoryFactory, logger, eventMessagesFactory,
                                                               _contentService.Value, _contentTypeService.Value, _mediaService.Value, _dataTypeService.Value, _memberService.Value, _memberTypeService.Value,
                                                               cache.RuntimeCache));
            }

            if (_relationService == null)
            {
                _relationService = new Lazy <IRelationService>(() => new RelationService(provider, repositoryFactory, logger, eventMessagesFactory, _entityService.Value));
            }

            if (_treeService == null)
            {
                _treeService = new Lazy <IApplicationTreeService>(() => new ApplicationTreeService(logger, cache));
            }

            if (_sectionService == null)
            {
                _sectionService = new Lazy <ISectionService>(() => new SectionService(_userService.Value, _treeService.Value, provider, cache));
            }

            if (_macroService == null)
            {
                _macroService = new Lazy <IMacroService>(() => new MacroService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_memberTypeService == null)
            {
                _memberTypeService = new Lazy <IMemberTypeService>(() => new MemberTypeService(provider, repositoryFactory, logger, eventMessagesFactory, _memberService.Value));
            }

            if (_tagService == null)
            {
                _tagService = new Lazy <ITagService>(() => new TagService(provider, repositoryFactory, logger, eventMessagesFactory));
            }

            if (_memberGroupService == null)
            {
                _memberGroupService = new Lazy <IMemberGroupService>(() => new MemberGroupService(provider, repositoryFactory, logger, eventMessagesFactory));
            }
        }
Пример #42
0
    protected void btnApply_Click(object sender, EventArgs e)
    {
        HttpRuntime.Cache.Remove(CacheKeys.SageFrameJs);
        HttpRuntime.Cache.Remove(CacheKeys.SageFrameCss);
        string optimized_path = Server.MapPath(SageFrameConstants.OptimizedResourcePath);

        IOHelper.DeleteDirectoryFiles(optimized_path, ".js,.css");
        if (File.Exists(Server.MapPath(SageFrameConstants.OptimizedCssMap)))
        {
            XmlHelper.DeleteNodes(Server.MapPath(SageFrameConstants.OptimizedCssMap), "resourcemaps/resourcemap");
        }
        if (File.Exists(Server.MapPath(SageFrameConstants.OptimizedJsMap)))
        {
            XmlHelper.DeleteNodes(Server.MapPath(SageFrameConstants.OptimizedJsMap), "resourcemap/resourcemap");
        }
        PresetInfo preset = new PresetInfo();

        preset = PresetHelper.LoadActivePagePreset(TemplateName, GetPageSEOName(Request.Url.ToString()));
        if (ddlScreen.SelectedItem.ToString() != string.Empty)
        {
            preset.ActiveWidth = ddlScreen.SelectedItem.ToString();
        }
        if (ddlThemes.SelectedItem != null && ddlThemes.SelectedItem.ToString() != string.Empty)
        {
            preset.ActiveTheme = ddlThemes.SelectedItem.ToString();
        }
        if (ddlLayout.SelectedItem != null && ddlLayout.SelectedItem.ToString() != string.Empty)
        {
            preset.ActiveLayout = Path.GetFileNameWithoutExtension(ddlLayout.SelectedItem.ToString());
        }
        List <KeyValue> lstLayouts = preset.lstLayouts;
        string          pageName   = Request.Url.ToString();
        SageFrameConfig sfConfig   = new SageFrameConfig();

        pageName = Path.GetFileNameWithoutExtension(pageName);
        pageName = pageName.ToLower().Equals("default") ? sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) : pageName;
        bool          isNewLayout     = false;
        int           oldPageCount    = 0;
        bool          isNewPage       = false;
        bool          deleteRepeat    = false;
        bool          duplicateLayout = false;
        List <string> pageList        = new List <string>();

        foreach (KeyValue kvp in lstLayouts)
        {
            if (kvp.Key == preset.ActiveLayout)
            {
                duplicateLayout = true;
            }
            string[] pages = kvp.Value.Split(',');
            pageList.Add(string.Join(",", pages));
            if (pages.Count() == 1 && pages.Contains(pageName)) // for single pagename and if page = currentpageName
            {
                kvp.Key = preset.ActiveLayout;
            }
            else if (pages.Count() > 1 && pages.Contains(pageName)) // for multiple pagename and if page = currentpageName
            {
                isNewLayout = true;                                 //its because we have to insert another layout
                List <string> lstnewpage = new List <string>();
                foreach (string page in pages)
                {
                    if (page.ToLower() != pageName.ToLower())
                    {
                        lstnewpage.Add(page);
                    }
                }
                kvp.Value = string.Join(",", lstnewpage.ToArray());
                pageList.Add(kvp.Value);
            }
            else
            {
                oldPageCount++;
            }
            if (kvp.Value == "All" && kvp.Key == preset.ActiveLayout)
            {
                deleteRepeat = true;
            }
        }
        if (lstLayouts.Count == oldPageCount)
        {
            isNewPage = true;
        }
        List <KeyValue> lstNewLayouts = new List <KeyValue>();

        if (isNewPage)
        {
            bool isAppended = false;
            foreach (KeyValue kvp in lstLayouts)
            {
                if (kvp.Key == preset.ActiveLayout)
                {
                    if (kvp.Value.ToLower() != "all")
                    {
                        kvp.Value += "," + pageName;
                    }
                    isAppended = true;
                }
                lstNewLayouts.Add(new KeyValue(kvp.Key, kvp.Value));
            }
            if (!isAppended)
            {
                lstNewLayouts.Add(new KeyValue(preset.ActiveLayout, pageName));
            }
            lstLayouts = lstNewLayouts;
        }
        else if (isNewLayout)
        {
            bool isAppended = false;
            bool isAll      = false;
            foreach (KeyValue kvp in lstLayouts)
            {
                if (kvp.Key == preset.ActiveLayout)
                {
                    if (kvp.Value.ToLower() != "all")
                    {
                        kvp.Value += "," + pageName;
                        isAll      = true;
                    }
                    isAppended = true;
                }
                lstNewLayouts.Add(new KeyValue(kvp.Key, kvp.Value));
            }
            if (!isAppended && !isAll)
            {
                lstNewLayouts.Add(new KeyValue(preset.ActiveLayout, pageName));
            }
            lstLayouts = lstNewLayouts;
        }
        else if (deleteRepeat)
        {
            foreach (KeyValue kvp in lstLayouts)
            {
                if (kvp.Value.ToLower() != pageName.ToLower())
                {
                    lstNewLayouts.Add(new KeyValue(kvp.Key, kvp.Value));
                }
            }
            lstLayouts = lstNewLayouts;
        }
        else if (duplicateLayout)
        {
            string        key   = preset.ActiveLayout;
            List <string> pages = new List <string>();
            foreach (KeyValue kvp in lstLayouts)
            {
                if (kvp.Key.ToLower() != preset.ActiveLayout.ToLower())
                {
                    lstNewLayouts.Add(new KeyValue(kvp.Key, kvp.Value));
                }
                else
                {
                    pages.Add(kvp.Value);
                }
            }
            lstNewLayouts.Add(new KeyValue(key, string.Join(",", pages.ToArray())));
            lstLayouts = lstNewLayouts;
        }
        preset.lstLayouts = lstLayouts;
        string presetPath = Decide.IsTemplateDefault(TemplateName.Trim()) ? Utils.GetPresetPath_DefaultTemplate(TemplateName) : Utils.GetPresetPath(TemplateName);
        string pagepreset = presetPath + "/" + TemplateConstants.PagePresetFile;

        presetPath += "/" + "pagepreset.xml";
        AppErazer.ClearSysHash(ApplicationKeys.ActivePagePreset + "_" + GetPortalID);
        PresetHelper.WritePreset(presetPath, preset);
        SageFrame.Common.CacheHelper.Clear("PresetList");
        Response.Redirect(Request.Url.OriginalString);
    }
Пример #43
0
        public void UpdateDepiction()
        {
            if (DepictionMesh != null)
            {
                DepictionMesh.Dispose();
                DepictionMesh = null;
            }
            foreach (var point in Points)
            {
                point.DropDepictionMesh();
            }

            //if (Points.Count == 0)
            //return;

            if (Depiction == PointDepiction.Mesh && File.Exists(DepictionMeshPath))
            {
                FileInfo Info = new FileInfo(DepictionMeshPath);
                if (Info.Extension.ToLower().Contains("mrc"))
                {
                    HeaderMRC VolumeHeader = (HeaderMRC)MapHeader.ReadFromFile(DepictionMeshPath);
                    float[]   VolumeData   = IOHelper.ReadSmallMapFloat(DepictionMeshPath, new int2(1, 1), 0, typeof(float));

                    Mesh NewMesh = Mesh.FromVolume(VolumeData, VolumeHeader.Dimensions, VolumeHeader.Pixelsize.X, (float)DepictionMeshLevel);
                    NewMesh.UsedComponents = MeshVertexComponents.Position | MeshVertexComponents.Normal;
                    NewMesh.GLContext      = MainWindow.Options.Viewport.GetControl();
                    NewMesh.UpdateBuffers();

                    _DepictionMesh = NewMesh;
                }
                else if (Info.Extension.ToLower().Contains("obj"))
                {
                    Mesh NewMesh = Mesh.FromOBJ(DepictionMeshPath, true);
                    NewMesh.UsedComponents = MeshVertexComponents.Position | MeshVertexComponents.Normal;
                    NewMesh.GLContext      = MainWindow.Options.Viewport.GetControl();
                    NewMesh.UpdateBuffers();

                    _DepictionMesh = NewMesh;
                }
            }
            else if (Depiction == PointDepiction.LocalSurface && MainWindow.Options.Membrane.TomogramTexture != null)
            {
                int3 DimsExtract = new int3((int)Size + 2, (int)Size + 2, (int)Size + 2);

                Parallel.ForEach(Points, point =>
                {
                    Vector3 TomoPos = (point.Position - MainWindow.Options.Membrane.TomogramTexture.Offset) / MainWindow.Options.PixelScale.X;
                    int3 TomoPosInt = new int3((int)Math.Round(TomoPos.X), (int)Math.Round(TomoPos.Y), (int)Math.Round(TomoPos.Z));

                    float[] LocalVol = Helper.Extract(MainWindow.Options.Membrane.TomogramTexture.OriginalData,
                                                      MainWindow.Options.Membrane.TomogramTexture.Size,
                                                      TomoPosInt,
                                                      DimsExtract);

                    if (DepictionLocalSurfaceInvert)
                    {
                        for (int i = 0; i < LocalVol.Length; i++)
                        {
                            LocalVol[i] = -LocalVol[i];
                        }
                    }

                    for (int z = 0; z < DimsExtract.Z; z++)
                    {
                        for (int y = 0; y < DimsExtract.Y; y++)
                        {
                            for (int x = 0; x < DimsExtract.X; x++)
                            {
                                if (z == 0 || y == 0 || x == 0 || z == DimsExtract.Z - 1 || y == DimsExtract.Y - 1 || x == DimsExtract.X - 1)
                                {
                                    LocalVol[(z * DimsExtract.Y + y) * DimsExtract.X + x] = -99999;
                                }
                            }
                        }
                    }

                    bool[] Mask     = new bool[LocalVol.Length];
                    float Threshold = (float)DepictionLocalSurfaceLevel;
                    if (DepictionLocalSurfaceOnlyCenter)
                    {
                        int MostCentralID     = -1;
                        float MostCentralDist = DimsExtract.X * DimsExtract.X;

                        // Find most central valid pixel in the local window to start mask expansion from there.
                        for (int z = 1; z < DimsExtract.Z - 1; z++)
                        {
                            int zz = z - DimsExtract.Z / 2;
                            zz    *= zz;
                            for (int y = 1; y < DimsExtract.Y - 1; y++)
                            {
                                int yy = y - DimsExtract.Y / 2;
                                yy    *= yy;
                                for (int x = 1; x < DimsExtract.X - 1; x++)
                                {
                                    if (LocalVol[(z * DimsExtract.Y + y) * DimsExtract.X + x] >= Threshold)
                                    {
                                        int xx  = x - DimsExtract.X / 2;
                                        xx     *= xx;
                                        float r = xx + yy + zz;
                                        if (r < MostCentralDist)
                                        {
                                            MostCentralDist = r;
                                            MostCentralID   = (z * DimsExtract.Y + y) * DimsExtract.X + x;
                                        }
                                    }
                                }
                            }
                        }
                        if (MostCentralID < 0) // Volume doesn't contain voxels above threshold
                        {
                            return;
                        }

                        Mask[MostCentralID] = true;

                        for (int mi = 0; mi < Size / 2; mi++)
                        {
                            bool[] NextMask = new bool[Mask.Length];

                            for (int z = 1; z < DimsExtract.Z - 1; z++)
                            {
                                for (int y = 1; y < DimsExtract.Y - 1; y++)
                                {
                                    for (int x = 1; x < DimsExtract.X - 1; x++)
                                    {
                                        int ID = (z * DimsExtract.Y + y) * DimsExtract.X + x;
                                        if (LocalVol[ID] >= Threshold)
                                        {
                                            if (Mask[ID] ||
                                                Mask[ID + 1] ||
                                                Mask[ID - 1] ||
                                                Mask[ID + DimsExtract.X] ||
                                                Mask[ID - DimsExtract.X] ||
                                                Mask[ID + DimsExtract.Y * DimsExtract.X] ||
                                                Mask[ID - DimsExtract.Y * DimsExtract.X])
                                            {
                                                NextMask[ID] = true;
                                            }
                                        }
                                    }
                                }
                            }

                            Mask = NextMask;
                        }
                    }
                    else
                    {
                        for (int i = 0; i < Mask.Length; i++)
                        {
                            Mask[i] = true;
                        }
                    }

                    // Apply spherical mask
                    int Size2 = (int)(Size * Size / 4);
                    for (int z = 1; z < DimsExtract.Z - 1; z++)
                    {
                        int zz = z - DimsExtract.Z / 2;
                        zz    *= zz;
                        for (int y = 1; y < DimsExtract.Y - 1; y++)
                        {
                            int yy = y - DimsExtract.Y / 2;
                            yy    *= yy;
                            for (int x = 1; x < DimsExtract.X - 1; x++)
                            {
                                int xx = x - DimsExtract.X / 2;
                                xx    *= xx;
                                int r2 = xx + yy + zz;

                                Mask[(z * DimsExtract.Y + y) * DimsExtract.X + x] &= r2 < Size2;
                            }
                        }
                    }

                    for (int i = 0; i < Mask.Length; i++)
                    {
                        if (!Mask[i])
                        {
                            LocalVol[i] = Math.Min(LocalVol[i], Threshold - 1e-5f);
                        }
                    }

                    //IOHelper.WriteMapFloat("d_extract.mrc", HeaderMRC.ReadFromFile("test_extract.mrc"), LocalVol);
                    //IOHelper.WriteMapFloat("d_original.mrc", HeaderMRC.ReadFromFile("Tomo1L1_bin4.mrc"), MainWindow.Options.Membrane.TomogramTexture.OriginalData);

                    point.DepictionMesh = Mesh.FromVolume(LocalVol,
                                                          DimsExtract,
                                                          MainWindow.Options.PixelScale.X,
                                                          (float)DepictionLocalSurfaceLevel);
                    point.DepictionMesh.UsedComponents = MeshVertexComponents.Position | MeshVertexComponents.Normal;
                });

                foreach (var point in Points)
                {
                    if (point.DepictionMesh == null)
                    {
                        continue;
                    }
                    point.DepictionMesh.GLContext = MainWindow.Options.Viewport.GetControl();
                    point.DepictionMesh.UpdateBuffers();
                }
            }

            MainWindow.Options.Viewport.Redraw();
        }
Пример #44
0
 /// <remarks/>
 public CacheRefresher()
 {
     // only set the url if the httpcontext is present, else it's set by the cache dispatcher methods (when using distributed calls)
     if (System.Web.HttpContext.Current != null)
     {
         this.Url = "http://" + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + IOHelper.ResolveUrl(SystemDirectories.Webservices) + "/cacheRefresher.asmx";
     }
 }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            long n = long.Parse(io.NextToken());
            /*
            int mid, left = 1, right = 1000000000;
            while(left <= right){
                mid = (left + right) >> 1;
                if(F(mid) >= n) right = mid - 1;
                else left = mid + 1;
            }
            io.WriteLine(n-F(left-1));
            */
            io.WriteLine(
                (from i in E.Range(Math.Max((int)Math.Sqrt((double)n*2)-10,0),20)
                    let x=n-(long)i*(long)(i+1)/2
                    where x>0
                    select x).Last()
                );
            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            long n, m;
            n = Int64.Parse(io.NextToken());
            m = Int64.Parse(io.NextToken());
            //bf(n, m);
            long ans = 0;
            if (m > n) {
                ans = llmul(n, m - n);
                m = n;
            }
            int sn = (int)Math.Sqrt(n);
            long lastp = m;
            for (int i = 1; i < sn; i++) {
                long p2 = n / (i + 1) + 1;
                if (p2 > lastp) continue;
                long num = lastp-p2 + 1;
                long ap = llmul(n%lastp,num)+llmul(llmul(llmul(num,num-1),i),500000004);
                //io.WriteLine("=" + i+" "+p2+" "+lastp + " " + ap);
                ans = (ans + ap) % mod;
                lastp = p2 - 1;

            }
            for (int i = 1; i <= lastp; i++) {
                ans += n % i;
                //io.WriteLine("-" + i + " " + ans);
                if (ans > (long)100 * mod) {
                    ans %= mod;
                }
            }
            io.WriteLine(ans%mod);

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            int n, k;
            n = io.NextInt(); k = io.NextInt();
            int[] d = new int[n+1];
            for (int i = 1; i <= n; i++) d[i] = io.NextInt();
            Dictionary<int, int> dict = new Dictionary<int, int>();
            int besthead=1, besttail=1;
            int h=1;
            dict[d[1]]=1;
            for (int i = 2; i <= n;i++ ) {
                if (!dict.ContainsKey(d[i])) {
                    dict[d[i]] = 1;
                    while (dict.Count > k) {
                        --dict[d[h]];
                        if (dict[d[h]] == 0) {
                            dict.Remove(d[h]);
                        }
                        h++;
                    }
                } else ++dict[d[i]];

                if (i - h > besttail - besthead) {
                    besttail = i;
                    besthead = h;
                }
            }
            io.WriteLine(besthead + " " + besttail);

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            string s = io.NextToken();
            BigInteger ans = 0;

            for (int i = 0; i < s.Length; i++) {
                int digit = s[i] - '0';
                if (digit==0||digit == 4 || digit == 8) {
                    ++ans;
                }
                if (i > 0) {
                    int twonum = int.Parse("" + s[i - 1] + s[i]);
                    if (twonum % 4 == 0) ans += i;
                }
            }
            io.WriteLine(ans);

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            String t = io.NextToken();
            string ans = ""+t[0]+ t[2] + t[4] + t[3] + t[1];
            int n = int.Parse(ans);
            BigInteger a = 1;
            for (int i = 1; i <= 5; i++) {
                a *= n;
            }
            a %= 100000;
            io.WriteLine(a.ToString("D5"));

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            n = io.NextInt(); m = io.NextInt();
            valN = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                valN[i] = io.NextInt();
            }
            G=new List<int>[n+1];
            for (int i = 1; i <= n; i++) G[i] = new List<int>();
            int task,sa, sb;
            for(int i=0;i<n-1;i++){
                sa=io.NextInt();
                sb=io.NextInt();
                G[sa].Add(sb);
                G[sb].Add(sa);
            }
            dfs_clock = 0;
            vis = new int[n * 2 + 5];
            firstId = new int[n + 1];
            lastId = new int[n + 1];
            dfs(1, 0);

            mask = new long[n * 8 + 5];
            lazy = new bool[n * 8 + 5];
            build(1, 1, dfs_clock);
            for (; m-- > 0; ) {
                task = io.NextInt();
                sa = io.NextInt();
                if (task == 1) {
                    sb = io.NextInt();
                    update(firstId[sa], lastId[sa], 1, 1, dfs_clock, sb);
                } else {
                    long mm = query(firstId[sa], lastId[sa], 1, 1, dfs_clock);
                    io.WriteLine(countMask(mm));
                }
            }

            io.Dispose();
        }
 public Program(string inputFile, string outputFile)
 {
     io = new IOHelper(inputFile, outputFile, Encoding.Default);
     int x1, y1, x2, y2;
     x1 = io.NextInt();
     y1 = io.NextInt();
     x2 = io.NextInt();
     y2 = io.NextInt();
     io.WriteLine(Math.Max(Math.Abs(x1 - x2), Math.Abs(y1 - y2)));
     io.Dispose();
 }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            int n = io.NextInt();
            io.WriteLine(((long)1 << (n+1)) - 2);

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            int n = io.NextInt();
            int[] arr = new int[n];
            for (int i = 0; i < n; ++i) arr[i] = io.NextInt();
            Array.Sort(arr);
            List<int> q = new List<int>();
            int p1 = 0, p2 = n - 1;
            while (p1 <= p2) {
                q.Add(arr[p1++]);
                if (p1 <= p2) q.Add(arr[p2--]);
            }
            foreach (int i in q) {
                io.Write(i + " ");
            }
            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            double a, b, c;
            a = io.NextDouble();
            b = io.NextDouble();
            c = io.NextDouble();
            double delta = b * b - 4 * a * c;
            delta = Math.Sqrt(delta);
            double x1 = (-b + delta) / (2 * a);
            double x2 = (-b - delta) / (2 * a);
            if (x1 < x2) {
                double tmp = x1; x1 = x2; x2 = tmp;
            }
            io.WriteLine(x1, 18);
            io.WriteLine(x2, 18);

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            int n = io.NextInt();
            int[] p = new int[n];
            for (int i = 0; i < n;i++ ) {
                p[i] = io.NextInt();
            }
            string s = io.NextToken();
            long ans = 0,init=0;
            for (int i = 0; i < n; i++) {
                if (s[i] == 'B') ans += p[i];
            }
            init = ans;
            long[] presum = new long[n];
            long[] sufsum = new long[n];
            for (int i = 0; i < n; i++) {
                presum[i] = (i != 0 ? presum[i - 1] : 0) + (s[i] == 'A' ? p[i] : -p[i]);
                ans = Math.Max(ans, init + presum[i]);
            }
            for (int i = n-1; i >=0; i--) {
                sufsum[i] = (i != n-1 ? sufsum[i + 1] : 0) + (s[i] == 'A' ? p[i] : -p[i]);
                ans = Math.Max(ans, init + sufsum[i]);
            }
            io.WriteLine(ans);

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);
            //直接思路:枚举1~m的lcm,对每个lcm枚举约数,然后约数的bin里都要,复杂度msqrt(m)
            //那么现在反转,枚举约数,再枚举这个数是哪些可能的lcm值的约数
            //根据调和级数公式,n/1+n/2+n/3+...n/n=nlogn

            int n=io.NextInt(),m = io.NextInt();
            List<int>[] bin = new List<int>[m + 1];
            for (int i = 0; i <= m; i++) bin[i] = new List<int>();
            for (int i = 1; i <= n; i++) {
                int x = io.NextInt();
                if (x <= m) bin[x].Add(i);
            }
            int[] cnt = new int[m + 1];
            for (int i = 1; i <= m; i++) {
                if (bin[i].Count == 0) continue;
                for (int j = i; j <= m; j += i) {
                    cnt[j] += bin[i].Count;
                }
            }
            int maxElement=cnt.Max();
            for (int i = 1; i <= m; i++) {
                if (cnt[i] == maxElement) {
                    io.WriteLine(i+" "+maxElement);
                    List<int> ans=new List<int>();
                    for (int j = 1; j <= Math.Sqrt(i); j++) {
                        if (i % j == 0) {
                            ans.AddRange(bin[j]);
                            if (j * j != i) ans.AddRange(bin[i / j]);
                        }
                    }
                    ans.Sort();
                    foreach (int k in ans) {
                        io.Write(k + " ");
                    }
                    break;
                }
            }

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            List<char> s = io.NextToken().ToList();
            for (int m = io.NextInt(); m-- > 0; ) {
                int l = io.NextInt();
                int r = io.NextInt();
                int k = io.NextInt();
                int len = r - l + 1;
                k %= len;
                --r; --l;

                s.Reverse(l, len);
                s.Reverse(l, k);
                s.Reverse(l+k, len-k);
            }
            io.WriteLine(new String(s.ToArray()));

            io.Dispose();
        }
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            int n,m;
            n=io.NextInt();
            m=io.NextInt();
            int[] data = new int[n];
            for (int i = 0; i < n; i++) {
                data[i] = io.NextInt();
                for (int j = 1; j < m; j++) {
                    int tmp = io.NextInt();
                    data[i] = Math.Min(tmp, data[i]);
                }
            }
            Console.WriteLine(data.Max());
            io.Dispose();
        }
Пример #59
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            SaveButton            = UmbracoPanel1.Menu.NewButton();
            SaveButton.Text       = ui.Text("save");
            SaveButton.ButtonType = MenuButtonType.Primary;
            SaveButton.ID         = "save";
            SaveButton.CssClass   = "client-side";

            var code = UmbracoPanel1.NewTabPage("xslt");

            code.Controls.Add(pane1);

            var props = UmbracoPanel1.NewTabPage("properties");

            props.Controls.Add(pane2);

            var tmp = editorSource.Menu.NewIcon();

            tmp.ImageURL       = IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/images/editor/insField.GIF";
            tmp.OnClickCommand = ClientTools.Scripts.OpenModalWindow(IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/developer/xslt/xsltinsertvalueof.aspx?objectId=" + editorSource.ClientID, "Insert value", 750, 250);
            //"umbracoInsertField(document.getElementById('editorSource'), 'xsltInsertValueOf', '','felt', 750, 230, '');";
            tmp.AltText = "Insert xslt:value-of";

            editorSource.Menu.InsertSplitter();

            tmp                = editorSource.Menu.NewIcon();
            tmp.ImageURL       = SystemDirectories.Umbraco + "/images/editor/insMemberItem.GIF";
            tmp.OnClickCommand = "UmbEditor.Insert('<xsl:variable name=\"\" select=\"', '\"/>\\n', '" + editorSource.ClientID + "'); return false;";
            tmp.AltText        = "Insert xsl:variable";

            editorSource.Menu.InsertSplitter();

            tmp                = editorSource.Menu.NewIcon();
            tmp.ImageURL       = SystemDirectories.Umbraco + "/images/editor/insChildTemplateNew.GIF";
            tmp.OnClickCommand = "UmbEditor.Insert('<xsl:if test=\"CONDITION\">\\n', '\\n</xsl:if>\\n', '" + editorSource.ClientID + "'); return false;";
            tmp.AltText        = "Insert xsl:if";

            tmp                = editorSource.Menu.NewIcon();
            tmp.ImageURL       = SystemDirectories.Umbraco + "/images/editor/insChildTemplateNew.GIF";
            tmp.OnClickCommand = "UmbEditor.Insert('<xsl:for-each select=\"QUERY\">\\n', '\\n</xsl:for-each>\\n', '" + editorSource.ClientID + "'); return false;";
            tmp.AltText        = "Insert xsl:for-each";

            editorSource.Menu.InsertSplitter();

            tmp                = editorSource.Menu.NewIcon();
            tmp.ImageURL       = SystemDirectories.Umbraco + "/images/editor/insFieldByLevel.GIF";
            tmp.OnClickCommand = "UmbEditor.Insert('<xsl:choose>\\n<xsl:when test=\"CONDITION\">\\n', '\\n</xsl:when>\\n<xsl:otherwise>\\n</xsl:otherwise>\\n</xsl:choose>\\n', '" + editorSource.ClientID + "'); return false;";
            tmp.AltText        = "Insert xsl:choose";

            editorSource.Menu.InsertSplitter();

            tmp                = editorSource.Menu.NewIcon();
            tmp.ImageURL       = SystemDirectories.Umbraco + "/images/editor/xslVisualize.GIF";
            tmp.OnClickCommand = "xsltVisualize();";
            tmp.AltText        = "Visualize XSLT";


            // Add source and filename
            var file = IOHelper.MapPath(SystemDirectories.Xslt + "/" + Request.QueryString["file"].CleanForXss().Replace(" ", ""));

            // validate file
            IOHelper.ValidateEditPath(file, SystemDirectories.Xslt);
            // validate extension
            IOHelper.ValidateFileExtension(file, new List <string>()
            {
                "xslt", "xsl"
            });


            xsltFileName.Text = file.Replace(IOHelper.MapPath(SystemDirectories.Xslt), "").Substring(1).Replace(@"\", "/");

            StreamReader SR;
            string       S;

            SR = File.OpenText(file);

            S = SR.ReadToEnd();
            SR.Close();

            editorSource.Text = S;
        }
Пример #60
-1
        protected void btnTestConfiguration_Click(object sender, EventArgs e)
        {
            //get all the fields, save in conf file
            //use that to then connect to the database
            
            IOHelper iohelper = new IOHelper(Server);
            
            string result = iohelper.SaveDBConfigString(txtServer.Text, txtPort.Text, txtDatabase.Text, txtUserName.Text, txtPassword.Text);

            if (result != null)
                lblOutput.Text = result;
            else
            {
                DatabaseUtilities du = new DatabaseUtilities(Server);
                string msg = du.TestDatabaseConnection();
                if (msg == null)
                {
                    labelSuccess.Text = "Connection to Database Successful!";
                    PanelSuccess.Visible = true;
                    Session["DBConfigured"] = true;
                }
                else
                {
                    labelError.Text = msg;
                    PanelError.Visible = true;
                    Session["DBConfigured"] = null;
                }
            }
        }