Ejemplo n.º 1
0
    public static void CreateAvatar()
    {
        GameObject go = Selection.activeGameObject;

        if (go != null && go.GetComponent("Animator") != null)
        {
            HumanDescription hd = new HumanDescription();

            Dictionary<string,string> boneName = new System.Collections.Generic.Dictionary<string, string>();
            boneName["Chest"] = "spine";
            boneName["Head"] = "head";
            boneName["Hips"] = "hip";
            boneName["LeftFoot"] = "footL";
            boneName["LeftHand"] = "handL";
            boneName["LeftLowerArm"] = "elbowL";
            boneName["LeftLowerLeg"] = "kneeL";
            boneName["LeftShoulder"] = "clavL";
            boneName["LeftUpperArm"] = "armL";
            boneName["LeftUpperLeg"] = "legL";
            boneName["RightFoot"] = "footR";
            boneName["RightHand"] = "handR";
            boneName["RightLowerArm"] = "elbowR";
            boneName["RightLowerLeg"] = "kneeR";
            boneName["RightShoulder"] = "clavR";
            boneName["RightUpperArm"] = "armR";
            boneName["RightUpperLeg"] = "legR";
            boneName["Spine"] = "spine2";
            string[] humanName = HumanTrait.BoneName;
            HumanBone[] humanBones = new HumanBone[boneName.Count];
            int j = 0;
            int i = 0;
            while (i < humanName.Length) {
                if (boneName.ContainsKey(humanName[i])) {
                    HumanBone humanBone = new HumanBone();
                    humanBone.humanName = humanName[i];
                    humanBone.boneName = boneName[humanName[i]];
                    humanBone.limit.useDefaultValues = true;
                    humanBones[j++] = humanBone;
                }
                i++;
            }

            hd.human = humanBones;

            //hd.skeleton = new SkeletonBone[18];
            //hd.skeleton[0].name = ("Hips") ;
            Avatar avatar = AvatarBuilder.BuildHumanAvatar(go, hd);

            avatar.name = (go.name + "_Avatar");
            Debug.Log(avatar.isHuman ? "is human" : "is generic");

            Animator animator = go.GetComponent("Animator") as Animator;
            animator.avatar = avatar;

            string path = AssetDatabase.GenerateUniqueAssetPath(Puppet2D_Editor._puppet2DPath+"/Animation/"+avatar.name+".asset");
            AssetDatabase.CreateAsset(avatar, path);

        }
    }
Ejemplo n.º 2
0
        // GET: Zakup
        public ActionResult Index()
        {
            DbModule module = DbModule.GetInstance();
            string[] koszyk = Request.Cookies["Cart"].Value.ToString().Split(',');
            var dict = new System.Collections.Generic.Dictionary<int, int>();

            if(!String.IsNullOrEmpty(Request.Cookies["Cart"].Value))
            foreach(string Ids in koszyk)
            {
                int Id = int.Parse(Ids);
                if (!dict.ContainsKey(Id))
                {
                    dict.Add(Id, 1);
                }
                else
                {
                    dict[Id] += 1;
                }
            }

            var dict2 = new System.Collections.Generic.Dictionary<Album, int>();
            decimal wartosc = 0;
            string waluta = "";
            foreach(var obiekt in dict)
            {
                var album = module.Albumy.Where(x => x.Id == obiekt.Key).First();
                dict2.Add(album, obiekt.Value);
                wartosc += album.BruttoValue * obiekt.Value;

                if(waluta == "")
                {
                    waluta = album.BruttoSymbol;
                }
                else if(waluta != album.BruttoSymbol)
                {
                    waluta = "(Wiele walut)";
                    wartosc = 0;
                }
            }
            ViewBag.wartosc = wartosc;
            ViewBag.waluta = waluta;

            return View(dict2);
        }
Ejemplo n.º 3
0
        private void ServerVariablesParser_Parsing(object sender, System.Collections.Generic.Dictionary <string, object> e)
        {
            if (HttpContext.Current == null)
            {
                throw new InvalidOperationException("HttpContext is null");
            }

            if (e.ContainsKey(ArticulateContentTypeAlias))
            {
                return;
            }

            var urlHelper = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));

            e[ArticulateContentTypeAlias] = new Dictionary <string, object>
            {
                { "articulateImportBaseUrl", urlHelper.GetUmbracoApiServiceBaseUrl <ArticulateBlogImportController>(controller => controller.PostImportBlogMl(null)) },
                { "articulateDataInstallerBaseUrl", urlHelper.GetUmbracoApiServiceBaseUrl <ArticulateBlogDataInstallController>(controller => controller.PostInstall()) },
                { "articulatePropertyEditorsBaseUrl", urlHelper.GetUmbracoApiServiceBaseUrl <ArticulatePropertyEditorsController>(controller => controller.GetThemes()) }
            };

            object found;

            if (e.TryGetValue("umbracoUrls", out found))
            {
                var umbUrls = (Dictionary <string, object>)found;
                umbUrls["articulateThemeEditorApiBaseUrl"] = urlHelper.GetUmbracoApiServiceBaseUrl <ThemeEditorController>(controller => controller.GetByPath(null));
            }
            else
            {
                e["umbracoUrls"] = new Dictionary <string, object>
                {
                    { "articulateThemeEditorApiBaseUrl", urlHelper.GetUmbracoApiServiceBaseUrl <ThemeEditorController>(controller => controller.GetByPath(null)) }
                };
            }
        }
Ejemplo n.º 4
0
        private void ConnectCallback(IAsyncResult ar)
        {
            LiveClient  lc   = ar.AsyncState as LiveClient;
            ConnectInfo info = lc.Tag as ConnectInfo;

            try
            {
                info.Socket.EndConnect(ar);
            }
            catch (System.Net.Sockets.SocketException)
            {
                string msg = string.Format("无法连接 {0}, 请检查设备", info.Source.Config.Name);

                Action showMsg = () => MessageBox.Show(this, msg, "连接错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                this.BeginInvoke(showMsg);

                return;
            }

            if (CellCameraMap.ContainsKey(info.Target))
            {
                CellCameraMap[info.Target].ImageReceived -= this.lc_ImageReceived;

                CellCameraMap[info.Target].Stop();

                CellCameraMap.Remove(info.Target);
            }


            lc.ImageReceived  += new EventHandler <ImageCapturedEventArgs>(lc_ImageReceived);
            lc.ConnectAborted += new EventHandler(lc_ConnectAborted);
            lc.Start();

            CellCameraMap.Add(info.Target, lc);
        }
Ejemplo n.º 5
0
        private void button6_Click(object sender, EventArgs e)
        {
            Dictionary <string, int> population = new System.Collections.Generic.Dictionary <string, int>();

            population.Clear();
            population.Add("Russia", 1707);
            population.Add("Candana", 233);
            population.Add("China", 960);
            population.Add("America", 122);
            population.Add("Brazil", 854);

            population.Remove("Candana");

            int cnt = population.Count;

            bool hasKey = population.ContainsKey("China");

            bool hasValue = population.ContainsValue(850);

            foreach (KeyValuePair <string, int> kvp in population)
            {
                MessageBox.Show(kvp.Key + kvp.Value);
            }

            //遍历所有键名
            foreach (string key in population.Keys)
            {
                MessageBox.Show(key);
            }

            //遍历所有值
            foreach (int val in population.Values)
            {
                MessageBox.Show(val.ToString());
            }
        }
Ejemplo n.º 6
0
        static private void theOtherWork2(string file)
        {
            using (StreamReader sr = new StreamReader(file))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    line = line.Trim();
                    if (string.IsNullOrEmpty(line) || line[0] == '#')
                    {
                        continue;
                    }

                    string[] sepped = line.Split(new char[] { ' ', '\t' }, 2);
                    if (sepped.Length < 2)
                    {
                        continue;
                    }

                    string mime = sepped[0];
                    if (dic_.ContainsKey(mime))
                    {
                        continue;
                    }

                    string[] exts = sepped[1].Split(new char[] { ' ', '\t', ',' });
                    if (exts.Length < 1)
                    {
                        continue;
                    }

                    string ext = string.Join(" ", exts);
                    dic_.Add(mime, ext);
                }
            }
        }
Ejemplo n.º 7
0
        private System.Collections.Generic.List <SyllTransition> GetSyllTransations(System.Collections.Generic.Dictionary <enrSYLL_STATE, enrSYLL_DSCR> ur_dscr_lookup)
        {
            Mx.bitbase <enrSYLL_STATE> .populate_bitbase();

            var ret_list = new System.Collections.Generic.List <SyllTransition>();

            ret_list.Add(new SyllTransition(enrSYLL_STATE.word_separator, enrSYLL_STATE.handshape_thumb, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.word_separator, enrSYLL_STATE.handshape_finger, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.word_separator, enrSYLL_STATE.basehand_flag, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.word_separator, enrSYLL_STATE.eyeword_plane, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_thumb, enrSYLL_STATE.handshape_finger, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_inner_thumb, enrSYLL_STATE.handshape_finger, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_finger, enrSYLL_STATE.handshape_finger, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_finger, enrSYLL_STATE.handshape_inner_thumb, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_finger, enrSYLL_STATE.body_height, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_finger, enrSYLL_STATE.body_side, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_finger, enrSYLL_STATE.body_depth, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_finger, enrSYLL_STATE.palm_pinky, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_finger, enrSYLL_STATE.palm_facing, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_finger, enrSYLL_STATE.repeat_flag, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_finger, enrSYLL_STATE.handsyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handshape_finger, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_height, enrSYLL_STATE.body_side, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_height, enrSYLL_STATE.body_offset_plane, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_height, enrSYLL_STATE.body_depth, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_height, enrSYLL_STATE.palm_pinky, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_height, enrSYLL_STATE.palm_facing, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_side, enrSYLL_STATE.body_depth, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_side, enrSYLL_STATE.body_offset_plane, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_side, enrSYLL_STATE.palm_pinky, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_side, enrSYLL_STATE.palm_facing, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_offset_plane, enrSYLL_STATE.body_offset_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_offset_dir, enrSYLL_STATE.body_offset_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_offset_dir, enrSYLL_STATE.body_offset_plane, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_offset_dir, enrSYLL_STATE.body_depth, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_offset_dir, enrSYLL_STATE.palm_pinky, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_offset_dir, enrSYLL_STATE.palm_facing, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_depth, enrSYLL_STATE.palm_pinky, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.body_depth, enrSYLL_STATE.palm_facing, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_pinky, enrSYLL_STATE.palm_facing, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_facing, enrSYLL_STATE.palm_rotate_flag, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_facing, enrSYLL_STATE.hand_offset_spacing, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_facing, enrSYLL_STATE.handsyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_facing, enrSYLL_STATE.repeat_flag, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_facing, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_rotate_flag, enrSYLL_STATE.palm_rotate_plane, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_rotate_plane, enrSYLL_STATE.palm_rotate_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_rotate_dir, enrSYLL_STATE.hand_offset_spacing, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_rotate_dir, enrSYLL_STATE.repeat_flag, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_rotate_dir, enrSYLL_STATE.handsyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.palm_rotate_dir, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.hand_offset_spacing, enrSYLL_STATE.hand_offset_plane, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.hand_offset_plane, enrSYLL_STATE.hand_offset_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.hand_offset_dir, enrSYLL_STATE.hand_offset_style, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.hand_offset_dir, enrSYLL_STATE.handsyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.hand_offset_style, enrSYLL_STATE.handsyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handsyll_separator, enrSYLL_STATE.word_separator, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handsyll_separator, enrSYLL_STATE.move_plane, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handsyll_separator, enrSYLL_STATE.move_depth, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.handsyll_separator, enrSYLL_STATE.move_touch_flag, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_depth, enrSYLL_STATE.repeat_flag, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_depth, enrSYLL_STATE.movesyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_depth, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_plane, enrSYLL_STATE.move_plane, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_plane, enrSYLL_STATE.move_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_dir, enrSYLL_STATE.move_plane, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_dir, enrSYLL_STATE.move_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_dir, enrSYLL_STATE.repeat_flag, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_dir, enrSYLL_STATE.movesyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_dir, enrSYLL_STATE.move_combine_flag, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_dir, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_combine_flag, enrSYLL_STATE.move_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_touch_flag, enrSYLL_STATE.move_touch_plane, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_touch_plane, enrSYLL_STATE.move_touch_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_touch_dir, enrSYLL_STATE.move_touch_style, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_touch_dir, enrSYLL_STATE.repeat_flag, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_touch_dir, enrSYLL_STATE.movesyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_touch_dir, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_touch_style, enrSYLL_STATE.repeat_flag, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_touch_style, enrSYLL_STATE.movesyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.move_touch_style, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.repeat_flag, enrSYLL_STATE.repeat_plane, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.repeat_flag, enrSYLL_STATE.repeat_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.repeat_flag, enrSYLL_STATE.movesyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.repeat_flag, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.repeat_plane, enrSYLL_STATE.repeat_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.repeat_plane, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.repeat_dir, enrSYLL_STATE.repeat_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.repeat_dir, enrSYLL_STATE.repeat_plane, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.repeat_dir, enrSYLL_STATE.movesyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.repeat_dir, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.movesyll_separator, enrSYLL_STATE.move_depth, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.movesyll_separator, enrSYLL_STATE.move_plane, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.movesyll_separator, enrSYLL_STATE.move_touch_flag, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.movesyll_separator, enrSYLL_STATE.handshape_thumb, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.movesyll_separator, enrSYLL_STATE.handshape_finger, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.movesyll_separator, enrSYLL_STATE.palm_pinky, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.movesyll_separator, enrSYLL_STATE.palm_facing, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.movesyll_separator, enrSYLL_STATE.word_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.basehand_flag, enrSYLL_STATE.basehand_handshape_finger, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.basehand_flag, enrSYLL_STATE.basehand_palm_facing, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.basehand_handshape_finger, enrSYLL_STATE.basehand_handshape_finger, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.basehand_handshape_finger, enrSYLL_STATE.basehand_handshape_thumb, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.basehand_handshape_finger, enrSYLL_STATE.basehand_palm_facing, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.basehand_handshape_thumb, enrSYLL_STATE.basehand_handshape_finger, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.basehand_handshape_thumb, enrSYLL_STATE.basehand_palm_facing, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.basehand_handshape_thumb, enrSYLL_STATE.movesyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.basehand_palm_facing, enrSYLL_STATE.basehand_palm_pinky, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.basehand_palm_facing, enrSYLL_STATE.movesyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.basehand_palm_pinky, enrSYLL_STATE.movesyll_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.eyeword_plane, enrSYLL_STATE.eyeword_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.eyeword_plane, enrSYLL_STATE.eyeword_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.eyeword_plane, enrSYLL_STATE.fingerspelling_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.eyeword_plane, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.eyeword_dir, enrSYLL_STATE.eyeword_separator, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.eyeword_dir, enrSYLL_STATE.eyeword_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.eyeword_dir, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.eyeword_separator, enrSYLL_STATE.eyeword_plane, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.eyeword_separator, enrSYLL_STATE.eyeword_dir, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.fingerspelling_separator, enrSYLL_STATE.fingerspelling_letter, enrSYLL_DSCR.none));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.fingerspelling_letter, enrSYLL_STATE.fingerspelling_letter, enrSYLL_DSCR.incomplete));
            ret_list.Add(new SyllTransition(enrSYLL_STATE.fingerspelling_letter, enrSYLL_STATE.word_end, enrSYLL_DSCR.none));

            foreach (var entry in ret_list)
            {
                if (entry.new_syll == enrSYLL_DSCR.none)
                {
                    if (ur_dscr_lookup.ContainsKey(entry.cur_state))
                    {
                        entry.new_syll = ur_dscr_lookup[entry.cur_state];
                    }
                    else
                    {
                        //var abc = "";
                    }
                }
            }

            return(ret_list);
        }
Ejemplo n.º 8
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            string formString = GameRequest.GetFormString("account");

            if (formString == "")
            {
                base.Response.Write("充值账号错误");
                base.Response.End();
            }
            int formInt = GameRequest.GetFormInt("amount", 0);

            if (formInt < 6)
            {
                base.Response.Write("充值金额不能低于6元");
                base.Response.End();
            }
            string      text        = GameRequest.GetFormString("type");
            OnLineOrder onLineOrder = new OnLineOrder();

            onLineOrder.OrderID = PayHelper.GetOrderIDByPrefix("dd");
            if (Fetch.GetUserCookie() == null)
            {
                onLineOrder.OperUserID = 0;
            }
            else
            {
                onLineOrder.OperUserID = Fetch.GetUserCookie().UserID;
            }
            onLineOrder.Accounts    = formString;
            onLineOrder.OrderAmount = formInt;
            onLineOrder.IPAddress   = GameRequest.GetUserIP();
            string text4 = text;

            switch (text4)
            {
            case "alipay":
                text = "010008";
                onLineOrder.ShareID = 2;
                goto IL_289;

            case "weixin":
                text = "010007";
                onLineOrder.ShareID = 3;
                goto IL_289;

            case "alipay-scan":
                text                = "010002";
                this.paytype        = "支付宝";
                onLineOrder.ShareID = 4;
                goto IL_289;

            case "weixin-scan":
                text                = "010001";
                this.paytype        = "微信";
                onLineOrder.ShareID = 5;
                goto IL_289;

            case "qq":
                text = "7";
                onLineOrder.ShareID = 6;
                goto IL_289;

            case "kuaijie":
                text = "010010";
                onLineOrder.ShareID = 7;
                goto IL_289;

            case "qq-scan":
                text                = "010000";
                this.paytype        = "QQ";
                onLineOrder.ShareID = 8;
                goto IL_289;

            case "jd":
                text = "6";
                onLineOrder.ShareID = 9;
                goto IL_289;

            case "baidu":
                text = "5";
                onLineOrder.ShareID = 10;
                goto IL_289;
            }
            text = "4";
            onLineOrder.ShareID = 1;
IL_289:
            Message message = FacadeManage.aideTreasureFacade.RequestOrder(onLineOrder);

            if (!message.Success)
            {
                base.Response.Write(message.Content);
                base.Response.End();
            }
            string url   = ApplicationSettings.Get("url_dd");
            string value = ApplicationSettings.Get("parter_dd");
            string str   = ApplicationSettings.Get("key_dd");
            string text2 = ApplicationSettings.Get("pay_url");

            if (text2 == "")
            {
                text2 = "http://" + base.Request.Url.Host;
            }
            string orderID = onLineOrder.OrderID;
            string value2  = text2 + "/pay/diandian/notify_url.aspx";
            string str2    = "{\"mch_app_id\":\"http://www.qp137.com\",\"device_info\":\"AND_WAP\",\"ua\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\",\"mch_app_name\":\"支付测试\",\"cashier_desk\":\"1\"}";
            string s       = System.Web.HttpUtility.UrlEncode(str2);

            byte[] bytes  = System.Text.Encoding.UTF8.GetBytes(s);
            string value3 = System.Convert.ToBase64String(bytes);

            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
            dictionary["version"]      = "1.0";
            dictionary["charset"]      = "utf-8";
            dictionary["merchant_id"]  = value;
            dictionary["out_trade_no"] = orderID;
            dictionary["user_ip"]      = GameRequest.GetUserIP();
            dictionary["subject"]      = "支付测试";
            dictionary["body"]         = "支付测试";
            dictionary["user_id"]      = formString;
            dictionary["total_fee"]    = formInt.ToString("#0.00");
            dictionary["notify_url"]   = value2;
            dictionary["return_url"]   = value2;
            dictionary["nonce_str"]    = TextUtility.CreateAuthStr(20, false);
            dictionary["biz_content"]  = value3;
            dictionary["trade_type"]   = text;
            dictionary = (
                from p in dictionary
                orderby p.Key
                select p).ToDictionary((System.Collections.Generic.KeyValuePair <string, string> p) => p.Key, (System.Collections.Generic.KeyValuePair <string, string> o) => o.Value);
            string str3 = PayHelper.PrepareSign(dictionary) + "&key=" + str;

            dictionary["sign"] = Jiami.MD5(str3).ToUpper();
            string param = PayHelper.ToXml(dictionary);
            string text3 = HttpHelper.HttpRequest(url, param, "post", "utf-8", "text/xml");

            System.Collections.Generic.Dictionary <string, string> dictionary2 = PayHelper.XmlToDic(text3);
            if (!dictionary2.ContainsKey("status"))
            {
                base.Response.Write(text3);
                base.Response.End();
            }
            else
            {
                string a = dictionary2["status"];
                if (a == "0")
                {
                    this.order_no     = orderID;
                    this.order_amount = formInt.ToString();
                    this.qrcode       = dictionary2["pay_info"];
                    base.Response.Redirect(this.qrcode);
                }
                else
                {
                    base.Response.Write(dictionary2["message"]);
                    base.Response.End();
                }
            }
        }
Ejemplo n.º 9
0
 private bool IsDerivedFromCslNode(string type)
 {
     return(m_nameToClass.ContainsKey(type));
 }
Ejemplo n.º 10
0
 public bool ContainsStudent(TKey Key)
 {
     return(dict.ContainsKey(Key));
 }
Ejemplo n.º 11
0
 public bool Has(string key)
 {
     return(data_.ContainsKey(key.ToUpper()));
 }
Ejemplo n.º 12
0
            //--------------------------------------------------------------------------------------------------------
            /// <summary>
            /// 载入词典词库 (载入的默认词库文件为同目目录下的DicKey.dic)
            /// </summary>
            /// <returns></returns>
            public bool LoadDic(string subPath)
            {

                //if (!subPath.Equals("XJU.SpellCheck.Spelling"))
                //    return false;
                try
                {

                    this.fs = new System.IO.FileStream("Dic.dic", System.IO.FileMode.Open);
                    this.sr = new System.IO.StreamReader(fs, System.Text.Encoding.Default);
                    this.DicTemp = new List<int>();
                    this.myDic = new Dictionary<string, string>();
                    this.resulList = new Dictionary<string, float>();
                    this.myDicList = new List<string>();
                    string inStr;
                    //开始读
                    while (sr.Peek() >= 0)
                    {
                        inStr = sr.ReadLine().Trim();
                        if (!myDic.ContainsKey(inStr))
                        {
                            this.myDic.Add(inStr, String.Empty);
                            this.myDicList.Add(inStr);
                        }
                    }
                    
                    //清理工作
                    this.sr.Close();
                    this.fs.Close();
                }
                catch(Exception openErr)
                {
                    this.myDic = null;
                    this.errMessage = openErr.Message;
                    return false;
                }
                try
                {

                    this.fs = new System.IO.FileStream("user.dic", System.IO.FileMode.Open);
                    this.sr = new System.IO.StreamReader(fs, System.Text.Encoding.Default);
                    string inStr;
                    //开始读
                    while (sr.Peek() >= 0)
                    {
                        inStr = sr.ReadLine().Trim();
                        if (!myDic.ContainsKey(inStr))
                        {
                            myDic.Add(inStr, String.Empty);
                            this.myDicList.Add(inStr);
                        }
                    }

                    //清理工作
                    this.sr.Close();
                    this.fs.Close();
                    return true;
                }
                catch (Exception openErr)
                {
                    this.errMessage = openErr.Message;
                    return true;

                }

            }
Ejemplo n.º 13
0
        public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
        {
            _errorCount = 0;

            var sb = new StringBuilder();
            lines.ForEach(line => sb.AppendLine(line));
            var xml = new XmlDocument();
            xml.LoadXml(sb.ToString().Trim());

            var nsmgr = new XmlNamespaceManager(xml.NameTable);
            nsmgr.AddNamespace("ttaf1", xml.DocumentElement.NamespaceURI);

            XmlNode div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).SelectSingleNode("ttaf1:div", nsmgr);
            if (div == null)
                div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).FirstChild;

            var styleDic = new System.Collections.Generic.Dictionary<string, string>();
            foreach (XmlNode node in xml.DocumentElement.SelectNodes("//ttaf1:style", nsmgr))
            {
                if (node.Attributes["tts:fontStyle"] != null && node.Attributes["xml:id"] != null)
                {
                    styleDic.Add(node.Attributes["xml:id"].Value, node.Attributes["tts:fontStyle"].Value);
                }
            }

            foreach (XmlNode node in div.ChildNodes)
            {
                try
                {
                    var pText = new StringBuilder();
                    foreach (XmlNode innerNode in node.ChildNodes)
                    {
                        switch (innerNode.Name)
                        {
                            case "br":
                                pText.AppendLine();
                                break;
                            case "span":
                                bool italic = false;
                                if (innerNode.Attributes["style"] != null && styleDic.ContainsKey(innerNode.Attributes["style"].Value))
                                {
                                    if (styleDic[innerNode.Attributes["style"].Value].Contains("italic"))
                                    {
                                        italic = true;
                                        pText.Append("<i>");
                                    }
                                }
                                if (!italic && innerNode.Attributes != null)
                                {
                                    var fs = innerNode.Attributes.GetNamedItem("tts:fontStyle");
                                    if (fs != null && fs.Value == "italic")
                                    {
                                        italic = true;
                                        pText.Append("<i>");
                                    }
                                }
                                if (innerNode.HasChildNodes)
                                {
                                    foreach (XmlNode innerInnerNode in innerNode.ChildNodes)
                                    {
                                        if (innerInnerNode.Name == "br")
                                        {
                                            pText.AppendLine();
                                        }
                                        else
                                        {
                                            pText.Append(innerInnerNode.InnerText);
                                        }
                                    }
                                }
                                else
                                {
                                    pText.Append(innerNode.InnerText);
                                }
                                if (italic)
                                    pText.Append("</i>");
                                break;
                            case "i":
                                pText.Append("<i>" + innerNode.InnerText + "</i>");
                                break;
                            case "b":
                                pText.Append("<b>" + innerNode.InnerText + "</b>");
                                break;
                            default:
                                pText.Append(innerNode.InnerText);
                                break;
                        }
                    }

                    string start = null; // = node.Attributes["begin"].InnerText;
                    string end = null; // = node.Attributes["begin"].InnerText;
                    string dur = null; // = node.Attributes["begin"].InnerText;
                    foreach (XmlAttribute attr in node.Attributes)
                    {
                        if (attr.Name.EndsWith("begin"))
                            start = attr.InnerText;
                        else if (attr.Name.EndsWith("end"))
                            end = attr.InnerText;
                        else if (attr.Name.EndsWith("duration"))
                            dur = attr.InnerText;
                    }
                    //string start = node.Attributes["begin"].InnerText;
                    string text = pText.ToString();
                    text = text.Replace(Environment.NewLine + "</i>", "</i>" + Environment.NewLine);
                    text = text.Replace("<i></i>", string.Empty).Trim();
                    if (end != null)
                    {
                        //string end = node.Attributes["end"].InnerText;
                        double dBegin, dEnd;
                        if (!start.Contains(":") && Utilities.CountTagInText(start, ".") == 1 && !start.Contains(":") && Utilities.CountTagInText(start, ".") == 1 &&
                            double.TryParse(start, out dBegin) && double.TryParse(end, out dEnd))
                        {
                            subtitle.Paragraphs.Add(new Paragraph(text, dBegin * 1000.0, dEnd * 1000.0));
                        }
                        else
                        {
                            if (start.Length == 8 && start[2] == ':' && start[5] == ':' &&
                                end.Length == 8 && end[2] == ':' && end[5] == ':')
                            {
                                Paragraph p = new Paragraph();
                                string[] parts = start.Split(new[] { ':' });
                                p.StartTime = new TimeCode(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), 0);
                                parts = end.Split(new[] { ':' });
                                p.EndTime = new TimeCode(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), 0);
                                p.Text = text;
                                subtitle.Paragraphs.Add(p);
                            }
                            else
                            {
                                subtitle.Paragraphs.Add(new Paragraph(TimedText10.GetTimeCode(start, false), TimedText10.GetTimeCode(end, false), text));
                            }
                        }
                    }
                    else if (dur != null)
                    {
                        TimeCode duration = TimedText10.GetTimeCode(dur, false);
                        TimeCode startTime = TimedText10.GetTimeCode(start, false);
                        TimeCode endTime = new TimeCode(startTime.TotalMilliseconds + duration.TotalMilliseconds);
                        subtitle.Paragraphs.Add(new Paragraph(startTime, endTime, text));
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    _errorCount++;
                }
            }
            subtitle.RemoveEmptyLines();
            subtitle.Renumber(1);
        }
public void LoadLevel()
{
        int verticalOffset = 85;
		
        //Debug.Log("Loading level at: " + _fullMapPath);
		
        Substrate.AnvilWorld mcWorld = Substrate.AnvilWorld.Create(_fullMapPath);
			
        Substrate.AnvilRegionManager mcAnvilRegionManager = mcWorld.GetRegionManager();
				
        OpenCog.BlockSet.OCBlockSet blockSet = _map.GetBlockSet();
				
        //_map.GetSunLightmap().SetSunHeight(20, 4, 4);

        int createCount = 0;
		
        System.Collections.Generic.Dictionary<int, int> unmappedBlockTypes = new System.Collections.Generic.Dictionary<int, int>();

        //Debug.Log("In LoadLevel, there are " + blockSet.BlockCount + " blocks available.");
		
        foreach(Substrate.AnvilRegion mcAnvilRegion in mcAnvilRegionManager)
        {
                // Loop through x-axis of chunks in this region
                for(int iMCChunkX  = 0; iMCChunkX < mcAnvilRegion.XDim; iMCChunkX++)
                {
                        // Loop through z-axis of chunks in this region.
                        for(int iMCChunkZ = 0; iMCChunkZ < mcAnvilRegion.ZDim; iMCChunkZ++)
                        {
                                // Retrieve the chunk at the current position in our 2D loop...
                                Substrate.ChunkRef mcChunkRef = mcAnvilRegion.GetChunkRef(iMCChunkX, iMCChunkZ);
					
                                if(mcChunkRef != null)
                                {
                                        if(mcChunkRef.IsTerrainPopulated)
                                        {
                                                // Ok...now to stick the blocks in...
							
                                                int iMCChunkY = 0;
							
                                                OCChunk chunk = null;//new OCChunk(_map, new Vector3i(iMCChunkX, iMCChunkY, iMCChunkZ));
                                                OCChunk lastChunk = null;
							
							
                                                Vector3i chunkPos = new Vector3i(mcAnvilRegion.ChunkGlobalX(iMCChunkX), iMCChunkY + verticalOffset, mcAnvilRegion.ChunkGlobalZ(iMCChunkZ));
                                                Vector3i lastChunkPos = Vector3i.zero;
                                                chunk = _map.GetChunkInstance(chunkPos);
							
                                                for(int iMCChunkInternalY = 0; iMCChunkInternalY < mcChunkRef.Blocks.YDim; iMCChunkInternalY++)
                                                {
                                                        if(iMCChunkInternalY / OCChunk.SIZE_Y > iMCChunkY)
                                                        {
                                                                lastChunk = chunk;
                                                                lastChunkPos = chunkPos;
                                                                chunkPos = new Vector3i(mcAnvilRegion.ChunkGlobalX(iMCChunkX), (iMCChunkInternalY + verticalOffset) / OCChunk.SIZE_Y, mcAnvilRegion.ChunkGlobalZ(iMCChunkZ));
                                                                chunk = _map.GetChunkInstance(chunkPos);
                                                        }
								
                                                        for(int iMCChunkInternalX = 0; iMCChunkInternalX < mcChunkRef.Blocks.XDim; iMCChunkInternalX++)
                                                        {
                                                                for(int iMCChunkInternalZ = 0; iMCChunkInternalZ < mcChunkRef.Blocks.ZDim; iMCChunkInternalZ++)
                                                                {
                                                                        int iBlockID = mcChunkRef.Blocks.GetID(iMCChunkInternalX, iMCChunkInternalY, iMCChunkInternalZ);
										
                                                                        if(iBlockID != 0)
                                                                        {
                                                                                Vector3i blockPos = new Vector3i(iMCChunkInternalX, iMCChunkInternalY % OCChunk.SIZE_Y, iMCChunkInternalZ);											
											
                                                                                int ourBlockID = -1;
											
//											switch (iBlockID)
//											{
//											case 3: // Dirt to first grass
//												ourBlockID = 1;
//												break;
//											case 12: // Grass to grass
//												ourBlockID = 1;
//												break;
//											case 13: // Gravel to stone
//												ourBlockID = 4;
//												break;
//											case 1: // Stone to second stone
//												ourBlockID = 5;
//												break;
//											case 16: // Coal ore to fungus
//												ourBlockID = 17;
//												break;
//											case 15: // Iron ore to pumpkin
//												ourBlockID = 20;
//												break;
//											case 9: // Water to water
//												ourBlockID = 8;
//												//Debug.Log ("Creating some water at [" + blockPos.x + ", " + blockPos.y + ", " + blockPos.z + "]");
//												break;
////											case 2:
////												iBlockID = 16;
////												break;
////											case 4:
////												iBlockID = 16;
////												break;
////											case 18:
////												iBlockID = 16;
////												break;
//											default: 
//											{
//												//Debug.Log ("Unmapped BlockID: " + iBlockID);
//												
//												if (!unmappedBlockTypes.ContainsKey (iBlockID))
//												{
//													unmappedBlockTypes.Add (iBlockID, 1);	
//												}
//												else
//												{
//													unmappedBlockTypes[iBlockID] += 1;	
//												}
//												
//												break;
//												}
//											}
											
                                                                                if(mcToOCBlockDictionary.ContainsKey(iBlockID))
                                                                                {
                                                                                        ourBlockID = mcToOCBlockDictionary[iBlockID];
                                                                                } else
                                                                                {
                                                                                        if(!unmappedBlockTypes.ContainsKey(iBlockID))
                                                                                        {
                                                                                                unmappedBlockTypes.Add(iBlockID, 1);	
                                                                                        } else
                                                                                        {
                                                                                                unmappedBlockTypes[iBlockID] += 1;	
                                                                                        }
                                                                                }
											
                                                                                if(ourBlockID != -1)
                                                                                {
                                                                                        OCBlock newBlock = blockSet.GetBlock(ourBlockID);
												
                                                                                        //OCBlockData block = new OpenCog.Map.OCBlockData(newBlock, blockPos);
                                                                                        OCBlockData block = (OCBlockData)OCScriptableObject.CreateInstance<OCBlockData>();
                                                                                        block.Init(newBlock, blockPos);
											
                                                                                        chunk.SetBlock(block, blockPos);
                                                                                        OpenCog.Map.Lighting.OCLightComputer.RecomputeLightAtPosition(_map, blockPos);
												
                                                                                        if(block.block.GetName() == "Battery")
                                                                                        {
                                                                                                GameObject batteryPrefab = OCMap.Instance.BatteryPrefab;
                                                                                                if(batteryPrefab == null)
                                                                                                {
                                                                                                        UnityEngine.Debug.LogWarning(OCLogSymbol.WARN + "OCBuilder::Update, batteryPrefab == null");
                                                                                                } else
                                                                                                {
                                                                                                        GameObject battery = (GameObject)GameObject.Instantiate(batteryPrefab);
                                                                                                        battery.transform.position = blockPos;
                                                                                                        battery.name = "Battery";		
                                                                                                        battery.transform.parent = OCMap.Instance.BatteriesSceneObject.transform;
                                                                                                }
													
                                                                                        }
													
                                                                                        if(block.block.GetName() == "Hearth")
                                                                                        {
                                                                                                GameObject hearthPrefab = OCMap.Instance.HearthPrefab;
                                                                                                if(hearthPrefab == null)
                                                                                                {
																									UnityEngine.Debug.LogWarning(OCLogSymbol.WARN +"OCBuilder::Update, hearthPrefab == null");
                                                                                                } else
                                                                                                {
                                                                                                        GameObject hearth = (GameObject)GameObject.Instantiate(hearthPrefab);
                                                                                                        hearth.transform.position = blockPos;
                                                                                                        hearth.name = "Hearth";		
                                                                                                        hearth.transform.parent = OCMap.Instance.HearthsSceneObject.transform;
                                                                                                }
                                                                                        }
												
                                                                                        createCount += 1;
                                                                                }
                                                                        }
                                                                } // End for (int iMCChunkInternalZ = 0; iMCChunkInternalZ < mcChunkRef.Blocks.ZDim; iMCChunkInternalZ++)
                                                        } // End for (int iMCChunkInternalY = 0; iMCChunkInternalY < mcChunkRef.Blocks.YDim; iMCChunkInternalY++)
								
                                                        string chunkCoord = chunkPos.x + ", " + chunkPos.z;
								
                                                        if(!chunkList.ContainsKey(chunkCoord))
                                                        {
                                                                chunkList.Add(chunkCoord, chunkPos);
                                                        }
								
                                                        if(iMCChunkY < iMCChunkInternalY / OCChunk.SIZE_Y)
                                                        {
                                                                _map.Chunks.AddOrReplace(lastChunk, lastChunkPos);
                                                                _map.UpdateChunkLimits(lastChunkPos);
                                                                _map.SetDirty(lastChunkPos);
                                                                iMCChunkY = iMCChunkInternalY / OCChunk.SIZE_Y;
                                                        }
								
                                                } // End for (int iMCChunkInternalX = 0; iMCChunkInternalX < mcChunkRef.Blocks.XDim; iMCChunkInternalX++)
                                        } // End if (mcChunkRef.IsTerrainPopulated)
                                } // End if (mcChunkRef != null)
                        } // End for (int iMCChunkZ = 0; iMCChunkZ < mcAnvilRegion.ZDim; iMCChunkZ++)
                } // End for (int iMCChunkX  = 0; iMCChunkX < mcAnvilRegion.XDim; iMCChunkX++)
        } // End foreach( Substrate.AnvilRegion mcAnvilRegion in mcAnvilRegionManager )
		
        foreach(Vector3i chunkToLight in chunkList.Values)
        {
                OpenCog.Map.Lighting.OCChunkSunLightComputer.ComputeRays(_map, chunkToLight.x, chunkToLight.z);
                OpenCog.Map.Lighting.OCChunkSunLightComputer.Scatter(_map, null, chunkToLight.x, chunkToLight.z);
        }
		
        foreach(System.Collections.Generic.KeyValuePair<int, int> unmappedBlockData in unmappedBlockTypes)
        {
                UnityEngine.Debug.LogWarning(OCLogSymbol.WARN + "Unmapped BlockID '" + unmappedBlockData.Key + "' found " + unmappedBlockData.Value + " times.");	
        }
		
        Debug.Log(OCLogSymbol.CLEARED + "Loaded level: " + _fullMapPath + ", created " + createCount + " blocks.");
		
        _map.AddColliders();
		
} // End public void LoadLevel()
Ejemplo n.º 15
0
        private void RefreshTreeviewNodeFormatting(TreeNode treeNode)
        {
            Cursor origCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            //if (isFolder(treeNode))
            if (treeNode.Nodes.Count > 0)
            {
                // First rename (title) the node items...
                //value = "{get_accession.accession_number_part1} + \" \" + {get_accession.accession_number_part2} + \" \" + {get_accession.accession_number_part3}; ";
                System.Collections.Generic.Dictionary<string, string> idTypeFormattingFormula = new System.Collections.Generic.Dictionary<string, string>();
                System.Collections.Generic.List<string> idTypes = new System.Collections.Generic.List<string>();
                System.Collections.Generic.Dictionary<string, string> idNumbers = new System.Collections.Generic.Dictionary<string, string>();
                DataSet ds = new DataSet();

                // First find all of the distinct ID_TYPES,
                // their corresponding formatting formulas,
                // and gather all of the ID_NUMBERS for each ID_TYPE in the userItemList collection...
                foreach (TreeNode tn in treeNode.Nodes)
                {
                    if (!isFolder(tn))
                    {
            //string pKey = tn.Tag.ToString().Split(';')[1].Trim();
            //string nodePKeyType = pKey.Split('=')[0].Replace(":", "").Trim().ToUpper();
            //string nodePKeyValue = pKey.Split('=')[1].Trim().ToUpper();
            string[] pKey = tn.Name.Split('=');
            string nodePKeyType = pKey[0];
            string nodePKeyValue = pKey[1];

                        // Get the ID_TYPE...
                        if (!idTypes.Contains(nodePKeyType)) idTypes.Add(nodePKeyType);
                        // Now get the formatting formula for each ID_TYPE in the collection...
                        if (!idTypeFormattingFormula.ContainsKey(nodePKeyType))
                        {
                            //string formula = GetTreeviewNodeProperty(nodePKeyType + "_NAME_FORMULA", tn);
                            string formula = GetTreeviewNodeProperty(tn.Tag.ToString().Split(';')[0].Trim().ToUpper() + "_NAME_FORMULA", tn, true, "");
                            if (string.IsNullOrEmpty(formula))
                            {
                                // Could not find a formula for this type of treenode object type...
                            }
                            idTypeFormattingFormula.Add(nodePKeyType, formula);
                        }
                        // Next collect all of the ID_NUMBERS for each of the ID_TYPES for the userItemList collection...
                        if (!idNumbers.ContainsKey(nodePKeyType))
                        {
                            idNumbers.Add(nodePKeyType, nodePKeyValue + ",");
                        }
                        else
                        {
                            idNumbers[nodePKeyType] = idNumbers[nodePKeyType] + nodePKeyValue + ",";
                        }
                    }
                    else
                    {
                        if (ux_checkboxIncludeSubFolders.Checked)
                        {
                            RefreshTreeviewNodeFormatting(tn);
                        }
                    }
                }

                Dictionary<string, Dictionary<int, string>> friendlyNames = new Dictionary<string,Dictionary<int,string>>();

                // Make all the trips to the server now to get all data needed for new userItemList titles...
                foreach (string idType in idTypes)
                {
                    // Create the new dictionary LU for the friendly name and add it to the collection...
                    friendlyNames.Add(idType, new Dictionary<int, string>());

                    // Break down the name formula into tokens and process the tokens one by one...
                    string[] formatTokens = idTypeFormattingFormula[idType].Split(new string[] { " + " }, StringSplitOptions.RemoveEmptyEntries);
                    string staticTextSeparator = "";
                    foreach (string formatToken in formatTokens)
                    {
                        if (formatToken.Contains("{") &&
                            formatToken.Contains("}"))
                        {
                            // This is a DB field used in the title - so if we don't already have it go get it now...
                            string[] dataviewAndField = formatToken.Trim().Replace("{", "").Replace("}", "").Trim().Split(new char[] { '.' });
                            if (!ds.Tables.Contains(dataviewAndField[0]))
                            {
                                DataSet newDS = _sharedUtils.GetWebServiceData(dataviewAndField[0], idType.Trim().ToLower() + "=" + idNumbers[idType].Trim().TrimEnd(','), 0, 0);
                                if (newDS != null &&
                                    newDS.Tables.Contains(dataviewAndField[0]))
                                {
                                    ds.Tables.Add(newDS.Tables[dataviewAndField[0]].Copy());
                                }
            else if (newDS.Tables.Contains("ExceptionTable") &&
            newDS.Tables["ExceptionTable"].Rows.Count > 0)
            {
            GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("There was an unexpected error retrieving data from {0} to use in building a node friendly name.\n\nFull error message:\n{1}", "Get Name Data Error", MessageBoxButtons.OK, MessageBoxDefaultButton.Button1);
            ggMessageBox.Name = "RefreshTreeviewNodeFormatting1";
            _sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
            //if (ggMessageBox.MessageText.Contains("{0}") &&
            //    ggMessageBox.MessageText.Contains("{1}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, dataviewAndField[0], newDS.Tables["ExceptionTable"].Rows[0]["Message"].ToString());
            //}
            //else if (ggMessageBox.MessageText.Contains("{0}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, dataviewAndField[0]);
            //}
            //else if (ggMessageBox.MessageText.Contains("{1}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, newDS.Tables["ExceptionTable"].Rows[0]["Message"].ToString());
            //}
            string[] argsArray = new string[100];
            argsArray[0] = dataviewAndField[0];
            argsArray[1] = newDS.Tables["ExceptionTable"].Rows[0]["Message"].ToString();
            ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, argsArray);
            ggMessageBox.ShowDialog();
            }
                            }
                            // Process all of the rows in the table to add the dbToken to the friendly name...
                            // But first check to make sure the field exists in the datatable (if it doesn't exist just skip it)...
                            if (ds != null &&
                                ds.Tables.Count > 0 &&
                                ds.Tables[dataviewAndField[0]].Columns.Contains(dataviewAndField[1]))
                            {
                                foreach (DataRow dr in ds.Tables[dataviewAndField[0]].Rows)
                                {
                                    int pkey;
                                    string dbTokenText = dr[dataviewAndField[1]].ToString();
                                    DataColumn dc = ds.Tables[dataviewAndField[0]].Columns[dataviewAndField[1]];

                                    if (int.TryParse(dr[ds.Tables[dataviewAndField[0]].PrimaryKey[0]].ToString(), out pkey) &&
                                        !string.IsNullOrEmpty(dbTokenText))
                                    {
                                        // Resolve fkeys and code_values to the display_member if necessary...
                                        if (_sharedUtils.LookupTablesIsValidFKField(dc))
                                        {
                                            dbTokenText = _sharedUtils.GetLookupDisplayMember(dc.ExtendedProperties["foreign_key_dataview_name"].ToString().Trim(), dbTokenText, "", dbTokenText);
                                        }
                                        else if (_sharedUtils.LookupTablesIsValidCodeValueField(dc))
                                        {
                                            dbTokenText = _sharedUtils.GetLookupDisplayMember("code_value_lookup", dbTokenText, dc.ExtendedProperties["group_name"].ToString(), dbTokenText);
                                        }
                                        // If the pkey is already in the dictionary append to it (otherwise add it)...
                                        if (friendlyNames[idType].ContainsKey(pkey))
                                        {
                                            friendlyNames[idType][pkey] += staticTextSeparator + dbTokenText;
                                        }
                                        else
                                        {
                                            friendlyNames[idType][pkey] = staticTextSeparator + dbTokenText;
                                        }
                                    }
                                }
                            }
                            staticTextSeparator = "";
                        }
                        else
                        {
                            staticTextSeparator += formatToken.Trim().Replace("\"", "");
                        }
                    }
                    if (!string.IsNullOrEmpty(staticTextSeparator))
                    {
                        for (int i = 0; i < friendlyNames[idType].Keys.Count; i++)
                        {
                            friendlyNames[idType][friendlyNames[idType].ElementAt(i).Key] += staticTextSeparator;
                        }
                    }
                }

                // Now refresh the titles for each item in the collection...
                // This next line REALLY speeds things up (it tells the control to stop painting during a major update)...
                treeNode.TreeView.BeginUpdate();
                foreach (TreeNode tn in treeNode.Nodes)
                {
                    if (!isFolder(tn))
                    {
                        string[] pKey = tn.Name.Split('=');
                        string nodePKeyType = pKey[0];
                        string nodePKeyValue = pKey[1];
                        int pkey;
                        //
                        if (int.TryParse(nodePKeyValue, out pkey) &&
                            friendlyNames[nodePKeyType].ContainsKey(pkey))
                        {
                            string title = friendlyNames[nodePKeyType][pkey];
                            tn.Text = title;
                            title = EnsureUniqueNodeText(treeNode, tn);
                            tn.Text = title.Trim();
                        }
                    }
                }
                // We are all done updating names so now we can let the treeview resume painting its display...
                treeNode.TreeView.EndUpdate();

            //                foreach (TreeNode tn in treeNode.Nodes)
            //                {
            //                    if (!isFolder(tn))
            //                    {
            ////string pKey = tn.Tag.ToString().Split(';')[1].Trim();
            ////string nodePKeyType = pKey.Split('=')[0].Replace(":", "").Trim().ToUpper();
            ////string nodePKeyValue = pKey.Split('=')[1].Trim().ToUpper();
            //string[] pKey = tn.Name.Split('=');
            //string nodePKeyType = pKey[0];
            //string nodePKeyValue = pKey[1];

            //                        string title = "";
            //                        string[] formatTokens = idTypeFormattingFormula[nodePKeyType].Split(new string[] { " + " }, StringSplitOptions.RemoveEmptyEntries);
            //                        foreach (string formatToken in formatTokens)
            //                        {
            //                            if (formatToken.Contains("{") &&
            //                                formatToken.Contains("}"))
            //                            {
            //                                // This is a DB field used in the title - so go get it...
            //                                string[] dataviewAndField = formatToken.Trim().Replace("{", "").Replace("}", "").Trim().Split(new char[] { '.' });
            //                                if (dataviewAndField.Length == 2)
            //                                {
            //                                    if (ds.Tables.Contains(dataviewAndField[0]) &&
            //                                        ds.Tables[dataviewAndField[0]].Rows.Count > 0 &&
            //                                        ds.Tables[dataviewAndField[0]].Columns.Contains(dataviewAndField[1]))
            //                                    {
            //                                        // The list of dataviews that can be used for building node titles must have a pkey that is one of the ID_TYPES
            //                                        // otherwise this next line won't work...
            //                                        DataRow tokenRawDataRow = ds.Tables[dataviewAndField[0]].Rows.Find(nodePKeyValue);
            //                                        if (tokenRawDataRow != null)
            //                                        {
            //                                            DataColumn dc = tokenRawDataRow.Table.Columns[dataviewAndField[1]];
            //                                            string valueMember = tokenRawDataRow[dataviewAndField[1]].ToString();
            //                                            if (_sharedUtils.LookupTablesIsValidFKField(dc) &&
            //                                                !string.IsNullOrEmpty(valueMember))
            //                                            {
            //                                                title += _sharedUtils.GetLookupDisplayMember(dc.ExtendedProperties["foreign_key_dataview_name"].ToString().Trim(), valueMember, "", valueMember);
            //                                            }
            //                                            else if (_sharedUtils.LookupTablesIsValidCodeValueField(dc) &&
            //                                                    !string.IsNullOrEmpty(valueMember))
            //                                            {
            ////title += _sharedUtils.GetLookupDisplayMember("code_value_lookup", valueMember, "", valueMember);
            //                                                title += _sharedUtils.GetLookupDisplayMember("code_value_lookup", valueMember, dc.ExtendedProperties["group_name"].ToString(), valueMember);
            //                                            }
            //                                            else
            //                                            {
            //                                                title += valueMember;
            //                                            }
            //                                        }
            //                                    }
            //                                }
            //                            }
            //                            else
            //                            {
            //                                title += formatToken.Trim().Replace("\"", "");
            //                            }
            //                        }
            //                        // If there was success in building a new node title and it is a different name than the old title, make sure it is unique and then replace the old title...
            //                        if (!string.IsNullOrEmpty(title))
            //                        {
            //                            tn.Text = title;
            //title = EnsureUniqueNodeText(treeNode, tn);
            //tn.Text = title.Trim();
            //                        }
            //                    }

            //                }

                // Now resort the items...
                string sortMode = GetTreeviewNodeProperty("SORT_MODE", treeNode, true, "MANUAL");
                string folderGroupingMode = GetTreeviewNodeProperty("FOLDER_GROUPING_MODE", treeNode, true, "TOP");
                if (isFolder(treeNode) && sortMode.ToUpper().Trim() != "MANUAL") sortFolder(treeNode, sortMode);
            }

            /*
            // Find the user_item_list row corresponding to this node...
            if (isFolder(treeNode))
            {
                // First rename (title) the node items...
                RefreshUserItemListTitles(drcItems);
                // Now resort the items...
                // Get the sort settings from the folder (actually it will come from the parent of the collection items)...
                if (drcItems.Length > 0)
                {
                    string sortMode = GetUserItemListProperty("SORT_MODE", drcItems[0]);
                    string folderGroupingMode = GetUserItemListProperty("FOLDER_GROUPING_MODE", drcItems[0]);
                    SortUserItemList(tabText, treeNode, sortMode, folderGroupingMode == "TOP");
                }
            }
            */
            // Restore cursor to default cursor...
            Cursor.Current = origCursor;
        }
Ejemplo n.º 16
0
 private void workerExportPdf_DoWork(object sender, DoWorkEventArgs e)
 {
     char[] chArray2;
     int num12;
     int num13;
     object obj2;
     char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars();
     BackgroundWorker worker = sender as BackgroundWorker;
     NoticeExportPdfParams @params = e.get_Argument() as NoticeExportPdfParams;
     ObjectList<NoticeNotice> notices = @params.Notices;
     int num = 0;
     if (this.rbExportAccountNotices.get_Checked())
     {
         foreach (NoticeNotice notice in notices)
         {
             if (worker.get_CancellationPending())
             {
                 e.set_Cancel(true);
                 break;
             }
             string str2 = string.IsNullOrEmpty(notice.HouseHolderName) ? ((string) "Неизвестная УК") : notice.HouseHolderName;
             chArray2 = invalidFileNameChars;
             num12 = 0;
             while (num12 < chArray2.Length)
             {
                 char ch = chArray2[num12];
                 str2 = str2.Replace(ch, ' ');
                 num12 = (int) (num12 + 1);
             }
             str2 = str2.Trim();
             System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(System.IO.Path.Combine(@params.PeriodDirectory.get_FullName(), str2));
             if (!info.get_Exists())
             {
                 info.Create();
             }
             ObjectList<NoticeNotice> list2 = new ObjectList<NoticeNotice>();
             list2.Add(notice);
             try
             {
                 using (System.Data.DataTable table = NoticeNotice.GetHeader(list2, this.cbHideClosedAccounts.get_Checked(), this.cbNoticeInformation.get_Checked()))
                 {
                     table.set_TableName("header");
                     using (System.Data.DataSet set = NoticeNotice.GetReport(list2, @params.NoticeTemplate.Sql))
                     {
                         if ((set.Tables.get_Count() < 2) || (set.Tables.get_Item(0).Rows.get_Count() == 0))
                         {
                             continue;
                         }
                         bool flag = false;
                         foreach (System.Data.DataRow row in table.Rows)
                         {
                             if (System.Convert.ToInt64(row.get_Item("id")) == notice.Id)
                             {
                                 foreach (System.Data.DataRow row2 in set.Tables.get_Item(0).Rows)
                                 {
                                     if (System.Convert.ToInt64(row2.get_Item("id")) == notice.Id)
                                     {
                                         flag = true;
                                         break;
                                     }
                                 }
                             }
                         }
                         if (!flag)
                         {
                             continue;
                         }
                         set.Tables.get_Item(0).set_TableName("pays");
                         set.Tables.get_Item(1).set_TableName("counter");
                         for (int i = 2; i < set.Tables.get_Count(); i = (int) (i + 1))
                         {
                             num13 = (int) (i - 1);
                             set.Tables.get_Item(i).set_TableName("data" + ((int) num13).ToString());
                         }
                         if (@params.NoticeTemplate.IdentityName == "Счет на оплату Ульяновск вариант 3")
                         {
                             if (set.Tables.get_Count() > 2)
                             {
                                 set.Tables.get_Item(2).set_TableName("organizations");
                             }
                             if (set.Tables.get_Count() > 3)
                             {
                                 set.Tables.get_Item(3).set_TableName("rates");
                             }
                         }
                         using (StiReport report = new StiReport())
                         {
                             report.LoadFromString(@params.NoticeTemplate.Template);
                             report.ReportCacheMode = StiReportCacheMode.Off;
                             report.Compile();
                             foreach (System.Data.DataTable table2 in set.Tables)
                             {
                                 report.RegData(table2.get_TableName(), (System.Data.DataTable) table2);
                             }
                             report.RegData("header", (System.Data.DataTable) table);
                             string accountNumber = notice.AccountNumber;
                             string str5 = System.IO.Path.Combine(info.get_FullName(), accountNumber);
                             if (System.IO.File.Exists(str5 + ".pdf"))
                             {
                                 int num5 = 1;
                                 num5 = 1;
                                 while (System.IO.File.Exists(str5 + "(" + ((int) num5).ToString() + ").pdf"))
                                 {
                                     num5 = (int) (num5 + 1);
                                 }
                                 obj2 = str5;
                                 str5 = string.Concat((object[]) new object[] { obj2, "(", ((int) num5), ")" });
                             }
                             report.ReportCacheMode = StiReportCacheMode.Off;
                             report.Compile();
                             report.Render(false);
                             new StiPdfExportService().ExportPdf(report, str5 + ".pdf");
                         }
                     }
                 }
             }
             catch (System.Exception exception)
             {
                 string message = string.Format("[{0}] Ошибка при выгрузке в PDF: Адрес: {4}, ЛС {3}{1}{2}{1}", new object[] { System.DateTime.Now.ToShortTimeString(), System.Environment.get_NewLine(), exception.get_Message(), notice.AccountNumber, notice.AddressName });
                 this.AddMessageToLogFile(info.get_FullName(), message, "errors");
                 continue;
             }
             int num6 = (int) (((num = (int) (num + 1)) * 100) / notices.get_Count());
             worker.ReportProgress(num6, (int) num);
         }
     }
     else
     {
         BoundaryCollection<long> boundarys = null;
         System.Collections.Generic.Dictionary<long, int[]> dictionary = null;
         foreach (System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IList<NoticeNotice>> pair in @params.HouseHolderNotices)
         {
             boundarys = new BoundaryCollection<long>(@params.MaxNoticesPerDocument, @params.MinHouseCount);
             dictionary = new System.Collections.Generic.Dictionary<long, int[]>();
             foreach (NoticeNotice notice2 in pair.Value)
             {
                 num = (int) (num + 1);
                 long num7 = (notice2.AddressLevel == 40) ? notice2.ParentAddrId : notice2.AddrId;
                 if (!dictionary.ContainsKey(num7))
                 {
                     dictionary.Add(num7, new int[] { 1, notice2.AddressLevel });
                 }
                 else
                 {
                     dictionary[num7][0] += 1;
                 }
             }
             int num8 = (int) ((num * 100) / notices.get_Count());
             worker.ReportProgress(num8, (int) num);
             foreach (System.Collections.Generic.KeyValuePair<long, int[]> pair2 in dictionary)
             {
                 boundarys.Add(pair2.Key, pair2.Value[0]);
             }
             System.Collections.Generic.Dictionary<string, int> dictionary2 = new System.Collections.Generic.Dictionary<string, int>();
             foreach (BoundaryCollectionNode<long> node in boundarys.Lists)
             {
                 if (node.Items.get_Count() > 0)
                 {
                     if (worker.get_CancellationPending())
                     {
                         e.set_Cancel(true);
                         break;
                     }
                     ObjectList<NoticeNotice> list3 = new ObjectList<NoticeNotice>();
                     string str7 = null;
                     System.Text.StringBuilder builder = new System.Text.StringBuilder();
                     foreach (long num9 in node.Items)
                     {
                         foreach (NoticeNotice notice3 in notices)
                         {
                             if (dictionary[num9][1] == 40)
                             {
                                 if (notice3.ParentAddrId == num9)
                                 {
                                     if (str7 == null)
                                     {
                                         str7 = string.IsNullOrEmpty(notice3.HouseHolderName) ? AIS.SN.Model.Constants.ObjectNotChoosedCaption : notice3.HouseHolderName;
                                         if (!dictionary2.ContainsKey(str7))
                                         {
                                             dictionary2.Add(str7, 1);
                                         }
                                     }
                                     builder.AppendLine(notice3.AddressName);
                                     list3.Add(notice3);
                                 }
                             }
                             else if (notice3.AddrId == num9)
                             {
                                 if (str7 == null)
                                 {
                                     str7 = string.IsNullOrEmpty(notice3.HouseHolderName) ? AIS.SN.Model.Constants.ObjectNotChoosedCaption : notice3.HouseHolderName;
                                     if (!dictionary2.ContainsKey(str7))
                                     {
                                         dictionary2.Add(str7, 1);
                                     }
                                 }
                                 builder.AppendLine(notice3.AddressName);
                                 list3.Add(notice3);
                             }
                         }
                     }
                     string str8 = str7;
                     chArray2 = invalidFileNameChars;
                     num12 = 0;
                     while (num12 < chArray2.Length)
                     {
                         char ch2 = chArray2[num12];
                         str8 = str8.Replace(ch2, ' ');
                         num12 = (int) (num12 + 1);
                     }
                     str8 = str8.Trim();
                     System.IO.DirectoryInfo info2 = new System.IO.DirectoryInfo(System.IO.Path.Combine(@params.PeriodDirectory.get_FullName(), str8));
                     if (!info2.get_Exists())
                     {
                         info2.Create();
                     }
                     using (System.Data.DataTable table3 = NoticeNotice.GetHeader(list3, this.cbHideClosedAccounts.get_Checked(), this.cbNoticeInformation.get_Checked()))
                     {
                         table3.set_TableName("header");
                         using (System.Data.DataSet set2 = NoticeNotice.GetReport(list3, @params.NoticeTemplate.Sql))
                         {
                             if ((set2.Tables.get_Count() >= 2) && (set2.Tables.get_Item(0).Rows.get_Count() != 0))
                             {
                                 set2.Tables.get_Item(0).set_TableName("pays");
                                 set2.Tables.get_Item(1).set_TableName("counter");
                                 for (int j = 2; j < set2.Tables.get_Count(); j = (int) (j + 1))
                                 {
                                     num13 = (int) (j - 1);
                                     set2.Tables.get_Item(j).set_TableName("data" + ((int) num13).ToString());
                                 }
                                 if (@params.NoticeTemplate.IdentityName == "Счет на оплату Ульяновск вариант 3")
                                 {
                                     if (set2.Tables.get_Count() > 2)
                                     {
                                         set2.Tables.get_Item(2).set_TableName("organizations");
                                     }
                                     if (set2.Tables.get_Count() > 3)
                                     {
                                         set2.Tables.get_Item(3).set_TableName("rates");
                                     }
                                 }
                                 using (StiReport report2 = new StiReport())
                                 {
                                     System.Collections.Generic.Dictionary<string, int> dictionary3;
                                     string str16;
                                     report2.LoadFromString(@params.NoticeTemplate.Template);
                                     report2.ReportCacheMode = StiReportCacheMode.Off;
                                     report2.Compile();
                                     foreach (System.Data.DataTable table4 in set2.Tables)
                                     {
                                         report2.RegData(table4.get_TableName(), (System.Data.DataTable) table4);
                                     }
                                     report2.RegData("header", (System.Data.DataTable) table3);
                                     report2.Compile();
                                     (dictionary3 = dictionary2).set_Item(str16 = str7, (num13 = dictionary3[str16]) + 1);
                                     string str10 = string.Format("{0} {1}", str7, (int) num13);
                                     chArray2 = invalidFileNameChars;
                                     for (num12 = 0; num12 < chArray2.Length; num12 = (int) (num12 + 1))
                                     {
                                         char ch3 = chArray2[num12];
                                         str10 = str10.Replace(ch3, ' ');
                                     }
                                     string str11 = System.IO.Path.Combine(info2.get_FullName(), str10);
                                     if (System.IO.File.Exists(str11 + ".pdf"))
                                     {
                                         int num11 = 1;
                                         num11 = 1;
                                         while (System.IO.File.Exists(str11 + "(" + ((int) num11).ToString() + ").pdf"))
                                         {
                                             num11 = (int) (num11 + 1);
                                         }
                                         obj2 = str11;
                                         str11 = string.Concat((object[]) new object[] { obj2, "(", ((int) num11), ")" });
                                     }
                                     try
                                     {
                                         report2.Render(false);
                                         new StiPdfExportService().ExportPdf(report2, str11 + ".pdf");
                                         System.IO.File.WriteAllText(str11 + ".txt", builder.ToString());
                                     }
                                     catch (System.IO.IOException exception2)
                                     {
                                         string str12 = string.Format("[{0}] Ошибка при записи в каталог.{1}{2}{1}", System.DateTime.Now.ToShortTimeString(), System.Environment.get_NewLine(), exception2.get_Message());
                                         string str13 = string.Format("[{0}] {1}{2}{1}", System.DateTime.Now.ToShortTimeString(), System.Environment.get_NewLine(), builder.ToString());
                                         this.AddMessageToLogFile(info2.get_FullName(), str12, "errors");
                                         this.AddMessageToLogFile(info2.get_FullName(), str13, "невыгруженные_адреса");
                                     }
                                     catch (System.Exception exception3)
                                     {
                                         string str14 = string.Format("[{0}] Ошибка при выгрузке в PDF..{1}{2}{1}", System.DateTime.Now.ToShortTimeString(), System.Environment.get_NewLine(), exception3.get_Message());
                                         string str15 = string.Format("[{0}] {1}{2}{1}", System.DateTime.Now.ToShortTimeString(), System.Environment.get_NewLine(), builder.ToString());
                                         this.AddMessageToLogFile(info2.get_FullName(), str14, "errors");
                                         this.AddMessageToLogFile(info2.get_FullName(), str15, "невыгруженные_адреса");
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 17
0
        private static System.Collections.Generic.Dictionary <int, SensorThreshold> GetSensorThreshold(System.Collections.Generic.Dictionary <string, string> result)
        {
            System.Collections.Generic.Dictionary <int, SensorThreshold> dictionary = new System.Collections.Generic.Dictionary <int, SensorThreshold>();
            System.Collections.Generic.IEnumerator <string> enumerator = result.Keys.GetEnumerator();
            EatonSensorTemperatureMib_M2 eatonSensorTemperatureMib_M   = null;
            EatonSensorHumidityMib_M2    eatonSensorHumidityMib_M      = null;
            int num = 0;

            while (enumerator.MoveNext())
            {
                string current = enumerator.Current;
                string text    = result[current];
                if ("\0".Equals(text))
                {
                    text = System.Convert.ToString(-10000);
                }
                else
                {
                    if (text == null || string.IsNullOrEmpty(text))
                    {
                        text = System.Convert.ToString(-5000);
                    }
                }
                int num2 = System.Convert.ToInt32(current.Substring(current.LastIndexOf(".") + 1));
                if (!dictionary.ContainsKey(num2))
                {
                    SensorThreshold value = new SensorThreshold(num2);
                    dictionary.Add(num2, value);
                }
                SensorThreshold sensorThreshold = dictionary[num2];
                if (num != num2)
                {
                    num = num2;
                    eatonSensorTemperatureMib_M = new EatonSensorTemperatureMib_M2(num2);
                    eatonSensorHumidityMib_M    = new EatonSensorHumidityMib_M2(num2);
                }
                float num3 = (float)System.Convert.ToInt32(text) / 10f;
                if (current.StartsWith(eatonSensorHumidityMib_M.MaxHumidityMT))
                {
                    sensorThreshold.MaxHumidityMT = num3;
                }
                else
                {
                    if (current.StartsWith(eatonSensorTemperatureMib_M.MaxTemperatureMT))
                    {
                        sensorThreshold.MaxTemperatureMT = num3;
                    }
                    else
                    {
                        if (current.StartsWith(eatonSensorHumidityMib_M.MinHumidityMt))
                        {
                            sensorThreshold.MinHumidityMT = num3;
                        }
                        else
                        {
                            if (!current.StartsWith(eatonSensorTemperatureMib_M.MinTemperatureMt))
                            {
                                return(new System.Collections.Generic.Dictionary <int, SensorThreshold>());
                            }
                            sensorThreshold.MinTemperatureMT = num3;
                        }
                    }
                }
            }
            return(dictionary);
        }
Ejemplo n.º 18
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            string formString = GameRequest.GetFormString("account");

            if (formString == "")
            {
                base.Response.Write("充值账号错误");
                base.Response.End();
            }
            int formInt = GameRequest.GetFormInt("amount", 0);

            if (formInt < 6)
            {
                base.Response.Write("充值金额不能低于6元");
                base.Response.End();
            }
            string      formString2 = GameRequest.GetFormString("type");
            OnLineOrder onLineOrder = new OnLineOrder();

            onLineOrder.OrderID = PayHelper.GetOrderIDByPrefix("45");
            if (Fetch.GetUserCookie() == null)
            {
                onLineOrder.OperUserID = 0;
            }
            else
            {
                onLineOrder.OperUserID = Fetch.GetUserCookie().UserID;
            }
            onLineOrder.Accounts    = formString;
            onLineOrder.OrderAmount = formInt;
            onLineOrder.IPAddress   = GameRequest.GetUserIP();
            string value = "";

            if (formString2 == "alipay")
            {
                value = "";
                onLineOrder.ShareID = 2;
                this.paytype        = "支付宝";
            }
            if (formString2 == "weixin")
            {
                value = "";
                onLineOrder.ShareID = 3;
                this.paytype        = "微信";
            }
            if (formString2 == "weixin-scan")
            {
                value = "";
                onLineOrder.ShareID = 5;
                this.paytype        = "微信";
            }
            Message message = FacadeManage.aideTreasureFacade.RequestOrder(onLineOrder);

            if (!message.Success)
            {
                base.Response.Write(message.Content);
                base.Response.End();
            }
            string url    = ApplicationSettings.Get("url_45");
            string value2 = ApplicationSettings.Get("parter_45");
            string text   = ApplicationSettings.Get("key_45");
            string text2  = ApplicationSettings.Get("pay_url");

            if (text2 == "")
            {
                text2 = "http://" + base.Request.Url.Host;
            }
            string value3 = text2 + "/pay/45/notify_url.aspx";

            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
            dictionary["v"]          = "1.0";
            dictionary["uid"]        = value2;
            dictionary["orderid"]    = onLineOrder.OrderID;
            dictionary["title"]      = "shop";
            dictionary["note"]       = "";
            dictionary["istype"]     = value;
            dictionary["amount"]     = formInt.ToString();
            dictionary["userpara"]   = "";
            dictionary["receiveurl"] = value3;
            dictionary["userIP "]    = GameRequest.GetUserIP();
            dictionary["returnurl"]  = value3;
            string password = string.Concat(new object[]
            {
                dictionary["uid"],
                dictionary["orderid"],
                formInt,
                dictionary["receiveurl"],
                text
            });
            string value4 = TextEncrypt.EncryptPassword(password).ToLower();

            dictionary["sign"] = value4;
            string param = PayHelper.PrepareSign(dictionary);
            string json  = HttpHelper.HttpRequest(url, param);

            System.Collections.Generic.Dictionary <string, string> dictionary2 = JsonHelper.DeserializeJsonToObject <System.Collections.Generic.Dictionary <string, string> >(json);
            if (!dictionary2.ContainsKey("result"))
            {
                base.Response.Write("接口正在维护中...");
            }
            else
            {
                if (dictionary2["result"].ToString() == "ok")
                {
                    base.Response.Redirect(dictionary2["data"]);
                }
                else
                {
                    base.Response.Write(dictionary2["msg"].ToString());
                }
            }
        }
Ejemplo n.º 19
0
        //based on the received criteria, generate a bunch of dates
        public ArrayList GenerateDateList()
        {
            ArrayList dates = new ArrayList();

            if (!hasBeenParsed)
            {
                throw new Exception("no information provided yet.");
            }

            //let's do the easy stuff first
            if (timeUnit == TimeUnit.Daily)
            {
                DateTime newDate  = startDt;
                int      dayCycle = this.everyNumber;
                if (dayCycle == 0)
                {
                    dayCycle = 1;
                }

                if (endDt != null)
                {
                    while (newDate <= endDt.Value)
                    {
                        dates.Add(newDate);
                        newDate = newDate.AddDays(dayCycle);
                    }
                }
                else
                {
                    int count    = 0;
                    int maxCount = this.occurNumber;
                    if (maxCount < 1)
                    {
                        maxCount = 1;
                    }
                    if (maxCount > 100)
                    {
                        maxCount = 100;
                    }
                    while (count < maxCount)
                    {
                        dates.Add(newDate);
                        newDate = newDate.AddDays(dayCycle);
                        count++;
                    }
                }
            }

            if (timeUnit == TimeUnit.Weekly)
            {
                DateTime newDate   = startDt;
                int      weekCycle = this.everyNumber;
                if (weekCycle == 0)
                {
                    weekCycle = 1;
                }
                //i can add days and add months, but not weeks.
                //so multiply this by 7
                weekCycle = weekCycle * 7;

                //hrmmmmm
                //"Repeat Weekly every 2 weeks on thursday and saturday"
                //i need to figure out week boundaries and skip weeks
                //or...
                //figure out a count for skipping a day name a number of times based on the query

                /*	everyNumber-1 do a skip
                 *      so if a thrusday every 3 weeks, skip 2 thursdays
                 */
                //set up counters
                //Hashtable dayCounter = new Hashtable();
                System.Collections.Generic.Dictionary <string, int> dayCounter = new System.Collections.Generic.Dictionary <string, int>();
                //
                int skipNumber = this.everyNumber - 1;
                if (skipNumber < 0)
                {
                    skipNumber = 0;
                }
                int skipCounter = 0;

                //load the dayCcounter
                foreach (string day in DayArray)
                {
                    if (!dayCounter.ContainsKey(day))
                    {
                        dayCounter.Add(day, 0);
                    }
                }

                if (endDt != null)
                {
                    while (newDate <= endDt.Value)
                    {
                        string dayOfWeek = newDate.DayOfWeek.ToString().ToLower();
                        if (dayCounter.ContainsKey(dayOfWeek))
                        {
                            if (dayCounter[dayOfWeek] == 0)
                            {
                                dates.Add(newDate);
                                dayCounter[dayOfWeek] = dayCounter[dayOfWeek] + 1;
                            }
                            else
                            {
                                if (dayCounter[dayOfWeek] == skipNumber)
                                {
                                    dayCounter[dayOfWeek] = 0;
                                }
                                else
                                {
                                    dates.Add(newDate);
                                    dayCounter[dayOfWeek] = dayCounter[dayOfWeek] + 1;
                                }
                            }
                        }

                        //increment
                        newDate = newDate.AddDays(1);
                    }
                }
                else
                {
                    int maxCount = this.occurNumber;
                    if (maxCount < 1)
                    {
                        maxCount = 1;
                    }
                    if (maxCount > 100)
                    {
                        maxCount = 100;
                    }

                    DateTime start = this.startDt;

                    foreach (string day in DayArray)
                    {
                        string dayOfWeek = start.DayOfWeek.ToString().ToLower();
                        while (dayCounter[day] < maxCount)
                        {
                            if (skipCounter == 0)
                            {
                                if (skipNumber > 0)
                                {
                                    skipCounter++;
                                }

                                dayOfWeek = start.DayOfWeek.ToString().ToLower();
                                if (dayCounter.ContainsKey(dayOfWeek))
                                {
                                    //don't add the current date
                                    //if (start > startDt) {
                                    dates.Add(start);
                                    //}
                                    dayCounter[day] = dayCounter[day] + 1;
                                }
                                start = start.AddDays(1);
                            }
                            else
                            {
                                if (skipCounter == skipNumber)
                                {
                                    skipCounter = 0;
                                }
                                else
                                {
                                    skipCounter++;
                                }
                                //scoot the time up one week
                                start = start.AddDays(1);
                            }
                        }
                    }
                }
            }

            if (timeUnit == TimeUnit.Monthly)
            {
                /*
                 * "repeat monthly every 2nd month on the 12th day..." note: start(end|occur) syntax the same from now on.
                 * repeat monthly every(2) day(12) {}
                 *
                 * "repeat monthly every 2nd month on the 2nd Thursday..."
                 * repeat monthly every(2) the(2)[Thursday] {}
                 *
                 * //this is causing an explosion
                 * it's saying that the start date is 12/3/9999 12:00:00 AM, and adding a month to it's not a representable date.
                 *
                 * repeat monthly every(1) day(3) {start(2006-12-1) occur(10)}
                 *
                 * 2008 12 22
                 * i ran into a bug
                 * i created monthly repeater starting on the first day of every month
                 * starting date: 2008 12 22
                 * it should have made the first date 2009 01 01, but it did 2008 instead
                 *
                 */

                //figure out the first date this can start.
                //get the current month, then check conditions.
                DateTime start      = startDt;
                int      skipNumber = everyNumber - 1;
                if (skipNumber < 0)
                {
                    skipNumber = 0;
                }
                int skipCounter = 0;

                if (this.dayNumber > 0)
                {
                    if (start.Day != dayNumber)
                    {
                        //the given start date is not really the beginning of the occurence.
                        //look for it movign forward
                        if (start.Day < dayNumber)
                        {
                            //look in current month
                            //ugh. we can quickly run into end-of month scenarios

                            //do a number diff. add the days
                            start = start.AddDays(dayNumber - start.Day);

                            //if this has kicked it to the next month, pull it back
                            if (start.Month > startDt.Month)
                            {
                                start = new DateTime(start.Year, start.AddMonths(-1).Month, DateTime.DaysInMonth(start.Year, start.AddMonths(-1).Month));
                            }
                            //dates.Add(start);
                        }
                        else
                        {
                            //look in next month
                            //start = new DateTime(start.Year, start.AddMonths(1).Month, dayNumber);
                            start = new DateTime(start.AddMonths(1).Year, start.AddMonths(1).Month, dayNumber);

                            //dates.Add(start);
                        }
                    }

                    //occurence count, or end date...
                    //both of these are gonna be a little different than day/week finders
                    //i need to do some different cleaning of the dates
                    int      monthIncrement = 0;
                    DateTime sourceDate     = start;
                    if (endDt != null)
                    {
                        //int sourceStartDay = sourceDate.Day;
                        while (start <= endDt.Value)
                        {
                            //System.Web.HttpContext.Current.Response.Write("<div>" + skipNumber.ToString() + " : " + skipCounter.ToString() + " - " + start.ToShortDateString() + " - " + endDt.Value.ToShortDateString() + "</div>");
                            if (skipCounter == 0 || skipNumber == 0)
                            {
                                skipCounter++;
                                if (start.Day < this.dayNumber)
                                {
                                    //some sanitation. make sure the day hasn't been pulled back in the case of dates near or at the end of a month
                                    int lastDay = DateTime.DaysInMonth(start.Year, start.Month);
                                    if (lastDay < this.dayNumber)
                                    {
                                        start = new DateTime(start.Year, start.Month, lastDay);
                                    }
                                    else
                                    {
                                        start = new DateTime(start.Year, start.Month, this.dayNumber);
                                    }
                                }
                                dates.Add(start);
                            }
                            else
                            {
                                if (skipCounter == skipNumber)
                                {
                                    skipCounter = 0;
                                }
                                else
                                {
                                    skipCounter++;
                                }
                            }
                            monthIncrement++;
                            //start = start.AddMonths(monthIncrement);
                            start = start.AddMonths(1);
                            //System.Web.HttpContext.Current.Response.Write("<div>" + start.ToShortDateString() + "</div>");
                        }
                    }
                    else
                    {
                        //Occurence limiter section

                        //reset this. just in case.
                        skipCounter = 0;

                        int currentCount = 0;
                        int maxCount     = this.occurNumber;
                        if (maxCount < 1)
                        {
                            maxCount = 1;
                        }
                        if (maxCount > 100)
                        {
                            maxCount = 100;
                        }

                        /*
                         * if (start.Year == 9999) {
                         *      throw new Exception("Start Date is not representable.");
                         * }
                         */

                        while (currentCount < maxCount)
                        {
                            /*
                             * if (start.Year == 9999) {
                             *      throw new Exception("Start Date is not representable. currentCount '" + currentCount.ToString() + "', skipNumber '" + skipNumber.ToString() + "'");
                             * }
                             */
                            if (skipCounter == 0)
                            {
                                if (skipNumber > 0)                                   //this was causing a nearly infinte loop for things occuring every month
                                {
                                    skipCounter++;
                                }
                                if (start.Day < this.dayNumber)
                                {
                                    //some sanitation. make sure the day hasn't been
                                    //pulled back in the case of dates near or at the end of a month
                                    int lastDay = DateTime.DaysInMonth(start.Year, start.Month);
                                    if (lastDay < this.dayNumber)
                                    {
                                        start = new DateTime(start.Year, start.Month, lastDay);
                                        //throw new Exception("Start Date modified. currentCount '" + currentCount.ToString() + "'. new start '" + start.ToString() + "'");
                                    }
                                    else
                                    {
                                        start = new DateTime(start.Year, start.Month, this.dayNumber);
                                        //throw new Exception("Start Date modified. currentCount '" + currentCount.ToString() + "'. new start '" + start.ToString() + "'");
                                    }
                                }
                                dates.Add(start);
                                currentCount++;
                            }
                            else
                            {
                                if (skipCounter == skipNumber)
                                {
                                    skipCounter = 0;
                                }
                                else
                                {
                                    skipCounter++;
                                }
                            }
                            monthIncrement++;                             //wtf do i even use this?

                            start = start.AddMonths(1);
                        }
                    }
                }

                if (this.theNumber > 0)
                {
                    //"repeat monthly every 2nd month on the 2nd Thursday..."

                    //rule: there can only be one named day defined.
                    //so, knowing this, i will start on the 1st of each month, then iterate up by days until i reach the proper counted named day

                    //set up counters
                    //Hashtable dayCounter = new Hashtable();
                    string namedDay        = DayArray[0];
                    int    namedDayCounter = 1;

                    //System.Web.HttpContext.Current.Response.Write("<div>named day  = " + namedDay + "</div>");

                    //start on the first of this current month to see if it has an applicable entry
                    start = new DateTime(start.Year, start.Month, 1);

                    if (endDt != null)
                    {
                        while (start <= endDt.Value)
                        {
                            //System.Web.HttpContext.Current.Response.Write("<div>date = " + start.ToShortDateString() + ", namedDayCounter = " + namedDayCounter.ToString() + "</div>");
                            //System.Web.HttpContext.Current.Response.Write("<div>date eval  = " + start.ToShortDateString() + " - " + start.DayOfWeek.ToString() + "</div>");
                            if (skipCounter == 0 || this.everyNumber == 1)                               //this is the month skipper
                            {
                                string dayOfWeek = start.DayOfWeek.ToString().ToLower();
                                if (namedDay == dayOfWeek)
                                {
                                    if (namedDayCounter == this.theNumber)
                                    {
                                        if (start >= startDt)
                                        {
                                            dates.Add(start);
                                            skipCounter++;
                                        }

                                        namedDayCounter = 1;                                         //reset
                                        //scoot to next month
                                        //i would just make it next month with day 1, but if it's in december.. i need the year to scoot too
                                        start = start.AddMonths(1);
                                        start = new DateTime(start.Year, start.Month, 1);
                                    }
                                    else
                                    {
                                        namedDayCounter++;
                                        start = start.AddDays(1);
                                    }
                                }
                                else
                                {
                                    start = start.AddDays(1);
                                }
                            }
                            else
                            {
                                if (skipCounter == skipNumber)
                                {
                                    skipCounter = 0;
                                }
                                else
                                {
                                    skipCounter++;
                                }
                                //scoot to the first of next month
                                start           = start.AddMonths(1);
                                start           = new DateTime(start.Year, start.Month, 1);
                                namedDayCounter = 1;                                 //reset
                            }
                        }
                    }
                    else
                    {
                        int maxCount     = this.occurNumber;
                        int currentCount = 0;
                        if (maxCount < 1)
                        {
                            maxCount = 1;
                        }
                        if (maxCount > 100)
                        {
                            maxCount = 100;
                        }

                        while (currentCount < maxCount)
                        {
                            //System.Web.HttpContext.Current.Response.Write("<div>date eval  = " + start.ToShortDateString() + " - " + start.DayOfWeek.ToString() + "</div>");
                            if (skipCounter == 0 || this.everyNumber == 1)                               //this is the month skipper
                            {
                                string dayOfWeek = start.DayOfWeek.ToString().ToLower();
                                if (namedDay == dayOfWeek)
                                {
                                    if (namedDayCounter == this.theNumber)
                                    {
                                        if (start >= startDt)
                                        {
                                            dates.Add(start);
                                            skipCounter++;
                                            currentCount++;
                                        }
                                        namedDayCounter = 1;                                         //reset
                                        //scoot to next month
                                        //i would just make it next month with day 1, but if it's in december.. i need the year to scoot too
                                        start = start.AddMonths(1);
                                        start = new DateTime(start.Year, start.Month, 1);
                                    }
                                    else
                                    {
                                        namedDayCounter++;
                                        start = start.AddDays(1);
                                    }
                                }
                                else
                                {
                                    start = start.AddDays(1);
                                }
                            }
                            else
                            {
                                if (skipCounter == skipNumber)
                                {
                                    skipCounter = 0;
                                }
                                else
                                {
                                    skipCounter++;
                                }
                                //scoot to the first of next month
                                start = start.AddMonths(1);
                                start = new DateTime(start.Year, start.Month, 1);
                            }
                        }
                    }
                }
            }

            if (timeUnit == TimeUnit.Yearly)
            {
                /*
                 * "repeat yearly every October 12..."
                 * repeat yearly every(10) day(12) {}
                 *
                 * "repeat yearly every second Thursday of October"
                 * repeat yearly every(10) the(2)[Thursday] {}
                 */
                DateTime start      = this.startDt;
                int      month      = this.everyNumber;
                int      skipNumber = theNumber - 1;
                if (skipNumber < 0)
                {
                    skipNumber = 0;
                }
                int skipCounter = 0;

                if (this.dayNumber > 0)
                {
                    int day = this.dayNumber;

                    //normailize the start date to the intended repeat sequence
                    DateTime realStart = new DateTime(start.Year, month, (day > DateTime.DaysInMonth(start.Year, month) ? DateTime.DaysInMonth(start.Year, month) : day));
                    if (start > realStart)
                    {
                        start = realStart.AddYears(1);
                    }
                    if (start < realStart)
                    {
                        start = realStart;
                    }

                    if (this.endDt != null)
                    {
                        while (start <= this.endDt.Value)
                        {
                            dates.Add(start);
                            start = start.AddYears(1);
                            //do some sanitation. since months like february have variable length year to year
                            if (start.Day < day)
                            {
                                start = new DateTime(start.Year, start.Month, DateTime.DaysInMonth(start.Year, start.Month));
                            }
                        }
                    }
                    else
                    {
                        int maxCount     = this.occurNumber;
                        int currentCount = 0;
                        if (maxCount < 1)
                        {
                            maxCount = 1;
                        }
                        if (maxCount > 100)
                        {
                            maxCount = 100;
                        }

                        while (currentCount < maxCount)
                        {
                            dates.Add(start);
                            start = start.AddYears(1);
                            //do some sanitation. since months like february have variable length year to year
                            if (start.Day < day)
                            {
                                start = new DateTime(start.Year, start.Month, DateTime.DaysInMonth(start.Year, start.Month));
                            }

                            currentCount++;
                        }
                    }
                }

                if (this.theNumber > 0)
                {
                    //the date normalization is a bit different

                    /*	if the year/month is equal to the intended repeat, go to the 1st of the month, iterate forward. see if
                     *      the startDt is before or after.
                     *      if the startDt is before, go with the new date
                     *      if the startDt is after, it's time to scoot to next year to try
                     */
                    /*	if the year/month is greater than the intended repeat, go to next year and start at the first day of that month
                     *      then iterate forward to get the correct day of the week on the correct counter
                     */
                    /*	if the year/month is less than the intended repeat (easiest scenario),
                     *      go to the year/month intended date, on the 1st day of that month
                     *      then do the look for the correct dayOfWeek counter
                     */

                    string namedDay        = DayArray[0];
                    int    namedDayCounter = 1;

                    if (start.Month == month)
                    {
                        start = new DateTime(start.Year, start.Month, 1);
                    }
                    if (start.Month > month)
                    {
                        start = new DateTime(start.AddYears(1).Year, month, 1);
                    }
                    if (start.Month < month)
                    {
                        start = new DateTime(start.Year, month, 1);
                    }



                    if (endDt != null)
                    {
                        while (start <= endDt.Value)
                        {
                            //System.Web.HttpContext.Current.Response.Write("<div>date eval  = " + start.ToShortDateString() + " - " + start.DayOfWeek.ToString() + "</div>");
                            string dayOfWeek = start.DayOfWeek.ToString().ToLower();
                            if (namedDay == dayOfWeek && start > startDt)
                            {
                                if (namedDayCounter == this.theNumber)
                                {
                                    dates.Add(start);
                                    namedDayCounter = 1;                                     //reset
                                    //scoot to next month
                                    //i would just make it next month with day 1, but if it's in december.. i need the year to scoot too
                                    start = start.AddYears(1);
                                    start = new DateTime(start.Year, start.Month, 1);
                                    skipCounter++;
                                }
                                else
                                {
                                    namedDayCounter++;
                                    start = start.AddDays(1);
                                }
                            }
                            else
                            {
                                start = start.AddDays(1);
                            }
                        }
                    }
                    else
                    {
                        int maxCount     = this.occurNumber;
                        int currentCount = 0;
                        if (maxCount < 1)
                        {
                            maxCount = 1;
                        }
                        if (maxCount > 100)
                        {
                            maxCount = 100;
                        }

                        while (currentCount < maxCount)
                        {
                            //System.Web.HttpContext.Current.Response.Write("<div>date eval  = " + start.ToShortDateString() + " - " + start.DayOfWeek.ToString() + "</div>");
                            string dayOfWeek = start.DayOfWeek.ToString().ToLower();
                            if (namedDay == dayOfWeek && start > startDt && start.Month == month)
                            {
                                if (namedDayCounter == this.theNumber)
                                {
                                    dates.Add(start);
                                    namedDayCounter = 1;                                     //reset
                                    //scoot to next year
                                    //i would just make it next month with day 1, but if it's in december.. i need the year to scoot too
                                    start = start.AddYears(1);
                                    start = new DateTime(start.Year, start.Month, 1);
                                    skipCounter++;
                                    currentCount++;
                                }
                                else
                                {
                                    namedDayCounter++;
                                    start = start.AddDays(1);
                                }
                            }
                            else
                            {
                                start = start.AddDays(1);
                            }
                        }
                    }
                }
            }

            return(dates);
        }
Ejemplo n.º 20
0
        public ActionResult Podsumowanie(Dokument dok)
        {
            if (!MusicStore.Models.Module.User.IsAuthenticated) return RedirectToAction("Index", "Home");
            if (MusicStore.Models.Module.User.GetCurrentRole() != MusicStore.Models.Module.User.Klient) return RedirectToAction("Index", "Home");
            DbModule module = DbModule.GetInstance();
            string[] koszyk = Request.Cookies["Cart"].Value.ToString().Split(',');
            var dict = new System.Collections.Generic.Dictionary<int, int>();

            if (!String.IsNullOrEmpty(Request.Cookies["Cart"].Value))
                foreach (string Ids in koszyk)
                {
                    int Id = int.Parse(Ids);
                    if (!dict.ContainsKey(Id))
                    {
                        dict.Add(Id, 1);
                    }
                    else
                    {
                        dict[Id] += 1;
                    }
                }

            var dict2 = new System.Collections.Generic.Dictionary<Album, int>();
            decimal wartosc = 0;
            string waluta = "";
            foreach (var obiekt in dict)
            {
                var album = module.Albumy.Where(x => x.Id == obiekt.Key).First();
                dict2.Add(album, obiekt.Value);
                wartosc += album.BruttoValue * obiekt.Value;

                if (waluta == "")
                {
                    waluta = album.BruttoSymbol;
                }
                else if (waluta != album.BruttoSymbol)
                {
                    waluta = "(Wiele walut)";
                    wartosc = 0;
                }
            }
            ViewBag.wartosc = wartosc;
            ViewBag.waluta = waluta;
            ViewBag.Pozycje = dict2;
            return View(dok);
        }
Ejemplo n.º 21
0
 public static System.Collections.Generic.Dictionary<Guid, string> GetInstalledPlugIns()
 {
   int count = InstalledPlugInCount;
   System.Collections.Generic.Dictionary<Guid, string> plug_in_dictionary = new System.Collections.Generic.Dictionary<Guid, string>(32);
   for (int i = 0; i < count; i++)
   {
     IntPtr name = UnsafeNativeMethods.CRhinoPlugInManager_GetName(i);
     if (name != IntPtr.Zero)
     {
       string sName = Marshal.PtrToStringUni(name);
       if (!string.IsNullOrEmpty(sName))
       {
         Guid id = UnsafeNativeMethods.CRhinoPlugInManager_GetID(i);
         if (id != Guid.Empty && !plug_in_dictionary.ContainsKey(id))
           plug_in_dictionary.Add(id, sName);
       }
     }
   }
   return plug_in_dictionary;
 }
Ejemplo n.º 22
0
            public bool LoadRepDic(string repdicFullPath, string subPath)
            {
                //if (!subPath.Equals("XJU.SpellCheck.Spelling"))
                //    return false;
                try
                {

                    this.fs = new System.IO.FileStream(repdicFullPath, System.IO.FileMode.Open);
                    this.sr = new System.IO.StreamReader(fs, System.Text.Encoding.Default);
                    this.myRepDic = new Dictionary<string, string>();
                    ArrayList al = new ArrayList();
                    string[] inStr;
                    //开始读
                    while (sr.Peek() >= 0)
                    {
                        inStr = sr.ReadLine().Split(new char[] { '\t' });
                        if (!myRepDic.ContainsKey(inStr[0]))
                        {
                            //al.Clear();
                            //al.Add(inStr[1]);
                            try
                            {
                                this.myRepDic.Add(inStr[0], inStr[1]);
                            }
                            catch (Exception err)
                            {
                                //past
                            }
                        }

                    }

                    //清理工作
                    this.sr.Close();
                    this.fs.Close();
                    return true;
                }
                catch (Exception openErr)
                {
                    this.errMessage = openErr.Message;
                    this.myRepDic = null;
                    return false;
                }

            }
Ejemplo n.º 23
0
    //-------------------------------------------------------------------------
    static void addColliderGameObjectsForOTTileMapLayer(Transform layerNode, Component otTileMap, object otTileMapLayer, int layerIndex)
    {
        // read tileMapSize = OTTileMap.mapSize (UnityEngine.Vector2)
        System.Type otTileMapType = otTileMap.GetType();
        FieldInfo   fieldMapSize  = otTileMapType.GetField("mapSize");

        if (fieldMapSize == null)
        {
            Debug.LogError("Detected a missing 'mapSize' member variable at OTTileMap component - Is your Orthello package up to date? 2D ColliderGen might probably not work correctly with this version.");
            return;
        }
        Vector2 tileMapSize   = (UnityEngine.Vector2)fieldMapSize.GetValue(otTileMap);
        int     tileMapWidth  = (int)tileMapSize.x;
        int     tileMapHeight = (int)tileMapSize.y;
        // read mapTileSize = OTTileMap.mapTileSize (UnityEngine.Vector2)
        FieldInfo fieldMapTileSize = otTileMapType.GetField("mapTileSize");

        if (fieldMapTileSize == null)
        {
            Debug.LogError("Detected a missing 'mapTileSize' member variable at OTTileMap component - Is your Orthello package up to date? 2D ColliderGen might probably not work correctly with this version.");
            return;
        }
        Vector2 mapTileSize  = (UnityEngine.Vector2)fieldMapTileSize.GetValue(otTileMap);
        Vector3 mapTileScale = new Vector3(1.0f / tileMapSize.x, 1.0f / tileMapSize.y, 1.0f / tileMapSize.x);

        System.Collections.Generic.Dictionary <int, object> tileSetAtTileIndex = new System.Collections.Generic.Dictionary <int, object>();


        Vector2 bottomLeftTileOffset = new Vector2(-0.5f, -0.5f);

        // read tileIndices = otTileMapLayer.tiles (int[])
        System.Type otTileMapLayerType = otTileMapLayer.GetType();
        FieldInfo   fieldTiles         = otTileMapLayerType.GetField("tiles");

        if (fieldTiles == null)
        {
            Debug.LogError("Detected a missing 'tiles' member variable at OTTileMapLayer component - Is your Orthello package up to date? 2D ColliderGen might probably not work correctly with this version.");
            return;
        }
        int[] tileIndices = (int[])fieldTiles.GetValue(otTileMapLayer);
        System.Collections.Generic.Dictionary <int, Transform> groupNodeForTileIndex = new System.Collections.Generic.Dictionary <int, Transform>();
        Transform tileGroupNode = null;

        object tileSet = null;

        for (int y = 0; y < tileMapHeight; ++y)
        {
            for (int x = 0; x < tileMapWidth; ++x)
            {
                int tileIndex = tileIndices[y * tileMapWidth + x];
                if (tileIndex != 0)
                {
                    if (groupNodeForTileIndex.ContainsKey(tileIndex))
                    {
                        tileGroupNode = groupNodeForTileIndex[tileIndex];
                        tileSet       = tileSetAtTileIndex[tileIndex];
                    }
                    else
                    {
                        // create a group node
                        GameObject newTileGroup = UndoAware.CreateGameObject("Tile Type " + tileIndex);
                        newTileGroup.transform.parent        = layerNode;
                        newTileGroup.transform.localPosition = Vector3.zero;
                        newTileGroup.transform.localScale    = Vector3.one;
                        tileGroupNode = newTileGroup.transform;
                        groupNodeForTileIndex[tileIndex] = tileGroupNode;
                        // get tileset for tile index
                        tileSet = AlphaMeshCollider.GetOTTileSetForTileIndex(otTileMap, tileIndex);
                        tileSetAtTileIndex[tileIndex] = tileSet;
                    }
                    // read tileSet.tileSize (Vector2)
                    System.Type otTileSetType = tileSet.GetType();
                    FieldInfo   fieldTileSize = otTileSetType.GetField("tileSize");
                    if (fieldTileSize == null)
                    {
                        Debug.LogError("Detected a missing 'tileSize' member variable at OTTileSet class - Is your Orthello package up to date? 2D ColliderGen might probably not work correctly with this version.");
                        return;
                    }
                    Vector2 tileSize         = (UnityEngine.Vector2)fieldTileSize.GetValue(tileSet);
                    Vector3 tileScale        = new Vector3(mapTileScale.x / mapTileSize.x * tileSize.x, mapTileScale.y / mapTileSize.y * tileSize.y, mapTileScale.z);
                    Vector2 tileCenterOffset = new Vector3(tileScale.x * 0.5f, tileScale.x * 0.5f);

                    // add a GameObject for each enabled tile with name "tile y x"
                    GameObject alphaMeshColliderNode = UndoAware.CreateGameObject("tile " + y + " " + x);
                    alphaMeshColliderNode.transform.parent = tileGroupNode;
                    AlphaMeshCollider alphaMeshColliderComponent = UndoAware.AddComponent <AlphaMeshCollider>(alphaMeshColliderNode);
                    alphaMeshColliderComponent.SetOTTileMap(otTileMap, layerIndex, x, y, tileMapWidth);

                    // set the position of the tile collider according to its (x,y) pos in the map.
                    alphaMeshColliderNode.transform.localPosition = new Vector3(x * mapTileScale.x + bottomLeftTileOffset.x + tileCenterOffset.x, (tileMapSize.y - 1 - y) * mapTileScale.y + bottomLeftTileOffset.y + tileCenterOffset.y, 0.0f);
                    alphaMeshColliderNode.transform.localScale    = tileScale;
                }
            }
        }
    }
Ejemplo n.º 24
0
        List<List<List<SubCalendarEvent>>> BuildAllPossibleSnugLists(List<CalendarEvent> SortedInterferringCalendarEvents, CalendarEvent ToBeFittedTimeLine, Dictionary<CalendarEvent, List<SubCalendarEvent>> DictionaryWithBothCalendarEventsAndListOfInterferringSubEvents, TimeLine ReferenceTimeLine, double Occupancy)
        {
            /*Name: Jerome Biotidara
             *Description: Function starts by Including all Rigid interferring schedules. Then goes on to setup tightest schedule.
             *Accomplished by:
             *1. stacking subevents of the same calendar event right next to each other.
             *2. Start Snugallotments based on deadline of Calendar Events
             *3. Try creating a snugness that has a snugness duration Greater than or Equal to start time and less than Or equal to the result generated by the difference between the CalendarEvent Deadline and Sum of Interferring subevent durations
             *4  Ensure that when you are assign subcalendar events, the sub calendar events that start within the timeline get noticed and are only allowed to start within the range
             */



            //TimeLine[] JustFreeSpots = ToBeFittedTimeLine.EventTimeLine.getAllFreeSlots();
            TimeLine[] JustFreeSpots = getAllFreeSpots_NoCompleteSchedule(ReferenceTimeLine);
            List<SubCalendarEvent>[] MyListOfSubCalendarEvents = DictionaryWithBothCalendarEventsAndListOfInterferringSubEvents.Values.ToArray();
            //TimeLine[] FreeSpotsWithOnlyRigids= ToBeFittedTimeLine.EventTimeLine.getAllFreeSlots();
            TimeLine[] FreeSpotsWithOnlyRigids = getAllFreeSpots_NoCompleteSchedule(ReferenceTimeLine);
            List<SubCalendarEvent> ListOfAllInterferringSubCalendarEvents = new List<SubCalendarEvent>();
            List<TimeSpan> ListOfAllInterferringTimeSpans = new List<TimeSpan>();

            foreach (List<SubCalendarEvent> MyList in MyListOfSubCalendarEvents)//Loop creates a List of interferring SubCalendarEvens
            {
                foreach (SubCalendarEvent MySubEvents in MyList)
                {
                    ListOfAllInterferringSubCalendarEvents.Add(MySubEvents);
                    ListOfAllInterferringTimeSpans.Add(MySubEvents.ActiveSlot.BusyTimeSpan);
                }
            }


            List<SubCalendarEvent> ListOfAlreadyAssignedSubCalendarEvents = new System.Collections.Generic.List<SubCalendarEvent>();

            /*foreach (BusyTimeLine MyBusySlot in ReferenceTimeLine.OccupiedSlots)
            {
                SubCalendarEvent MySubCalendarEvent = getSubCalendarEvent(MyBusySlot.TimeLineID);
                if (MySubCalendarEvent != null)
                {
                    ListOfAlreadyAssignedSubCalendarEvents.Add(MySubCalendarEvent);
                }
            }

            ListOfAllInterferringSubCalendarEvents = Utility.NotInList(ListOfAllInterferringSubCalendarEvents, ListOfAlreadyAssignedSubCalendarEvents);*/

            Dictionary<TimeLine, List<CalendarEvent>> DictionaryOfFreeTimeLineAndPertinentCalendarEventList = new System.Collections.Generic.Dictionary<TimeLine, System.Collections.Generic.List<CalendarEvent>>();

            Dictionary<TimeLine, Dictionary<CalendarEvent, List<SubCalendarEvent>>> DictionaryOfFreeTimeLineAndDictionaryOfCalendarEventAndListOfSubCalendarEvent = new System.Collections.Generic.Dictionary<TimeLine, System.Collections.Generic.Dictionary<CalendarEvent, System.Collections.Generic.List<SubCalendarEvent>>>();



            foreach (TimeLine MyFreeTimeLine in JustFreeSpots)
            {
                CalendarEvent[] MyListOfPertinentCalendarEventsForMyTimeLine = getPertinentCalendarEvents(SortedInterferringCalendarEvents.ToArray(), MyFreeTimeLine);
                Dictionary<CalendarEvent, List<SubCalendarEvent>> MyDictionaryOfCalendarEventAndPertinentSubCalendarEvent = new System.Collections.Generic.Dictionary<CalendarEvent, System.Collections.Generic.List<SubCalendarEvent>>();
                foreach (CalendarEvent MyCalendarEvent in MyListOfPertinentCalendarEventsForMyTimeLine)
                {
                    List<SubCalendarEvent> MyListwe = DictionaryWithBothCalendarEventsAndListOfInterferringSubEvents[MyCalendarEvent];
                    MyDictionaryOfCalendarEventAndPertinentSubCalendarEvent.Add(MyCalendarEvent, MyListwe);
                }
                DictionaryOfFreeTimeLineAndDictionaryOfCalendarEventAndListOfSubCalendarEvent.Add(MyFreeTimeLine, MyDictionaryOfCalendarEventAndPertinentSubCalendarEvent);
                DictionaryOfFreeTimeLineAndPertinentCalendarEventList.Add(MyFreeTimeLine, MyListOfPertinentCalendarEventsForMyTimeLine.ToList());//Next step is to call the snug array. Note: you will need to ensure that when ever a subevent gets used in a free timeline. It will have to be removed from the List so that it cannot be used in another free timeline. Also you need to create every possible permutation. Take for example a calendar event thats pertinent to two different "free timelines". you need to ensure that you have different calls to the snuglist generator that has the calendar event enabled in one and disabled in the other.
            }


            List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> EmptyIntialListOfSubCalendarEvemts = new List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>();

            for (int i = 0; i < JustFreeSpots.Length; i++)
            {
                EmptyIntialListOfSubCalendarEvemts.Add(new System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>());
            }



            Tuple<List<TimeSpanWithStringID>, List<mTuple<bool, SubCalendarEvent>>> Arg14 = ConvertSubCalendarEventToTimeSpanWitStringID(ListOfAllInterferringSubCalendarEvents);

            List<TimeSpanWithStringID> SubCalEventsAsTimeSpanWithStringID = Arg14.Item1;//ListOfAllInterferringSubCalendarEvents as TimeSpanWithStringID
            List<mTuple<bool, SubCalendarEvent>> Arg15 = Arg14.Item2;

            Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> Dict_StringTickAndCount = new System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>();
            Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> Dict_StringTickAndCount_Cpy = new System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>();

            foreach (TimeSpanWithStringID eachTimeSpanWithStringID in SubCalEventsAsTimeSpanWithStringID)
            {
                if (Dict_StringTickAndCount.ContainsKey(eachTimeSpanWithStringID.timeSpan))
                {
                    ++Dict_StringTickAndCount[eachTimeSpanWithStringID.timeSpan].Item1;
                    ++Dict_StringTickAndCount_Cpy[eachTimeSpanWithStringID.timeSpan].Item1;
                }
                else
                {
                    Dict_StringTickAndCount.Add(eachTimeSpanWithStringID.timeSpan, new mTuple<int, TimeSpanWithStringID>(1, eachTimeSpanWithStringID));
                    Dict_StringTickAndCount_Cpy.Add(eachTimeSpanWithStringID.timeSpan, new mTuple<int, TimeSpanWithStringID>(1, eachTimeSpanWithStringID));
                }
            }


            Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> TotalSum = new Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>();

            TotalSum = SnugArray.CreateCopyOFSnuPossibilities(Dict_StringTickAndCount_Cpy);

            InterferringTimeSpanWithStringID_Cpy = Dict_StringTickAndCount_Cpy;//hack to keep track of available events


            Dictionary<TimeLine, List<mTuple<bool, SubCalendarEvent>>> Dict_TimeLine_ListOfSubCalendarEvent = BuildDicitionaryOfTimeLineAndSubcalendarEvents(Arg15, DictionaryOfFreeTimeLineAndDictionaryOfCalendarEventAndListOfSubCalendarEvent, ToBeFittedTimeLine);

            Dictionary<TimeLine, List<mTuple<bool, SubCalendarEvent>>> Dict_ConstrainedList = generateConstrainedList(JustFreeSpots.ToList(), Arg15);

            Dictionary<TimeLine, List<mTuple<int, TimeSpanWithStringID>>> Dict_TimeLine_ListOfmTuple = new System.Collections.Generic.Dictionary<TimeLine, System.Collections.Generic.List<mTuple<int, TimeSpanWithStringID>>>();

            Dictionary<TimeLine, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> Dict_TimeLine_Dict_string_mTple = new System.Collections.Generic.Dictionary<TimeLine, System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>();

            Dictionary<TimeLine, Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>>> Dict_TimeLine_Dict_StringID_Dict_SubEventStringID_mTuple_Bool_MatchinfSubCalevents = new Dictionary<TimeLine, Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>>>();

            Dictionary<TimeLine, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> Dict_TimeLine_Dict_string_mTple_Constrained = new Dictionary<TimeLine, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>();

            foreach (TimeLine eachTimeLine in Dict_TimeLine_ListOfSubCalendarEvent.Keys)
            {
                List<mTuple<bool, SubCalendarEvent>> LisOfSubCalEvent = Dict_TimeLine_ListOfSubCalendarEvent[eachTimeLine];
                Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> myDict = new System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>();
                Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>> myDict0 = new Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>>();


                foreach (mTuple<bool, SubCalendarEvent> eachmTuple in LisOfSubCalEvent)//goes Through each Subcalevent in Each timeline and generates a dict for a TimeTick To List of TimeSpanID
                {
                    if (myDict.ContainsKey(eachmTuple.Item2.ActiveDuration))
                    {
                        ++myDict[eachmTuple.Item2.ActiveDuration].Item1;
                    }
                    else
                    {
                        myDict.Add(eachmTuple.Item2.ActiveDuration, new mTuple<int, TimeSpanWithStringID>(1, new TimeSpanWithStringID(eachmTuple.Item2.ActiveDuration, eachmTuple.Item2.ActiveDuration.Ticks.ToString())));

                    }



                    if (myDict0.ContainsKey(eachmTuple.Item2.ActiveDuration))
                    {


                        myDict0[eachmTuple.Item2.ActiveDuration].Add(eachmTuple.Item2.ID, eachmTuple);
                    }
                    else
                    {
                        Dictionary<string, mTuple<bool, SubCalendarEvent>> var17 = new System.Collections.Generic.Dictionary<string, mTuple<bool, SubCalendarEvent>>();
                        var17.Add(eachmTuple.Item2.ID, eachmTuple);
                        myDict0.Add(eachmTuple.Item2.ActiveDuration, var17);
                    }

                }
                Dict_TimeLine_Dict_string_mTple.Add(eachTimeLine, myDict);
                Dict_TimeLine_Dict_StringID_Dict_SubEventStringID_mTuple_Bool_MatchinfSubCalevents.Add(eachTimeLine, myDict0);
            }


            foreach (TimeLine eachTimeLine in Dict_ConstrainedList.Keys)
            {
                List<mTuple<bool, SubCalendarEvent>> LisOfSubCalEvent = Dict_ConstrainedList[eachTimeLine];
                Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> myDict = new System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>();
                foreach (mTuple<bool, SubCalendarEvent> eachmTuple in LisOfSubCalEvent)//goes Through each Subcalevent in Each timeline and generates a dict for a TimeTick To List of TimeSpanID
                {
                    if (myDict.ContainsKey(eachmTuple.Item2.ActiveDuration))
                    {
                        ++myDict[eachmTuple.Item2.ActiveDuration].Item1;
                    }
                    else
                    {
                        myDict.Add(eachmTuple.Item2.ActiveDuration, new mTuple<int, TimeSpanWithStringID>(1, new TimeSpanWithStringID(eachmTuple.Item2.ActiveDuration, eachmTuple.Item2.ActiveDuration.Ticks.ToString())));
                    }
                }

                Dict_TimeLine_Dict_string_mTple_Constrained.Add(eachTimeLine, myDict);
            }

            /*
            foreach (TimeLine eachTimeLine in Dict_TimeLine_Dict_string_mTple.Keys)
            {
                Dictionary<string, mTuple<int, TimeSpanWithStringID>> stringMtuple = Dict_TimeLine_Dict_string_mTple[eachTimeLine];
                List<mTuple<int, TimeSpanWithStringID>> List_mTuple = new System.Collections.Generic.List<mTuple<int, TimeSpanWithStringID>>();

                foreach (KeyValuePair<string, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair in stringMtuple)
                {
                    TimeSpanWithStringID myTimeSpanWithStringID = eachKeyValuePair.Value.Item2;
                    List_mTuple.Add(new mTuple<int, TimeSpanWithStringID>(eachKeyValuePair.Value.Item1, myTimeSpanWithStringID));
                }

                Dict_TimeLine_ListOfmTuple.Add(eachTimeLine, List_mTuple);
            }

            */


            Dictionary<TimeLine, Tuple<Dictionary<string, mTuple<int, TimeSpanWithStringID>>, Dictionary<string, mTuple<int, TimeSpanWithStringID>>>> var6 = new System.Collections.Generic.Dictionary<TimeLine, Tuple<System.Collections.Generic.Dictionary<string, mTuple<int, TimeSpanWithStringID>>, System.Collections.Generic.Dictionary<string, mTuple<int, TimeSpanWithStringID>>>>();

            //Dictionary<TimeLine, Dictionary<string, mTuple<int, TimeSpanWithStringID>>>
            int i0 = 0;
            List<TimeLine> var7 = Dict_TimeLine_Dict_string_mTple_Constrained.Keys.ToList();//List Of TimeLines pertaining to COnstrained List i.e restricted elements
            Dictionary<string, mTuple<int, TimeSpanWithStringID>> var10 = new System.Collections.Generic.Dictionary<string, mTuple<int, TimeSpanWithStringID>>();
            List<KeyValuePair<TimeLine, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>> var11 = Dict_TimeLine_Dict_string_mTple_Constrained.ToList(); //Same as Dict_TimeLine_Dict_string_mTple_Constrained only as List of KeyValuePair
            Dictionary<TimeLine, Dictionary<string, mTuple<int, TimeSpanWithStringID>>> var14 = new System.Collections.Generic.Dictionary<TimeLine, System.Collections.Generic.Dictionary<string, mTuple<int, TimeSpanWithStringID>>>();
            Dictionary<TimeLine, Tuple<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>> var15 = new Dictionary<TimeLine, Tuple<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>>();

            foreach (KeyValuePair<TimeLine, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> eachKeyValuePair in Dict_TimeLine_Dict_string_mTple_Constrained)
            {
                i0 = var7.IndexOf(eachKeyValuePair.Key);
                Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> var8 = eachKeyValuePair.Value;
                Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> var9 = new System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>();
                for (; i0 < var7.Count; i0++)
                {
                    Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> var12 = var11[i0].Value;
                    foreach (KeyValuePair<TimeSpan, mTuple<int, TimeSpanWithStringID>> var13 in var12)
                    {
                        if (var9.ContainsKey(var13.Key))
                        {
                            var9[var13.Key].Item1 += var13.Value.Item1;
                        }
                        else
                        {
                            var9.Add(var13.Key, new mTuple<int, TimeSpanWithStringID>(var13.Value.Item1, var13.Value.Item2));
                        }
                    }
                }
                var15.Add(eachKeyValuePair.Key, new Tuple<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>(eachKeyValuePair.Value, var9));
            }



            List<List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>> AllTImeLinesWithSnugPossibilities = generateTreeCallsToSnugArray(Dict_StringTickAndCount, JustFreeSpots.ToList(), 0, EmptyIntialListOfSubCalendarEvemts, Dict_TimeLine_Dict_string_mTple, var15);




            List<List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>> validMatches = getValidMatches(ListOfAllInterferringSubCalendarEvents, AllTImeLinesWithSnugPossibilities, Dict_TimeLine_Dict_string_mTple_Constrained);

            List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> AverageMatched = getAveragedOutTIimeLine(validMatches, 0);



            Dictionary<TimeLine, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> AveragedMatchAsDictWithTimeLine = new Dictionary<TimeLine, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>();

            i0 = 0;
            for (; i0 < JustFreeSpots.Length; i0++)
            {
                AveragedMatchAsDictWithTimeLine.Add(JustFreeSpots[i0], AverageMatched[i0]);
                //TotalSum[0] = SnugArray.AddToSnugPossibilityList(TotalSum[0], AverageMatched[i0]);
            }



            Dict_ConstrainedList = stitchRestrictedSubCalendarEvent(JustFreeSpots.ToList(), 0, Dict_ConstrainedList);

            Dictionary<TimeLine, List<mTuple<bool, SubCalendarEvent>>> Dict_TimeLine_ListOfSubCalendarEvent_Cpy = new System.Collections.Generic.Dictionary<TimeLine, System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>>(Dict_TimeLine_ListOfSubCalendarEvent);

            Dictionary<TimeLine, List<mTuple<bool, SubCalendarEvent>>> DictWithTimeLine_ArrangedOptimizedSubCalEvents = new System.Collections.Generic.Dictionary<TimeLine, System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>>()
;
            i0 = 0;
            List<mTuple<bool, SubCalendarEvent>> TotalArrangedElements = new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>();
            List<List<SubCalendarEvent>> TotalArrangedElements_NoMTuple = new System.Collections.Generic.List<System.Collections.Generic.List<SubCalendarEvent>>();
            List<TimeLine> ListOfTimeLines = JustFreeSpots.ToList();//This will be decremented so do not reused

            Dictionary<string, SubCalendarEvent> TestDict = new System.Collections.Generic.Dictionary<string, SubCalendarEvent>();

            List<List<SubCalendarEvent>> restrictedSubCaleventsAfterScheduleUpdate = new List<List<SubCalendarEvent>>();
            Dictionary<TimeLine, Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>>> copyOfPossibleEvents = createCopyOfPossibleEvents(Dict_TimeLine_Dict_StringID_Dict_SubEventStringID_mTuple_Bool_MatchinfSubCalevents);

            

            foreach (KeyValuePair<TimeLine, Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>>> eachKeyValuePair in Dict_TimeLine_Dict_StringID_Dict_SubEventStringID_mTuple_Bool_MatchinfSubCalevents)
            {
                List<mTuple<bool, SubCalendarEvent>> var16 = Dict_ConstrainedList[eachKeyValuePair.Key];
                List<BusyTimeLine> RestrictedBusySlots = new System.Collections.Generic.List<BusyTimeLine>();
                foreach (mTuple<bool, SubCalendarEvent> eachmTuple in var16)
                {
                    eachmTuple.Item1 = true;
                    RestrictedBusySlots.Add(eachmTuple.Item2.ActiveSlot);
                    TimeSpan ActiveTimespan1 = eachmTuple.Item2.ActiveDuration;
                    string SubEventID = eachmTuple.Item2.ID;
                    eachKeyValuePair.Value[ActiveTimespan1][SubEventID] = eachmTuple;
                }
                eachKeyValuePair.Key.AddBusySlots(RestrictedBusySlots.ToArray());
                if (i0 == 3|| i0 == 12)
                {
                    ;
                }



                List<mTuple<bool, SubCalendarEvent>> ArrangedElements = stitchUnRestrictedSubCalendarEvent(eachKeyValuePair.Key, var16, Dict_TimeLine_Dict_StringID_Dict_SubEventStringID_mTuple_Bool_MatchinfSubCalevents[eachKeyValuePair.Key], AverageMatched[i0],Occupancy);
                foreach (TimeLine eachTimeLine in JustFreeSpots)
                {
                    foreach (mTuple<bool, SubCalendarEvent> eachmTuple in ArrangedElements)
                    {
                        TimeSpan ActiveTimeSpan0 = eachmTuple.Item2.ActiveDuration;
                        if (Dict_TimeLine_Dict_StringID_Dict_SubEventStringID_mTuple_Bool_MatchinfSubCalevents[eachTimeLine].ContainsKey(ActiveTimeSpan0))
                        {
                            Dict_TimeLine_Dict_StringID_Dict_SubEventStringID_mTuple_Bool_MatchinfSubCalevents[eachTimeLine][ActiveTimeSpan0].Remove(eachmTuple.Item2.ID);
                        }
                    }
                }
                /*
                if (i0 + 1 < Dict_TimeLine_Dict_StringID_Dict_SubEventStringID_mTuple_Bool_MatchinfSubCalevents.Count)
                {
                    Dictionary<TimeLine, Dictionary<string, Dictionary<string, mTuple<bool, SubCalendarEvent>>>> test = Dict_TimeLine_Dict_StringID_Dict_SubEventStringID_mTuple_Bool_MatchinfSubCalevents;
                    ArrangedElements = FurtherFillTimeLineWithSubCalEvents(ArrangedElements, JustFreeSpots[i0 + 1], AveragedMatchAsDictWithTimeLine, eachKeyValuePair.Key, test);
                    foreach (KeyValuePair<string, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair0 in AveragedMatchAsDictWithTimeLine[eachKeyValuePair.Key])
                    {
                        if (AveragedMatchAsDictWithTimeLine[JustFreeSpots[i0 + 1]].ContainsKey(eachKeyValuePair0.Key))
                        {
                            AveragedMatchAsDictWithTimeLine[JustFreeSpots[i0 + 1]][eachKeyValuePair0.Key].Item1 += eachKeyValuePair0.Value.Item1;
                        }
                        else
                        {
                            AveragedMatchAsDictWithTimeLine[JustFreeSpots[i0 + 1]].Add(eachKeyValuePair0.Key, new mTuple<int, TimeSpanWithStringID>(eachKeyValuePair0.Value));
                        }
                    }

                }*/
                foreach (TimeLine eachTimeLine in JustFreeSpots)
                {
                    foreach (mTuple<bool, SubCalendarEvent> eachmTuple in ArrangedElements)
                    {


                        TimeSpan ActiveTimeSpan2 = eachmTuple.Item2.ActiveDuration;
                        if (Dict_TimeLine_Dict_StringID_Dict_SubEventStringID_mTuple_Bool_MatchinfSubCalevents[eachTimeLine].ContainsKey(ActiveTimeSpan2))
                        {
                            Dict_TimeLine_Dict_StringID_Dict_SubEventStringID_mTuple_Bool_MatchinfSubCalevents[eachTimeLine][ActiveTimeSpan2].Remove(eachmTuple.Item2.ID);
                        }
                    }
                }



                TotalArrangedElements_NoMTuple.Add(Utility.mTupleToSubCalEvents(ArrangedElements));
                List<mTuple<bool, SubCalendarEvent>> previous = TotalArrangedElements.ToList();
                int BeforeErrorIndex = TotalArrangedElements.Count;
                TotalArrangedElements.AddRange(ArrangedElements);
                int AfterErrorIndex = TotalArrangedElements.Count;
                DictWithTimeLine_ArrangedOptimizedSubCalEvents.Add(eachKeyValuePair.Key, ArrangedElements);
                Dict_TimeLine_ListOfSubCalendarEvent_Cpy.Remove(eachKeyValuePair.Key);





                foreach (List<mTuple<bool, SubCalendarEvent>> eachList in Dict_TimeLine_ListOfSubCalendarEvent_Cpy.Values)
                {
                    int i = 0;
                    for (; i < eachList.Count; i++)
                    {
                        /*if (eachList[i].Item1)
                        {
                            eachList.RemoveAt(i);
                            --i;
                        }*/

                        foreach (mTuple<bool, SubCalendarEvent> eachmTuple in ArrangedElements)
                        {
                            if (eachList[i].Item2.ID == eachmTuple.Item2.ID)
                            {
                                eachList.RemoveAt(i);
                                --i;
                                break;
                            }


                        }


                    }
                }

                if (Dict_ConstrainedList.Count == 2)
                {
                    ;
                }



                List<SubCalendarEvent> UnassignedSubevents = ListOfAllInterferringSubCalendarEvents.ToList();
                List<SubCalendarEvent> AlreadyAssigned = Utility.mTupleToSubCalEvents(TotalArrangedElements);

                
                foreach (SubCalendarEvent eachSubCalendarEvent in AlreadyAssigned)
                {
                    if (eachSubCalendarEvent.ID == "470_482")
                    {
                        ;
                    }
                    TestDict.Add(eachSubCalendarEvent.ID, eachSubCalendarEvent);//if it crashes at this point there is some possible error in your constrained list generating duplicate values. 
                }
                TestDict = new System.Collections.Generic.Dictionary<string, SubCalendarEvent>();
                /*
                UnassignedSubevents=Utility.NotInList(UnassignedSubevents, AlreadyAssigned);
                */
                List<string> MyAssignedIDs = AlreadyAssigned.Select(obj => obj.ID).ToList();

                UnassignedSubevents.RemoveAll(e => MyAssignedIDs.Contains(e.ID));
                int StartIndex = 0;
                if (Dict_ConstrainedList.Count > 1)
                {
                    restrictedSubCaleventsAfterScheduleUpdate.Add(Utility.mTupleToSubCalEvents(Dict_ConstrainedList[ListOfTimeLines[0]]));
                    StartIndex = i0 + 1;
                    ListOfTimeLines.RemoveAt(0);

                    Dict_ConstrainedList = generateConstrainedList(ListOfTimeLines, Utility.SubCalEventsTomTuple(UnassignedSubevents, false));

                    TimeLine PertinentTimeLine=Dict_TimeLine_ListOfSubCalendarEvent_Cpy.Keys.ToList()[0];
                    List<mTuple<bool, SubCalendarEvent>> beforeList = Dict_ConstrainedList[PertinentTimeLine];
                    int before = Dict_ConstrainedList[PertinentTimeLine].Count;
                    
                    Dict_ConstrainedList[PertinentTimeLine] = stitchRestrictedSubCalendarEvent(Dict_ConstrainedList[PertinentTimeLine], PertinentTimeLine);
                    int after = Dict_ConstrainedList[PertinentTimeLine].Count;
                    List<mTuple<bool, SubCalendarEvent>> AfterList = Dict_ConstrainedList[PertinentTimeLine];
                    if (after != before)
                    {
                        ;
                    }
                    //Dict_ConstrainedList = stitchRestrictedSubCalendarEvent(Dict_TimeLine_ListOfSubCalendarEvent_Cpy.Keys.ToList(), 0, Dict_ConstrainedList);
                }
                i0++;
            }


            TimeSpan TotalBusyTimeFrame = Utility.SumOfActiveDuration(ListOfAllInterferringSubCalendarEvents);
            foreach(BusyTimeLine OccupiedSlot in ReferenceTimeLine.OccupiedSlots)
            {
                TotalBusyTimeFrame+=OccupiedSlot.BusyTimeSpan;
            }
            
            TimeSpan TotalTimeSpan = ReferenceTimeLine.TimelineSpan;


            double PercentageOfOccupiedSpace = (double)TotalBusyTimeFrame.Ticks / (double)TotalTimeSpan.Ticks;


            restrictedSubCaleventsAfterScheduleUpdate.Add(Utility.mTupleToSubCalEvents(Dict_ConstrainedList[ListOfTimeLines[0]]));//updates the constrained List one last time

            TotalArrangedElements_NoMTuple=SpreadOutEvents(TotalArrangedElements_NoMTuple, PercentageOfOccupiedSpace, JustFreeSpots.ToList(), copyOfPossibleEvents, restrictedSubCaleventsAfterScheduleUpdate);




            
            List<List<List<SubCalendarEvent>>> ReValue = new System.Collections.Generic.List<System.Collections.Generic.List<System.Collections.Generic.List<SubCalendarEvent>>>();
            //List<List<List<SubCalendarEvent>>> ReValue = FixSubCalEventOrder(AllTImeLinesWithSnugPossibilities, JustFreeSpots);
            ReValue.Add(TotalArrangedElements_NoMTuple);

            return ReValue;
        }
Ejemplo n.º 25
0
        public bool ProcessTVDBResponse(Stream str, int?codeHint)
        {
            // Will have one or more series, and episodes
            // all wrapped in <Data> </Data>

            // e.g.:
            //<Data>
            // <Series>
            //  <id>...</id>
            //  etc.
            // </Series>
            // <Episode>
            //  <id>...</id>
            //  blah blah
            // </Episode>
            // <Episode>
            //  <id>...</id>
            //  blah blah
            // </Episode>
            // ...
            //</Data>

            if (!this.GetLock("ProcessTVDBResponse"))
            {
                return(false);
            }

            try
            {
                XmlReaderSettings settings = new XmlReaderSettings
                {
                    IgnoreComments   = true,
                    IgnoreWhitespace = true
                };
                XmlReader r = XmlReader.Create(str, settings);

                r.Read();

                while (!r.EOF)
                {
                    if ((r.Name == "Data") && !r.IsStartElement())
                    {
                        break; // that's it.
                    }
                    if (r.Name == "Series")
                    {
                        // The <series> returned by GetSeries have
                        // less info than other results from
                        // thetvdb.com, so we need to smartly merge
                        // in a <Series> if we already have some/all
                        // info on it (depending on which one came
                        // first).

                        SeriesInfo si = new SeriesInfo(r.ReadSubtree());
                        if (this.Series.ContainsKey(si.TVDBCode))
                        {
                            this.Series[si.TVDBCode].Merge(si, this.RequestLanguage);
                        }
                        else
                        {
                            this.Series[si.TVDBCode] = si;
                        }
                        r.Read();
                    }
                    else if (r.Name == "Episode")
                    {
                        Episode e = new Episode(null, null, r.ReadSubtree(), Args);
                        if (e.OK())
                        {
                            if (!this.Series.ContainsKey(e.SeriesID))
                            {
                                throw new TVDBException("Can't find the series to add the episode to (TheTVDB).");
                            }
                            SeriesInfo ser  = this.Series[e.SeriesID];
                            Season     seas = ser.GetOrAddSeason(e.ReadSeasonNum, e.SeasonID);

                            bool added = false;
                            for (int i = 0; i < seas.Episodes.Count; i++)
                            {
                                Episode ep = seas.Episodes[i];
                                if (ep.EpisodeID == e.EpisodeID)
                                {
                                    seas.Episodes[i] = e;
                                    added            = true;
                                    break;
                                }
                            }
                            if (!added)
                            {
                                seas.Episodes.Add(e);
                            }
                            e.SetSeriesSeason(ser, seas);
                        }
                        r.Read();
                    }
                    else if (r.Name == "xml")
                    {
                        r.Read();
                    }
                    else if (r.Name == "Data")
                    {
                        string time = r.GetAttribute("time");
                        if (time != null)
                        {
                            this.New_Srv_Time = int.Parse(time);
                        }
                        r.Read();
                    }
                    else
                    {
                        r.ReadOuterXml();
                    }
                }
            }
            catch (XmlException e)
            {
                if (!this.Args.Unattended)
                {
                    string message = "Error processing data from TheTVDB (top level).";
                    message += "\r\n" + e.Message;
                    String name = "";
                    if (codeHint.HasValue && Series.ContainsKey(codeHint.Value))
                    {
                        name += "Show \"" + Series[codeHint.Value].Name + "\" ";
                    }
                    if (codeHint.HasValue)
                    {
                        name += "ID #" + codeHint.Value + " ";
                    }
                    MessageBox.Show(name + message, "TVRename", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    // throw new TVDBException(e.Message);
                }
                return(false);
            }
            finally
            {
                this.Unlock("ProcessTVDBResponse");
            }
            return(true);
        }
Ejemplo n.º 26
0
        List<mTuple<bool, SubCalendarEvent>> FurtherFillTimeLineWithSubCalEvents(List<mTuple<bool, SubCalendarEvent>> AllReadyAssignedSubCalEvents, TimeLine ReferenceTimeLine, Dictionary<TimeLine, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> AllCompatibleWithList, TimeLine PreceedingTimeLine, Dictionary<TimeLine, Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>>> PossibleEntries)
        {
            /*
             * CompatibleWithList has whats left after stitchUnRestrictedSubCalendarEvent has removed all possible fittable Events
             * Hack Alert: The current implementation does not optimize for restricted values
             */

            List<SubCalendarEvent> AssignedSubCalendarEvents = new System.Collections.Generic.List<SubCalendarEvent>();
            foreach (mTuple<bool, SubCalendarEvent> eachmTuple in AllReadyAssignedSubCalEvents)
            {
                AssignedSubCalendarEvents.Add(eachmTuple.Item2);
            }


            List<TimeSpanWithStringID> LeftOvers = new System.Collections.Generic.List<TimeSpanWithStringID>();

            foreach (KeyValuePair<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair in AllCompatibleWithList[PreceedingTimeLine])
            {
                if (eachKeyValuePair.Value.Item1 > 0)
                {
                    LeftOvers.Add(eachKeyValuePair.Value.Item2);
                }
            }

            PreceedingTimeLine.Empty();
            TimeLine UpdatedTImeLine = Utility.AddSubCaleventsToTimeLine(PreceedingTimeLine, AssignedSubCalendarEvents);
            PreceedingTimeLine.AddBusySlots(UpdatedTImeLine.OccupiedSlots);

            List<TimeLine> AllFreeSpots = PreceedingTimeLine.getAllFreeSlots().ToList();
            Dictionary<TimeLine, List<mTuple<bool, SubCalendarEvent>>> matchingValidSubcalendarEvents = new System.Collections.Generic.Dictionary<TimeLine, System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>>();//Dictionary contains a match up of the free within already assigned variables and possible fillers
            Dictionary<TimeLine, Dictionary<string, mTuple<int, TimeSpanWithStringID>>> ForSnugArray = new System.Collections.Generic.Dictionary<TimeLine, System.Collections.Generic.Dictionary<string, mTuple<int, TimeSpanWithStringID>>>();
            Dictionary<TimeLine, SnugArray> FreeSpotSnugArrays = new System.Collections.Generic.Dictionary<TimeLine, SnugArray>();
            Dictionary<TimeLine, List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>> FreeSpotSnugPossibiilities = new System.Collections.Generic.Dictionary<TimeLine, System.Collections.Generic.List<System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>>();
            //Dictionary<TimeLine, List<TimeSpanWithStringID>> FreeSpotSnugPossibilities = new System.Collections.Generic.Dictionary<TimeLine, SnugArray>();
            Dictionary<string, SubCalendarEvent> AllMovableSubCalEvents = new System.Collections.Generic.Dictionary<string, SubCalendarEvent>();
            List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> AllMoveOvrSet = new System.Collections.Generic.List<System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>();
            // Dictionary<string, Dictionary<SubCalendarEvent, List<TimeLine>>> SubEventToMatchingTimeLinePossible = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<SubCalendarEvent, System.Collections.Generic.List<TimeLine>>>();
            Dictionary<TimeLine, Dictionary<TimeSpan, List<mTuple<bool, SubCalendarEvent>>>> TimeLine_WithMathChingSubCalevents = new Dictionary<TimeLine, Dictionary<TimeSpan, List<mTuple<bool, SubCalendarEvent>>>>();// string in second dictionary is the String of the duration of the SubCalendarEvent
            Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> TotalPossibleTimeSpanWithStrings = new System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>();




            foreach (TimeLine eachTimeLine in AllFreeSpots)
            {
                List<mTuple<bool, SubCalendarEvent>> PossibleFillers = removeSubCalEventsThatCantWorkWithTimeLine(eachTimeLine, PossibleEntries[PreceedingTimeLine].ToList(), true);//hack we need to ensure cases of partial fit
                ForSnugArray.Add(eachTimeLine, new System.Collections.Generic.Dictionary<string, mTuple<int, TimeSpanWithStringID>>());
                TimeLine_WithMathChingSubCalevents.Add(eachTimeLine, new System.Collections.Generic.Dictionary<TimeSpan, System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>>());

                foreach (mTuple<bool, SubCalendarEvent> eachmTuple in PossibleFillers)
                {
                    if (ForSnugArray[eachTimeLine].ContainsKey(eachmTuple.Item2.ActiveDuration.ToString()))
                    {
                        ++ForSnugArray[eachTimeLine][eachmTuple.Item2.ActiveDuration.ToString()].Item1;
                    }
                    else
                    {
                        ForSnugArray[eachTimeLine].Add(eachmTuple.Item2.ActiveDuration.ToString(), new mTuple<int, TimeSpanWithStringID>(1, new TimeSpanWithStringID(eachmTuple.Item2.ActiveDuration, eachmTuple.Item2.ActiveDuration.ToString())));
                    }

                    if (!AllMovableSubCalEvents.ContainsKey(eachmTuple.Item2.ID))//populates all movable SubCalendarEVents
                    {
                        AllMovableSubCalEvents.Add(eachmTuple.Item2.ID, eachmTuple.Item2);

                        if (TotalPossibleTimeSpanWithStrings.ContainsKey(eachmTuple.Item2.ActiveDuration))
                        {
                            ++TotalPossibleTimeSpanWithStrings[eachmTuple.Item2.ActiveDuration].Item1;
                        }
                        else
                        {
                            TotalPossibleTimeSpanWithStrings.Add(eachmTuple.Item2.ActiveDuration, new mTuple<int, TimeSpanWithStringID>(1, new TimeSpanWithStringID(eachmTuple.Item2.ActiveDuration, eachmTuple.Item2.ActiveDuration.ToString())));
                        }
                    }
                    TimeSpan IdTimeSpan = eachmTuple.Item2.ActiveDuration;

                    if (TimeLine_WithMathChingSubCalevents[eachTimeLine].ContainsKey(IdTimeSpan))
                    {
                        TimeLine_WithMathChingSubCalevents[eachTimeLine][IdTimeSpan].Add(eachmTuple);
                    }
                    else
                    {
                        TimeLine_WithMathChingSubCalevents[eachTimeLine].Add(IdTimeSpan, new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>() { eachmTuple });
                    }


                    /*if (SubEventToMatchingTimeLinePossible.ContainsKey(eachmTuple.Item2.ActiveDuration.ToString()))// builds a dictionary of the TimeSpan String ID and a Dictionary of SubCalendar EVents with a List of feasible TimeLine
                    {
                        if (SubEventToMatchingTimeLinePossible[eachmTuple.Item2.ActiveDuration.ToString()].ContainsKey(eachmTuple.Item2))
                        {
                            SubEventToMatchingTimeLinePossible[eachmTuple.Item2.ActiveDuration.ToString()][eachmTuple.Item2].Add(eachTimeLine);
                        }
                        else 
                        {
                            SubEventToMatchingTimeLinePossible[eachmTuple.Item2.ActiveDuration.ToString()].Add(eachmTuple.Item2, new System.Collections.Generic.List<TimeLine>() { eachTimeLine });
                        }
                    }
                    else
                    {
                        SubEventToMatchingTimeLinePossible.Add(eachmTuple.Item2.ActiveDuration.ToString(), new System.Collections.Generic.Dictionary<SubCalendarEvent, System.Collections.Generic.List<TimeLine>>());
                        SubEventToMatchingTimeLinePossible[eachmTuple.Item2.ActiveDuration.ToString()].Add(eachmTuple.Item2, new System.Collections.Generic.List<TimeLine>() { eachTimeLine });
                    }*/
                }
                matchingValidSubcalendarEvents.Add(eachTimeLine, PossibleFillers);
            }


            foreach (TimeLine eachTimeLine in AllFreeSpots)
            {
                FreeSpotSnugArrays.Add(eachTimeLine, new SnugArray(ForSnugArray[eachTimeLine].Values.ToList(), eachTimeLine.TimelineSpan));
            }

            foreach (TimeLine eachTimeLine in AllFreeSpots)
            {
                FreeSpotSnugPossibiilities.Add(eachTimeLine, FreeSpotSnugArrays[eachTimeLine].MySnugPossibleEntries);
            }

            foreach (List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> allFreeSpotSnugPossibiilities in FreeSpotSnugPossibiilities.Values)
            {
                AllMoveOvrSet.AddRange(allFreeSpotSnugPossibiilities);
            }

            TimeSpanWithStringID UnAssignedTimeSpanWithString = new TimeSpanWithStringID(ReferenceTimeLine.TimelineSpan, ReferenceTimeLine.TimelineSpan.ToString());
            /*if (LeftOvers.Count > 0)
            {
                UnAssignedTimeSpanWithString = LeftOvers[0];
            }*/

            TimeSpan TotalMovedSofar = new TimeSpan(0);

            Dictionary<TimeLine, List<mTuple<bool, SubCalendarEvent>>> FreeSpots_MatchedEvents = new System.Collections.Generic.Dictionary<TimeLine, System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>>();

            Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> CompatibleListForReferenceTimeLine = AllCompatibleWithList[ReferenceTimeLine];

            foreach (TimeLine eachTimeLine in AllFreeSpots)
            {
                FreeSpots_MatchedEvents.Add(eachTimeLine, new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>());
                Tuple<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>, Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> UpdatedCompatibleList_BestSnugPossibility = UpdateCompatibleListOfTimeLine(CompatibleListForReferenceTimeLine, FreeSpotSnugPossibiilities[eachTimeLine], ReferenceTimeLine, UnAssignedTimeSpanWithString, TotalPossibleTimeSpanWithStrings);
                Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> UpdatedCompatibleList = UpdatedCompatibleList_BestSnugPossibility.Item1;
                Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> BestSnugAvailability = UpdatedCompatibleList_BestSnugPossibility.Item2;
                TotalMovedSofar += SnugArray.TotalTimeSpanOfSnugPossibility(BestSnugAvailability);
                Dictionary<TimeSpan, List<mTuple<bool, SubCalendarEvent>>> TimeLineMatchingSubEvents = TimeLine_WithMathChingSubCalevents[eachTimeLine];

                foreach (KeyValuePair<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair in BestSnugAvailability)
                {
                    if (TimeLineMatchingSubEvents[eachKeyValuePair.Key].Count > 0)
                    {
                        FreeSpots_MatchedEvents[eachTimeLine].Add(TimeLineMatchingSubEvents[eachKeyValuePair.Key][0]);
                        TimeLineMatchingSubEvents[eachKeyValuePair.Key].RemoveAt(0);
                        --TotalPossibleTimeSpanWithStrings[eachKeyValuePair.Key].Item1;
                        if (TotalPossibleTimeSpanWithStrings[eachKeyValuePair.Key].Item1 == 0)
                        {
                            TotalPossibleTimeSpanWithStrings.Remove(eachKeyValuePair.Key);
                        }
                    }
                    else
                    {
                        ;
                    }
                }


                //KeyValuePair<string, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair
                List<TimeSpan> AllKeys = CompatibleListForReferenceTimeLine.Keys.ToList();
                foreach (TimeSpan eachTimeSpan in AllKeys)//Updates the  Compatible List of the Reference timelin, in order to reflect movement in data
                {
                    if (UpdatedCompatibleList.ContainsKey(eachTimeSpan))//checks if reference timeLine has updated  keys
                    {
                        CompatibleListForReferenceTimeLine[eachTimeSpan] = UpdatedCompatibleList[eachTimeSpan];
                    }
                    else
                    {
                        CompatibleListForReferenceTimeLine.Remove(eachTimeSpan);
                    }
                }
            }





            TimeSpan FreeSpaceAfterMovement = ReferenceTimeLine.TimelineSpan - SnugArray.TotalTimeSpanOfSnugPossibility(CompatibleListForReferenceTimeLine);

            if (LeftOvers.Count > 0)//checks if there are move overs from preceeding compatible TimeLine
            {
                SnugArray BestFitIntoCurrentTimeLine = new SnugArray(AllCompatibleWithList[PreceedingTimeLine].Values.ToList(), FreeSpaceAfterMovement);//Tries to construct tightest fit on newly created free space in reference timelin....hack alert, it does not prioritize restricted elements

                List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> SortedData = BestFitIntoCurrentTimeLine.MySnugPossibleEntries;//sort the snug possibility based on mst filling
                if (SortedData.Count > 0)
                {
                    Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> selectedDictionary = SortedData[SortedData.Count - 1];

                    foreach (KeyValuePair<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair in selectedDictionary)
                    {
                        if (CompatibleListForReferenceTimeLine.ContainsKey(eachKeyValuePair.Key))
                        {
                            CompatibleListForReferenceTimeLine[eachKeyValuePair.Key].Item1 += eachKeyValuePair.Value.Item1;
                            AllCompatibleWithList[PreceedingTimeLine][eachKeyValuePair.Key].Item1 -= eachKeyValuePair.Value.Item1;
                        }
                        else
                        {
                            CompatibleListForReferenceTimeLine.Add(eachKeyValuePair.Key, eachKeyValuePair.Value);
                            AllCompatibleWithList[PreceedingTimeLine][eachKeyValuePair.Key].Item1 -= eachKeyValuePair.Value.Item1;
                        }

                        if (AllCompatibleWithList[PreceedingTimeLine][eachKeyValuePair.Key].Item1 < 0)
                        {
                            ;
                        }
                    }
                }
            }

            List<mTuple<bool, SubCalendarEvent>> retValue = new System.Collections.Generic.List<mTuple<bool, SubCalendarEvent>>(AllReadyAssignedSubCalEvents);
            foreach (TimeLine eachTimeLine in AllFreeSpots)//Snaps each Subcalevent to the beginning of a free TimeLine
            {
                List<SubCalendarEvent> ListOfSubCalEvents = Utility.mTupleToSubCalEvents(FreeSpots_MatchedEvents[eachTimeLine]);
                if (Utility.PinSubEventsToStart(ListOfSubCalEvents, eachTimeLine))
                {
                    retValue.AddRange(FreeSpots_MatchedEvents[eachTimeLine]);
                }
                else
                {
                    ;
                }
            }

            return retValue;



        }
Ejemplo n.º 27
0
            public override void Setup(IHttpRequestData requestData)
            {
                request.url = requestData.URL;

                switch (requestData.Method)
                {
                case HttpMethod.Get:
                    request.method = UnityWebRequest.kHttpVerbGET;
                    break;

                case HttpMethod.Post:
                    request.method = UnityWebRequest.kHttpVerbPOST;
                    break;

                case HttpMethod.Put:
                    request.method = UnityWebRequest.kHttpVerbPUT;
                    break;

                case HttpMethod.Delete:
                    request.method = UnityWebRequest.kHttpVerbDELETE;
                    break;
                }

                if (requestData.Method != HttpMethod.Get && requestData.Method != HttpMethod.Head)
                {
                    var dh = requestData.DataAndHeader;
                    request.uploadHandler = new UploadHandlerRaw((byte[])dh["data"]);
                    System.Collections.Generic.Dictionary <string, string> formHeaders = (System.Collections.Generic.Dictionary <string, string>)dh["header"];
                    if (formHeaders.ContainsKey("Content-Type"))
                    {
                        request.uploadHandler.contentType = formHeaders["Content-Type"];
                    }
                }
                else
                {
                    request.uploadHandler = null;
                }

                if (requestData.Method != HttpMethod.Head)
                {
                    switch (requestData.ResponseType)
                    {
                    case ResponseType.Text:
                        request.downloadHandler = new DownloadHandlerBuffer();
                        break;

                    case ResponseType.ReadableTexture:
                    case ResponseType.Texture:
                        request.downloadHandler = new DownloadHandlerTexture(requestData.ResponseType == ResponseType.ReadableTexture);
                        break;
                    }
                }

                var headers = new System.Collections.Generic.Dictionary <string, string> (requestData.Headers);

                if (headers != null)
                {
                    headers.Remove("Content-Type");
                    foreach (var kv in headers)
                    {
                        request.SetRequestHeader(kv.Key, kv.Value);
                    }
                }
            }
Ejemplo n.º 28
0
        List<List<SubCalendarEvent>> generateCombinationForDifferentEntries(Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> CompatibleWithList, Dictionary<TimeSpan, Dictionary<string, mTuple<bool, SubCalendarEvent>>> PossibleEntries)
        {
            /*
             * Function attempts to generate multiple combinations of compatible sub calendar event for Snug fit entry
             * CompatibleWithList is an snug fit result
             * PossibleEntries are the possible sub calendar that can be used in the combinatorial result
             */
            ++CountCall;
            if (CountCall == 4)
            {
                ;
            }
            List<List<List<string>>> MAtrixedSet = new System.Collections.Generic.List<System.Collections.Generic.List<System.Collections.Generic.List<string>>>();
            Dictionary<string, mTuple<int, List<SubCalendarEvent>>> var4 = new System.Collections.Generic.Dictionary<string, mTuple<int, System.Collections.Generic.List<SubCalendarEvent>>>();
            List<List<SubCalendarEvent>> retValue = new System.Collections.Generic.List<System.Collections.Generic.List<SubCalendarEvent>>();
            foreach (KeyValuePair<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair0 in CompatibleWithList)//loops every timespan in Snug FIt possibility
            {
                TimeSpan eachTimeSpan = eachKeyValuePair0.Key;

                Dictionary<string, mTuple<bool, SubCalendarEvent>> var1 = PossibleEntries[eachTimeSpan];
                List<List<string>> receivedValue = new System.Collections.Generic.List<System.Collections.Generic.List<string>>();
                Dictionary<string, int> var2 = new System.Collections.Generic.Dictionary<string, int>();
                foreach (KeyValuePair<string, mTuple<bool, SubCalendarEvent>> eachKeyValuePair in var1)
                {
                    string ParentID = eachKeyValuePair.Value.Item2.SubEvent_ID.getStringIDAtLevel(0);
                    if (var2.ContainsKey(ParentID))
                    {
                        ++var2[ParentID];
                        var4[ParentID].Item2.Add(eachKeyValuePair.Value.Item2);
                    }
                    else
                    {
                        var2.Add(ParentID, 1);
                        List<SubCalendarEvent> var5 = new System.Collections.Generic.List<SubCalendarEvent>();
                        var5.Add(eachKeyValuePair.Value.Item2);
                        var4.Add(ParentID, new mTuple<int, System.Collections.Generic.List<SubCalendarEvent>>(0, var5));
                    }
                }
                List<mTuple<string, int>> PossibleCalEvents = new System.Collections.Generic.List<mTuple<string, int>>();
                foreach (KeyValuePair<string, int> eachKeyValuePair in var2)
                {
                    PossibleCalEvents.Add(new mTuple<string, int>(eachKeyValuePair.Key, eachKeyValuePair.Value));
                }

                List<List<string>> var3 = generateCombinationForSpecficTimeSpanStringID(eachKeyValuePair0.Value.Item1, PossibleCalEvents);
                MAtrixedSet.Add(var3);
            }

            List<List<string>> serializedList = Utility.SerializeList(MAtrixedSet);
            foreach (List<string> eachList in serializedList)//serializedList has a list of fittable ParentIDs, the loop replaces each List of strings with List of subCalendarEvents
            {
                List<SubCalendarEvent> var6 = new System.Collections.Generic.List<SubCalendarEvent>();
                mTuple<int, List<SubCalendarEvent>> var7 = new mTuple<int, System.Collections.Generic.List<SubCalendarEvent>>(0, new System.Collections.Generic.List<SubCalendarEvent>());
                foreach (string eachString in eachList)
                {
                    var7 = var4[eachString];
                    var6.Add(var7.Item2[var7.Item1++]);
                }
                foreach (KeyValuePair<string, mTuple<int, List<SubCalendarEvent>>> eachKeyValuePair in var4)
                {
                    eachKeyValuePair.Value.Item1 = 0;
                }

                //var7.Item1 = 0;

                retValue.Add(var6);
            }

            return retValue;

        }
Ejemplo n.º 29
0
        /// <summary>The subSpans are ordered in the same doc, so there is a possible match.
        /// Compute the slop while making the match as short as possible by advancing
        /// all subSpans except the last one in reverse order.
        /// </summary>
        private bool ShrinkToAfterShortestMatch()
        {
            matchStart = subSpans[subSpans.Length - 1].Start();
            matchEnd   = subSpans[subSpans.Length - 1].End();
            System.Collections.Generic.Dictionary <byte[], byte[]> possibleMatchPayloads = new System.Collections.Generic.Dictionary <byte[], byte[]>();
            if (subSpans[subSpans.Length - 1].IsPayloadAvailable())
            {
                System.Collections.Generic.ICollection <byte[]> payload = subSpans[subSpans.Length - 1].GetPayload();
                foreach (byte[] pl in payload)
                {
                    if (!possibleMatchPayloads.ContainsKey(pl))
                    {
                        possibleMatchPayloads.Add(pl, pl);
                    }
                }
            }

            System.Collections.Generic.List <byte[]> possiblePayload = null;

            int matchSlop = 0;
            int lastStart = matchStart;
            int lastEnd   = matchEnd;

            for (int i = subSpans.Length - 2; i >= 0; i--)
            {
                Spans prevSpans = subSpans[i];
                if (collectPayloads && prevSpans.IsPayloadAvailable())
                {
                    System.Collections.Generic.ICollection <byte[]> payload = prevSpans.GetPayload();
                    possiblePayload = new System.Collections.Generic.List <byte[]>(payload.Count);
                    possiblePayload.AddRange(payload);
                }

                int prevStart = prevSpans.Start();
                int prevEnd   = prevSpans.End();
                while (true)
                {
                    // Advance prevSpans until after (lastStart, lastEnd)
                    if (!prevSpans.Next())
                    {
                        inSameDoc = false;
                        more      = false;
                        break; // Check remaining subSpans for final match.
                    }
                    else if (matchDoc != prevSpans.Doc())
                    {
                        inSameDoc = false; // The last subSpans is not advanced here.
                        break;             // Check remaining subSpans for last match in this document.
                    }
                    else
                    {
                        int ppStart = prevSpans.Start();
                        int ppEnd   = prevSpans.End(); // Cannot avoid invoking .end()
                        if (!DocSpansOrdered(ppStart, ppEnd, lastStart, lastEnd))
                        {
                            break; // Check remaining subSpans.
                        }
                        else
                        {
                            // prevSpans still before (lastStart, lastEnd)
                            prevStart = ppStart;
                            prevEnd   = ppEnd;
                            if (collectPayloads && prevSpans.IsPayloadAvailable())
                            {
                                System.Collections.Generic.ICollection <byte[]> payload = prevSpans.GetPayload();
                                possiblePayload = new System.Collections.Generic.List <byte[]>(payload.Count);
                                possiblePayload.AddRange(payload);
                            }
                        }
                    }
                }

                if (collectPayloads && possiblePayload != null)
                {
                    foreach (byte[] pl in possiblePayload)
                    {
                        if (!possibleMatchPayloads.ContainsKey(pl))
                        {
                            possibleMatchPayloads.Add(pl, pl);
                        }
                    }
                }

                System.Diagnostics.Debug.Assert(prevStart <= matchStart);
                if (matchStart > prevEnd)
                {
                    // Only non overlapping spans add to slop.
                    matchSlop += (matchStart - prevEnd);
                }

                /* Do not break on (matchSlop > allowedSlop) here to make sure
                 * that subSpans[0] is advanced after the match, if any.
                 */
                matchStart = prevStart;
                lastStart  = prevStart;
                lastEnd    = prevEnd;
            }

            bool match = matchSlop <= allowedSlop;

            if (collectPayloads && match && possibleMatchPayloads.Count > 0)
            {
                matchPayload.AddRange(possibleMatchPayloads.Keys);
            }

            return(match); // ordered and allowed slop
        }
Ejemplo n.º 30
0
        List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> getAveragedOutTIimeLine(List<List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>> arg1, int PreecdintTimeSpanWithSringIDCoun)
        {
            /*
             * Function takes a list of valid possible matches. It uses this list of valid matches to calculate an average which will be used to calculate the best snug possibility
             * arg1= The List of possible snug time Lines
             */

            List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> retValue = new List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>();
            List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> Total = new List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>();
            /*if (arg1.Count<1)
            {
                return retValue;
            }*/
            foreach (Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachDictionary in arg1[0])//initializes Total with the first element in the list
            {
                Total.Add(new System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>());
            }



            int i = 0;
            int j = 0;

            for (; j < arg1.Count; j++)
            {
                List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> eachList = arg1[j];
                if (j == 30)
                {
                    ;
                }
                i = 0;
                foreach (Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachDictionary in eachList)
                {

                    foreach (KeyValuePair<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair in eachDictionary)
                    {
                        if (Total[i].ContainsKey(eachKeyValuePair.Key))
                        {
                            Total[i][eachKeyValuePair.Key].Item1 += eachKeyValuePair.Value.Item1;
                        }
                        else
                        {
                            Total[i].Add(eachKeyValuePair.Key, new mTuple<int, TimeSpanWithStringID>(eachKeyValuePair.Value.Item1, eachKeyValuePair.Value.Item2));
                        }
                    }
                    ++i;
                }
            }

            Dictionary<TimeSpan, int> RoundUpRoundDown = new System.Collections.Generic.Dictionary<TimeSpan, int>();
            i = 0;
            foreach (Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachDictionary in Total)//initializes Total with the first element in the list
            {

                retValue.Add(new System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>());
                foreach (KeyValuePair<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair in eachDictionary)
                {
                    double arg0 = eachKeyValuePair.Value.Item1 / j;
                    int PassedToRet = (int)Math.Round(arg0);
                    string[] Int_Decimal = arg0.ToString().Split('.');
                    if (Int_Decimal.Length == 2)
                    {
                        if (Int_Decimal[1] == "5")
                        {
                            if (RoundUpRoundDown.ContainsKey(eachKeyValuePair.Key))
                            {
                                if (RoundUpRoundDown[eachKeyValuePair.Key] == 0)
                                {
                                    RoundUpRoundDown[eachKeyValuePair.Key] = 1;
                                }
                                else
                                {
                                    PassedToRet = (int)Math.Floor(arg0);
                                    RoundUpRoundDown[eachKeyValuePair.Key] = 0;
                                }
                            }
                            else
                            {
                                PassedToRet = (int)Math.Floor(arg0);
                                RoundUpRoundDown.Add(eachKeyValuePair.Key, 0);
                            }
                        }
                    }

                    if (PassedToRet > 0)
                    {
                        retValue[i].Add(eachKeyValuePair.Key, new mTuple<int, TimeSpanWithStringID>(PassedToRet, eachKeyValuePair.Value.Item2));
                    }
                }
                i++;
            }


            List<List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>> ListOfPossibleretValue = new System.Collections.Generic.List<System.Collections.Generic.List<System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>>();


            i = 0;
            foreach (List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>> eachList in arg1)
            {
                i = 0;
                bool arg3 = false;
                foreach (Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachDictionary in retValue)//initializes Total with the first element in the list
                {
                    Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>> arg2 = eachList[i];
                    foreach (KeyValuePair<TimeSpan, mTuple<int, TimeSpanWithStringID>> eachKeyValuePair in eachDictionary)
                    {
                        if (arg2.ContainsKey(eachKeyValuePair.Key))
                        {
                            if (eachKeyValuePair.Value.Item1 <= arg2[eachKeyValuePair.Key].Item1)
                            {
                                arg3 = true;
                            }
                            else
                            {
                                arg3 = false;
                                break;
                            }
                        }
                    }

                    if (!arg3)
                    {
                        break;
                    }
                    i++;
                }

                if (arg3)
                {
                    ListOfPossibleretValue.Add(eachList);
                }


            }
            List<List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>> SpreadOutResult = getMostSpreadOut(ListOfPossibleretValue);
            Random myRandomizer=new Random();
            if (((SpreadOutResult.Count < 1) && (arg1.Count > 0)))//hack alert, this says if for some reason we have no generated possible ListOfPossibleretValue, we can pick one at random
            {
                return arg1[myRandomizer.Next(0, arg1.Count)];
            }
            ListOfPossibleretValue = SpreadOutResult;




            List<List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>> TempList = new System.Collections.Generic.List<System.Collections.Generic.List<System.Collections.Generic.Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>>();
            TempList.Add(retValue);

            Tuple<int, List<List<Dictionary<TimeSpan, mTuple<int, TimeSpanWithStringID>>>>> arg4 = Utility.getHighestCountList(TempList, retValue);

            if (arg4.Item1 <= PreecdintTimeSpanWithSringIDCoun)
            {
                return retValue;
            }

            else
            {
                return getAveragedOutTIimeLine(ListOfPossibleretValue, arg4.Item1);
            }



        }
Ejemplo n.º 31
0
 public bool hayClave(string clave)
 {
     return(_json != null && _json.ContainsKey(clave));
 }
Ejemplo n.º 32
0
        List<List<SubCalendarEvent>> BuildListMatchingTimelineAndSubCalendarEvent(List<List<TimeSpanWithEventID>> ListOfSnugPossibilities, List<SubCalendarEvent> ListOfSubCalendarEvents, List<SubCalendarEvent> ConsrainedList)
        {
            List<List<SubCalendarEvent>> retValue = new System.Collections.Generic.List<System.Collections.Generic.List<SubCalendarEvent>>();
            Dictionary<string, SubCalendarEventListCounter> Dict_ParentIDListOfSubCalEvents = new System.Collections.Generic.Dictionary<string, SubCalendarEventListCounter>();
            foreach (SubCalendarEvent eachSubCalendarEvent in ListOfSubCalendarEvents)
            {
                string ParentKey = eachSubCalendarEvent.SubEvent_ID.getCalendarEventID();
                if (Dict_ParentIDListOfSubCalEvents.ContainsKey(ParentKey))
                {
                    Dict_ParentIDListOfSubCalEvents[ParentKey].UpdateList = eachSubCalendarEvent;
                }
                else
                {
                    Dict_ParentIDListOfSubCalEvents.Add(ParentKey, new SubCalendarEventListCounter(eachSubCalendarEvent, ParentKey));
                }
            }

            foreach (List<TimeSpanWithEventID> eachListOfTimeSpanWithID in ListOfSnugPossibilities)
            {
                List<SubCalendarEvent> CurentLine = new System.Collections.Generic.List<SubCalendarEvent>();
                CurentLine.AddRange(ConsrainedList);
                foreach (TimeSpanWithEventID eachTimeSpanWithID in eachListOfTimeSpanWithID)
                {
                    CurentLine.Add(Dict_ParentIDListOfSubCalEvents[eachTimeSpanWithID.TimeSpanID.ToString()].getNextSubCalendarEvent);
                }

                retValue.Add(CurentLine);
                foreach (SubCalendarEventListCounter eachSubCalendarEventListCounter in Dict_ParentIDListOfSubCalEvents.Values)
                {
                    eachSubCalendarEventListCounter.reset();
                }

            }

            return retValue;



            /*List<TimeSpan> AllTimesSpan = new List<TimeSpan>();
            Dictionary<TimeSpanWithID, List<SubCalendarEvent>> DictionaryOfTimeSpanWithIDandSubCalendarEvent = new System.Collections.Generic.Dictionary<TimeSpanWithID, System.Collections.Generic.List<SubCalendarEvent>>();
            List<List<SubCalendarEvent>> MatchingListOfSnugPossibilitesWithSubcalendarEvents = new System.Collections.Generic.List<System.Collections.Generic.List<SubCalendarEvent>>();
            Dictionary<string, List<SubCalendarEvent>> ListOfCaleventIDAndListSubCalendarEvent = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<SubCalendarEvent>>();

            
            //foreach (List<TimeSpan> MySnugPossibility in ListOfSnugPossibilities)
            //{
                //var MyConcatList = AllTimesSpan.Concat(MySnugPossibility);
              //  AllTimesSpan=MyConcatList.ToList();
            //}
            Dictionary <string ,int> DictCalendarEventID_Ini = new System.Collections.Generic.Dictionary<string,int>();
            foreach (SubCalendarEvent MySubCalendarEvent in ListOfSubCalendarEvents)
            { 
                EventID MyEventID = new EventID( MySubCalendarEvent.ID);
                if (ListOfCaleventIDAndListSubCalendarEvent.ContainsKey(MyEventID.getLevelID(0)))
                {
                    ListOfCaleventIDAndListSubCalendarEvent[MyEventID.getLevelID(0)].Add(MySubCalendarEvent);
                }
                else
                {
                    ListOfCaleventIDAndListSubCalendarEvent.Add(MyEventID.getLevelID(0),new System.Collections.Generic.List<SubCalendarEvent>());
                    ListOfCaleventIDAndListSubCalendarEvent[MyEventID.getLevelID(0)].Add(MySubCalendarEvent);
                    DictCalendarEventID_Ini.Add(MyEventID.getLevelID(0),0);
                }
            }


            List<SubCalendarEvent> MyListOfSubCalendarEvent = new System.Collections.Generic.List<SubCalendarEvent>();
            int Index = 0;
            Dictionary <string ,int> DictCalendarEventID_Index = new System.Collections.Generic.Dictionary<string,int>(DictCalendarEventID_Ini);
            foreach (List<TimeSpanWithID> MyListOfTimeSpanWithID in ListOfSnugPossibilities)
            {
                DictCalendarEventID_Index = new System.Collections.Generic.Dictionary<string,int>(DictCalendarEventID_Ini);
                foreach (TimeSpanWithID MyTimeSpanWithID in MyListOfTimeSpanWithID)
                {
                    string ID=MyTimeSpanWithID.TimeSpanID.getLevelID(0);
                    Index = DictCalendarEventID_Index[ID];
                    MyListOfSubCalendarEvent.Add(ListOfCaleventIDAndListSubCalendarEvent[ID][Index]);
                    ++Index;
                    DictCalendarEventID_Index[ID] = Index;
                }
                MatchingListOfSnugPossibilitesWithSubcalendarEvents.Add(MyListOfSubCalendarEvent);
                MyListOfSubCalendarEvent = new System.Collections.Generic.List<SubCalendarEvent>();
            }
            

            return MatchingListOfSnugPossibilitesWithSubcalendarEvents;*/
        }
Ejemplo n.º 33
0
        private void show_devTb()
        {
            this.m_ininit = true;
            DataGridViewColumn sortedColumn = this.dgvAllDevices.SortedColumn;

            this.dgvAllDevices.Rows.Clear();
            System.Collections.Generic.Dictionary <long, CommParaClass> deviceRackMapping = DeviceOperation.GetDeviceRackMapping();
            System.Collections.Generic.List <DeviceInfo> allDevice = DeviceOperation.GetAllDevice();
            foreach (TreeNode treeNode in this.m_rootNode.Nodes)
            {
                string     text       = treeNode.Text;
                long       num        = System.Convert.ToInt64(treeNode.Name);
                bool       flag       = false;
                DeviceInfo deviceInfo = null;
                for (int i = 0; i < allDevice.Count; i++)
                {
                    deviceInfo = allDevice[i];
                    if ((long)deviceInfo.DeviceID == num)
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    string    text2     = "";
                    IPAddress iPAddress = IPAddress.Parse(deviceInfo.DeviceIP);
                    if (deviceRackMapping.ContainsKey(num))
                    {
                        text2 = deviceRackMapping[num].String_First;
                    }
                    string text3 = this.tbFilterKey.Text;
                    if (text3.Length <= 0 || text.Contains(text3) || deviceInfo.Mac.Contains(text3) || iPAddress.ToString().Contains(text3) || deviceInfo.Port.ToString().Contains(text3) || deviceInfo.ModelNm.Contains(text3) || text2.Contains(text3))
                    {
                        object[] values;
                        if (ClientAPI.IsDeviceOnline(deviceInfo.DeviceID))
                        {
                            values = new object[]
                            {
                                this.imgon,
                                text,
                                deviceInfo.Mac,
                                iPAddress,
                                deviceInfo.Port,
                                deviceInfo.ModelNm,
                                text2,
                                num.ToString()
                            };
                        }
                        else
                        {
                            if (ClientAPI.IsMACConflict(deviceInfo.Mac))
                            {
                                values = new object[]
                                {
                                    this.imgConflict,
                                    text,
                                    deviceInfo.Mac,
                                    iPAddress,
                                    deviceInfo.Port,
                                    deviceInfo.ModelNm,
                                    text2,
                                    num.ToString()
                                };
                            }
                            else
                            {
                                values = new object[]
                                {
                                    this.imgoff,
                                    text,
                                    deviceInfo.Mac,
                                    iPAddress,
                                    deviceInfo.Port,
                                    deviceInfo.ModelNm,
                                    text2,
                                    num.ToString()
                                };
                            }
                        }
                        this.dgvAllDevices.Rows.Add(values);
                    }
                }
            }
            foreach (DataGridViewRow dataGridViewRow in (System.Collections.IEnumerable) this.dgvAllDevices.Rows)
            {
                DataGridViewCell dataGridViewCell = dataGridViewRow.Cells[0];
                if (dataGridViewCell.Value.Equals(this.imgConflict))
                {
                    dataGridViewCell.ToolTipText = EcoLanguage.getMsg(LangRes.tips_MACMismatch, new string[0]);
                }
            }
            if (sortedColumn != null)
            {
                ListSortDirection direction = (this.dgvAllDevices.SortOrder == SortOrder.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
                this.dgvAllDevices.Sort(sortedColumn, direction);
            }
            if (this.dgvAllDevices.Rows.Count == 0)
            {
                this.butDevicesDel.Enabled    = false;
                this.butDeviceSetup.Enabled   = false;
                this.butSyncThreshold.Enabled = false;
            }
            else
            {
                this.butDevicesDel.Enabled    = true;
                this.butDeviceSetup.Enabled   = true;
                this.butSyncThreshold.Enabled = true;
            }
            this.m_ininit = false;
        }
Ejemplo n.º 34
0
 /// <summary>The subSpans are ordered in the same doc, so there is a possible match.
 /// Compute the slop while making the match as short as possible by advancing
 /// all subSpans except the last one in reverse order.
 /// </summary>
 private bool ShrinkToAfterShortestMatch()
 {
     matchStart = subSpans[subSpans.Length - 1].Start();
     matchEnd = subSpans[subSpans.Length - 1].End();
     System.Collections.Generic.Dictionary<byte[], byte[]> possibleMatchPayloads = new System.Collections.Generic.Dictionary<byte[], byte[]>();
     if (subSpans[subSpans.Length - 1].IsPayloadAvailable())
     {
         System.Collections.Generic.ICollection<byte[]> payload = subSpans[subSpans.Length - 1].GetPayload();
         foreach(byte[] pl in payload)
         {
             if (!possibleMatchPayloads.ContainsKey(pl))
             {
                 possibleMatchPayloads.Add(pl, pl);
             }
         }
     }
     
     System.Collections.Generic.List<byte[]> possiblePayload = null;
     
     int matchSlop = 0;
     int lastStart = matchStart;
     int lastEnd = matchEnd;
     for (int i = subSpans.Length - 2; i >= 0; i--)
     {
         Spans prevSpans = subSpans[i];
         if (collectPayloads && prevSpans.IsPayloadAvailable())
         {
             System.Collections.Generic.ICollection<byte[]> payload = prevSpans.GetPayload();
             possiblePayload = new System.Collections.Generic.List<byte[]>(payload.Count);
             possiblePayload.AddRange(payload);
         }
         
         int prevStart = prevSpans.Start();
         int prevEnd = prevSpans.End();
         while (true)
         {
             // Advance prevSpans until after (lastStart, lastEnd)
             if (!prevSpans.Next())
             {
                 inSameDoc = false;
                 more = false;
                 break; // Check remaining subSpans for final match.
             }
             else if (matchDoc != prevSpans.Doc())
             {
                 inSameDoc = false; // The last subSpans is not advanced here.
                 break; // Check remaining subSpans for last match in this document.
             }
             else
             {
                 int ppStart = prevSpans.Start();
                 int ppEnd = prevSpans.End(); // Cannot avoid invoking .end()
                 if (!DocSpansOrdered(ppStart, ppEnd, lastStart, lastEnd))
                 {
                     break; // Check remaining subSpans.
                 }
                 else
                 {
                     // prevSpans still before (lastStart, lastEnd)
                     prevStart = ppStart;
                     prevEnd = ppEnd;
                     if (collectPayloads && prevSpans.IsPayloadAvailable())
                     {
                         System.Collections.Generic.ICollection<byte[]> payload = prevSpans.GetPayload();
                         possiblePayload = new System.Collections.Generic.List<byte[]>(payload.Count);
                         possiblePayload.AddRange(payload);
                     }
                 }
             }
         }
         
         if (collectPayloads && possiblePayload != null)
         {
             foreach (byte[] pl in possiblePayload)
             {
                 if (!possibleMatchPayloads.ContainsKey(pl))
                 {
                     possibleMatchPayloads.Add(pl, pl);
                 }
             }
         }
         
         System.Diagnostics.Debug.Assert(prevStart <= matchStart);
         if (matchStart > prevEnd)
         {
             // Only non overlapping spans add to slop.
             matchSlop += (matchStart - prevEnd);
         }
         
         /* Do not break on (matchSlop > allowedSlop) here to make sure
         * that subSpans[0] is advanced after the match, if any.
         */
         matchStart = prevStart;
         lastStart = prevStart;
         lastEnd = prevEnd;
     }
     
     bool match = matchSlop <= allowedSlop;
     
     if (collectPayloads && match && possibleMatchPayloads.Count > 0)
     {
         matchPayload.AddRange(possibleMatchPayloads.Keys);
     }
     
     return match; // ordered and allowed slop
 }
Ejemplo n.º 35
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="target"></param>
        /// <param name="kvp"></param>
        /// <param name="escapeForXml"></param>
        /// <returns></returns>
        public static string ApplyKVP(string target, System.Collections.Generic.Dictionary <string, string> kvp, bool escapeForXml, StemStr reuseStemStr = null)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (kvp == null)
            {
                throw new ArgumentNullException(nameof(kvp));
            }

            IEnumerable <string> keysWithTokensInValues = kvp.Keys.Where(i => kvp[i] != null && kvp[i].Contains("[") && kvp[i].Contains("]"));

            foreach (string key in keysWithTokensInValues)
            {
                if (kvp[key].IndexOf(key, StringComparison.InvariantCultureIgnoreCase) >= 0)
                {
                    throw new Exception("Map error - key in value (" + key + ")");
                }
            }

            // Check for cross collision
            foreach (string key in keysWithTokensInValues)
            {
                foreach (string k in keysWithTokensInValues)
                {
                    if (kvp[key].IndexOf(k, StringComparison.InvariantCultureIgnoreCase) >= 0 && kvp[k].IndexOf(key, StringComparison.InvariantCultureIgnoreCase) >= 0)
                    {
                        throw new Exception("Map error - cross key reference (" + key + ", " + k + ")");
                    }
                }
            }

            DateTime      now         = DateTime.UtcNow;
            List <string> keysPresent = new List <string>();

            StemStr ss = reuseStemStr;

            if (ss == null)
            {
                ss = new StemStr(target, target.Length * 2);
            }
            else
            {
                ss.Reset(target);
            }

            List <string> keys = new List <string>();

            while (true)
            {
                bool matchFound = false;

                int masterIndex = 0;

                keys.Clear();

                while ((masterIndex = ss.IndexOf("[", masterIndex)) >= 0)
                {
                    if (ss.IndexOf("]", masterIndex) < 0)
                    {
                        break;
                    }

                    string k = ss.Substring(masterIndex, ss.IndexOf("]", masterIndex) - masterIndex + 1);

                    if (k.Length == 0)
                    {
                        masterIndex++;
                        continue;
                    }

                    masterIndex += k.Length;

                    if (keys.Contains(k))
                    {
                        continue;
                    }

                    keys.Add(k);

                    string v = null;

                    if (kvp.ContainsKey(k))
                    {
                        v = kvp[k];
                    }
                    else
                    {
                        v = kvp.Where(i => i.Key.Equals(k, StringComparison.InvariantCultureIgnoreCase)).Select(i => i.Value).FirstOrDefault();
                    }

                    if (v == null)
                    {
                        continue;
                    }

                    v = v.Trim();

                    if (k.Equals("[NewGuid]", StringComparison.InvariantCultureIgnoreCase))
                    {
                        matchFound = true;

                        if (target == k)
                        {
                            return(Guid.NewGuid().ToString());
                        }

                        string[] parts = target.Split(new string[] { k }, StringSplitOptions.None);

                        string tmp = parts[0];

                        for (int i = 1; i < parts.Length; i++)
                        {
                            tmp = tmp + Guid.NewGuid().ToString() + parts[i];
                        }

                        ss.Reset(tmp);
                    }
                    else
                    {
                        if (v.Equals("Reserved", StringComparison.InvariantCultureIgnoreCase))
                        {
                            continue;
                        }

                        if (v.ToUpper().Contains(k.ToUpper()))
                        {
                            throw new Exception("Key in value! (" + k + ", " + v + ")");
                        }

                        if (k.Equals("[UtcNow]", StringComparison.InvariantCultureIgnoreCase))
                        {
                            v = now.ToString(v, System.Globalization.CultureInfo.CurrentCulture);
                        }

                        if (escapeForXml)
                        {
                            v = System.Security.SecurityElement.Escape(v);
                        }

                        matchFound = true;

                        ss.Replace(k, v, 0);
                    }
                }

                if (!matchFound)
                {
                    return(ss.ToString());
                }
            }
        }
Ejemplo n.º 36
0
    private HumanDescription CreateHumanDescription(GameObject skeletonRoot)
    {
        HumanDescription desc = new HumanDescription();

        List <HumanBone>    humanBones    = new List <HumanBone>();
        List <SkeletonBone> skeletonBones = new List <SkeletonBone>();

        Dictionary <string, string> boneName = new System.Collections.Generic.Dictionary <string, string>();

        boneName["Hips"]                 = "Bip001 Pelvis";
        boneName["Spine"]                = "Bip001 Spine";
        boneName["UpperChest"]           = "Bip001 Spine2";
        boneName["Chest"]                = "Bip001 Spine1";
        boneName["Head"]                 = "Bip001 Head";
        boneName["Left Thumb Proximal"]  = "Bip001 L Finger0";
        boneName["LeftFoot"]             = "Bip001 L Foot";
        boneName["LeftHand"]             = "Bip001 L Hand";
        boneName["LeftLowerArm"]         = "Bip001 L Forearm";
        boneName["LeftLowerLeg"]         = "Bip001 L Calf";
        boneName["LeftShoulder"]         = "Bip001 L Clavicle";
        boneName["LeftToes"]             = "Bip001 L Toe0";
        boneName["LeftUpperArm"]         = "Bip001 L UpperArm";
        boneName["LeftUpperLeg"]         = "Bip001 L Thigh";
        boneName["Neck"]                 = "Bip001 Neck";
        boneName["Right Thumb Proximal"] = "Bip001 R Finger0";
        boneName["RightFoot"]            = "Bip001 R Foot";
        boneName["RightHand"]            = "Bip001 R Hand";
        boneName["RightLowerArm"]        = "Bip001 R Forearm";
        boneName["RightLowerLeg"]        = "Bip001 R Calf";
        boneName["RightShoulder"]        = "Bip001 R Clavicle";
        boneName["RightToes"]            = "Bip001 R Toe0";
        boneName["RightUpperArm"]        = "Bip001 R UpperArm";
        boneName["RightUpperLeg"]        = "Bip001 R Thigh";

        string[] humanName = HumanTrait.BoneName;
        int      i         = 0;

        while (i < humanName.Length)
        {
            if (boneName.ContainsKey(humanName[i]))
            {
                HumanBone humanBone = new HumanBone();
                humanBone.humanName = humanName[i];
                humanBone.boneName  = boneName[humanName[i]];
                humanBone.limit.useDefaultValues = true;
                humanBones.Add(humanBone);
            }
            i++;
        }
        //foreach (KeyValuePair<string, string> item in boneName)
        //{
        //    HumanBone humanBone = new HumanBone();
        //    humanBone.humanName = item.Key;
        //    humanBone.boneName = item.Value;
        //    humanBone.limit.useDefaultValues = true;
        //    humanBones.Add(humanBone);
        //}
        AddSkeletonBoneRecursive(skeletonRoot.transform, skeletonBones);

        desc.human    = humanBones.ToArray();
        desc.skeleton = skeletonBones.ToArray();

        //desc.upperArmTwist = 0.5f;
        //desc.lowerArmTwist = 0.5f;
        //desc.upperLegTwist = 0.5f;
        //desc.lowerLegTwist = 0.5f;
        //desc.armStretch = 0.05f;
        //desc.legStretch = 0.05f;
        //desc.feetSpacing = 0.0f;

        return(desc);
    }
Ejemplo n.º 37
0
        private static System.Collections.Generic.Dictionary <int, BankThreshold> GetBankThreshold(System.Collections.Generic.Dictionary <string, string> result)
        {
            System.Collections.Generic.Dictionary <int, BankThreshold> dictionary = new System.Collections.Generic.Dictionary <int, BankThreshold>();
            System.Collections.Generic.IEnumerator <string>            enumerator = result.Keys.GetEnumerator();
            EatonGroupEntryMib_M2   eatonGroupEntryMib_M   = null;
            EatonGroupVoltageMib_M2 eatonGroupVoltageMib_M = null;
            EatonGroupCurrentMib_M2 eatonGroupCurrentMib_M = null;
            int num = 0;

            while (enumerator.MoveNext())
            {
                string current = enumerator.Current;
                string text    = result[current];
                if ("\0".Equals(text))
                {
                    text = System.Convert.ToString(-1000000);
                }
                else
                {
                    if (text == null || string.IsNullOrEmpty(text))
                    {
                        text = System.Convert.ToString(-500000);
                    }
                }
                int num2 = System.Convert.ToInt32(current.Substring(current.LastIndexOf(".") + 1));
                if (!dictionary.ContainsKey(num2))
                {
                    BankThreshold value = new BankThreshold(num2);
                    dictionary.Add(num2, value);
                }
                if (num != num2)
                {
                    eatonGroupEntryMib_M   = new EatonGroupEntryMib_M2(num2);
                    eatonGroupCurrentMib_M = new EatonGroupCurrentMib_M2(num2);
                    eatonGroupVoltageMib_M = new EatonGroupVoltageMib_M2(num2);
                    num = num2;
                }
                BankThreshold bankThreshold = dictionary[num2];
                if (current.StartsWith(eatonGroupEntryMib_M.GroupName))
                {
                    bankThreshold.BankName = (text.Equals(System.Convert.ToString(-1000000)) ? string.Empty : text);
                }
                else
                {
                    if (current.StartsWith(eatonGroupCurrentMib_M.MinCurrentMt))
                    {
                        bankThreshold.MinCurrentMt = (float)System.Convert.ToInt32(text) / 1000f;
                    }
                    else
                    {
                        if (current.StartsWith(eatonGroupCurrentMib_M.MaxCurrentMT))
                        {
                            bankThreshold.MaxCurrentMT = (float)System.Convert.ToInt32(text) / 1000f;
                        }
                        else
                        {
                            if (current.StartsWith(eatonGroupVoltageMib_M.MinVoltageMt))
                            {
                                bankThreshold.MinVoltageMT = (float)System.Convert.ToInt32(text) / 1000f;
                            }
                            else
                            {
                                if (!current.StartsWith(eatonGroupVoltageMib_M.MaxVoltageMT))
                                {
                                    return(new System.Collections.Generic.Dictionary <int, BankThreshold>());
                                }
                                bankThreshold.MaxVoltageMT = (float)System.Convert.ToInt32(text) / 1000f;
                            }
                        }
                    }
                }
                if (bankThreshold.MinCurrentMt == -500f)
                {
                    bankThreshold.MinCurrentMt = -300f;
                }
                if (bankThreshold.MinPowerMT == -500f)
                {
                    bankThreshold.MinPowerMT = -300f;
                }
            }
            return(dictionary);
        }
Ejemplo n.º 38
0
        private bool processBIORADFile(string fileName, Guid rotationId, Plate plate, out bool isRightPositionNumber)
        {
            isRightPositionNumber = true;
            string formatTitle   = "Well,Fluor,Target,Content,Sample,Cq,Starting Quantity (SQ)";
            bool   isRightFormat = false;

            System.Collections.Generic.Dictionary <string, BIORADPCRColumnData> dataList = new System.Collections.Generic.Dictionary <string, BIORADPCRColumnData>();

            using (FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    while (!reader.EndOfStream)
                    {
                        string content = reader.ReadLine();
                        if (isRightFormat)
                        {
                            string[] values = content.Split(',');
                            if (values.Count() < 6)
                            {
                                break;
                            }
                            BIORADPCRColumnData bioData = new BIORADPCRColumnData();
                            bioData.Well       = values[0];
                            bioData.Fluor      = values[1];
                            bioData.Cq         = values[5];
                            bioData.XmlContent = "<Well>" + values[0] + "</Well><Fluor>" + values[1] + "</Fluor><Cq>" + values[5] + "</Cq>";

                            if (!dataList.ContainsKey(bioData.Well))
                            {
                                dataList.Add(bioData.Well, bioData);
                            }
                            else
                            {
                                BIORADPCRColumnData _bioData = (BIORADPCRColumnData)dataList[bioData.Well];
                                if (_bioData.DataList == null)
                                {
                                    _bioData.DataList = new List <PCRColumnData>();
                                    _bioData.DataList.Add(bioData);
                                }
                                else
                                {
                                    _bioData.DataList.Add(bioData);
                                }
                            }
                        }

                        if (!isRightFormat && content.StartsWith(formatTitle))
                        {
                            isRightFormat = true;
                        }
                    }
                }
            }

            if (!isRightFormat)
            {
                return(isRightFormat);
            }

            Dictionary <int, DataRow> dc = controller.GetPCRPositionsByPlateID(plate.PlateID, currentExperimentId);

            if (dc.Count != dataList.Count)
            {
                isRightPositionNumber = false;
                if (!isRightPositionNumber)
                {
                    MessageBoxResult selectResult = MessageBox.Show("PCR仪检测结果和混样数不一致,请检查操作是否正确?“是”将按现有规则导入", "系统提示", MessageBoxButton.YesNo);
                    if (selectResult == MessageBoxResult.No)
                    {
                        return(isRightFormat);
                    }
                    else
                    {
                        isRightPositionNumber = true;
                    }
                }
            }

            foreach (BIORADPCRColumnData bioData in dataList.Values)
            {
                PCRTestResult info = new PCRTestResult();
                info.ItemID     = WanTaiObjectService.NewSequentialGuid();
                info.RotationID = rotationId;
                info.Position   = controller.ChangeCharacterToPositionNumber(bioData.Well);
                info.CreateTime = DateTime.Now;
                //calculate
                if (dc.ContainsKey(info.Position))
                {
                    DataRow  row      = dc[info.Position];
                    bool     isSingle = (int)row["TubeNumber"] == 1 ? true : false;
                    Tubetype tubeType = (Tubetype)((short)row["TubeType"]);
                    info.Result = checkPCRResult(bioData, row["TestName"].ToString(), isSingle, tubeType);
                }

                info.ExperimentID = currentExperimentId;
                if (plate.BarCode != null)
                {
                    info.BarCode = plate.BarCode;
                }

                info.PlateID = plate.PlateID;
                string xmlContent = bioData.XmlContent;
                if (bioData.DataList != null && bioData.DataList.Count > 0)
                {
                    foreach (BIORADPCRColumnData data in bioData.DataList)
                    {
                        xmlContent = xmlContent + data.XmlContent;
                    }
                }
                info.PCRContent = "<PCRContent>" + xmlContent + "</PCRContent>";
                pcrResultList.Add(info);
            }

            return(isRightFormat);
        }
Ejemplo n.º 39
0
 public override bool ContainsKey(object key)
 {
     return(Data.ContainsKey(key));
 }
Ejemplo n.º 40
0
        private bool processStratageneFile(string fileName, Guid rotationId, Plate plate, out bool isRightPositionNumber)
        {
            isRightPositionNumber = true;
            OleDbConnectionStringBuilder connectionStringBuilder = new OleDbConnectionStringBuilder();

            connectionStringBuilder.Provider   = "Microsoft.Jet.OLEDB.4.0";
            connectionStringBuilder.DataSource = fileName;
            connectionStringBuilder.Add("Mode", "Read");
            connectionStringBuilder.Add("Extended Properties", "Excel 8.0;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text");
            bool isRightFormat = false;
            bool hasWellColumn = false;
            bool hasDyeColumn  = false;
            bool hasCtColumn   = false;

            using (OleDbConnection con = new OleDbConnection(connectionStringBuilder.ToString()))
            {
                con.Open();
                DataTable dtSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                string    Sheet1   = dtSchema.Rows[0].Field <string>("TABLE_NAME");

                DataTable sheetColumns = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, Sheet1, null });
                foreach (DataRow row in sheetColumns.Rows)
                {
                    string strColumnName = row["COLUMN_NAME"].ToString();
                    if (strColumnName == "Well")
                    {
                        hasWellColumn = true;
                    }
                    else if (strColumnName == "Dye")
                    {
                        hasDyeColumn = true;
                    }
                    if (strColumnName == "Ct (dR)")
                    {
                        hasCtColumn = true;
                    }
                }

                if (hasWellColumn && hasDyeColumn && hasCtColumn)
                {
                    isRightFormat = true;
                }

                if (!isRightFormat)
                {
                    return(isRightFormat);
                }

                OleDbDataAdapter da = new OleDbDataAdapter("select [Well],[Dye],[Ct (dR)] from [" + Sheet1 + "]", con);
                DataTable        dt = new DataTable();
                da.Fill(dt);
                Dictionary <int, DataRow> dc = controller.GetPCRPositionsByPlateID(plate.PlateID, currentExperimentId);
                System.Collections.Generic.Dictionary <string, StratagenePCRColumnData> dataList = new System.Collections.Generic.Dictionary <string, StratagenePCRColumnData>();

                foreach (DataRow row in dt.Rows)
                {
                    StratagenePCRColumnData sData = new StratagenePCRColumnData()
                    {
                        Well = row[0].ToString(), Dye = row[1].ToString(), Ct = row[2].ToString()
                    };
                    sData.XmlContent = "<Well>" + sData.Well + "</Well><Dye>" + sData.Dye + "</Dye><Ct>" + sData.Ct + "</Ct>";
                    if (!dataList.ContainsKey(sData.Well))
                    {
                        dataList.Add(sData.Well, sData);
                    }
                    else
                    {
                        StratagenePCRColumnData _sData = (StratagenePCRColumnData)dataList[sData.Well];
                        if (_sData.DataList == null)
                        {
                            _sData.DataList = new List <PCRColumnData>();
                            _sData.DataList.Add(sData);
                        }
                        else
                        {
                            _sData.DataList.Add(sData);
                        }
                    }
                }

                if (dc.Count != dataList.Count)
                {
                    isRightPositionNumber = false;
                    if (!isRightPositionNumber)
                    {
                        MessageBoxResult selectResult = MessageBox.Show("PCR仪检测结果和混样数不一致,请检查操作是否正确?“是”将按现有规则导入", "系统提示", MessageBoxButton.YesNo);
                        if (selectResult == MessageBoxResult.No)
                        {
                            return(isRightFormat);
                        }
                        else
                        {
                            isRightPositionNumber = true;
                        }
                    }
                }

                foreach (StratagenePCRColumnData sData in dataList.Values)
                {
                    PCRTestResult info = new PCRTestResult();
                    info.ItemID     = WanTaiObjectService.NewSequentialGuid();
                    info.RotationID = rotationId;
                    info.Position   = controller.ChangeCharacterToPositionNumber(sData.Well);
                    info.CreateTime = DateTime.Now;

                    //calculate
                    if (dc.ContainsKey(info.Position))
                    {
                        DataRow  dcrow    = dc[info.Position];
                        bool     isSingle = (int)dcrow["TubeNumber"] == 1 ? true : false;
                        Tubetype tubeType = (Tubetype)((short)dcrow["TubeType"]);
                        info.Result = checkPCRResult(sData, dcrow["TestName"].ToString(), isSingle, tubeType);
                    }

                    info.ExperimentID = currentExperimentId;
                    if (plate.BarCode != null)
                    {
                        info.BarCode = plate.BarCode;
                    }

                    info.PlateID = plate.PlateID;
                    string xmlContent = sData.XmlContent;
                    if (sData.DataList != null && sData.DataList.Count > 0)
                    {
                        foreach (StratagenePCRColumnData data in sData.DataList)
                        {
                            xmlContent = xmlContent + data.XmlContent;
                        }
                    }
                    info.PCRContent = "<PCRContent>" + xmlContent + "</PCRContent>";
                    pcrResultList.Add(info);
                }
            }

            return(isRightFormat);
        }
Ejemplo n.º 41
0
        private static VLogger _log = VLogger.GetVLogger(typeof(MIndex).FullName);          //.class);

        public static MIndex[] GetResults(String query, Ctx ctx, Trx trxName)
        {
            String sql = "SELECT * FROM K_Index WHERE K_Index_ID IN (" +
                         "SELECT MAX(K_Index_ID) FROM K_Index WHERE " +
                         "Keyword LIKE @param GROUP BY AD_Table_ID, Record_ID)";

            System.Collections.Generic.Dictionary <int, MIndex> tTable = new System.Collections.Generic.Dictionary <int, MIndex>();
            SqlParameter[] param = new SqlParameter[1];
            IDataReader    idr   = null;

            try
            {
                // First lookup full word
                //pstmt = DataBase.prepareStatement (sql, trxName);
                //pstmt.setString (1, query.toUpperCase ());
                param[0] = new SqlParameter("@param", query.ToUpper());
                idr      = DataBase.DB.ExecuteReader(sql, param, trxName);
                while (idr.Read())
                {
                    MIndex tIndex = new MIndex(ctx, idr, trxName);
                    tTable.Add(tIndex.Get_ID(), tIndex);
                }
                idr.Close();
                // Second lookup with appended %
                //pstmt = DataBase.prepareStatement (sql, trxName);
                //pstmt.setString (1, query.toUpperCase () + "%");
                param[0] = new SqlParameter("@param", query.ToUpper() + "%");
                idr      = DataBase.DB.ExecuteReader(sql, param, trxName);
                while (idr.Read())
                {
                    MIndex tIndex = new MIndex(ctx, idr, trxName);
                    if (!tTable.ContainsKey(tIndex.Get_ID()))
                    {
                        tTable.Add(tIndex.Get_ID(), tIndex);
                    }
                }
                idr.Close();
                // Third lookup with prefix% and appended %
                //pstmt = DataBase.prepareStatement (sql, trxName);
                //pstmt.setString (1, "%" + query.toUpperCase () + "%");
                param[0] = new SqlParameter("@param", "%" + query.ToUpper() + "%");
                idr      = DataBase.DB.ExecuteReader(sql, param, trxName);
                while (idr.Read())
                {
                    MIndex tIndex = new MIndex(ctx, idr, trxName);
                    if (!tTable.ContainsKey(tIndex.Get_ID()))
                    {
                        tTable.Add(tIndex.Get_ID(), tIndex);
                    }
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                _log.Log(Level.SEVERE, "getResults", e);
            }

            // Log the search and the number of results
            MIndexLog thisLog = new MIndexLog(ctx, 0, trxName);

            thisLog.SetIndexQuery(query);
            thisLog.SetIndexQueryResult(tTable.Count);
            thisLog.SetQuerySource(X_K_IndexLog.QUERYSOURCE_CollaborationManagement);
            thisLog.Save();

            MIndex [] entries = new MIndex [tTable.Count];
            //Enumeration E = tTable.keys ();
            System.Collections.IEnumerator E = tTable.Keys.GetEnumerator();
            int i = 0;

            while (E.MoveNext())
            {
                entries[i++] = tTable[Utility.Util.GetValueOfInt(E.Current)];
            }
            return(entries);
        }
Ejemplo n.º 42
0
        public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
        {
            _errorCount = 0;

            var sb = new StringBuilder();

            lines.ForEach(line => sb.AppendLine(line));
            var xml = new XmlDocument();

            xml.LoadXml(sb.ToString().Trim());

            var nsmgr = new XmlNamespaceManager(xml.NameTable);

            nsmgr.AddNamespace("ttaf1", xml.DocumentElement.NamespaceURI);

            XmlNode div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).SelectSingleNode("ttaf1:div", nsmgr);

            if (div == null)
            {
                div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).FirstChild;
            }

            var styleDic = new System.Collections.Generic.Dictionary <string, string>();

            foreach (XmlNode node in xml.DocumentElement.SelectNodes("//ttaf1:style", nsmgr))
            {
                if (node.Attributes["tts:fontStyle"] != null && node.Attributes["xml:id"] != null)
                {
                    styleDic.Add(node.Attributes["xml:id"].Value, node.Attributes["tts:fontStyle"].Value);
                }
            }

            foreach (XmlNode node in div.ChildNodes)
            {
                try
                {
                    var pText = new StringBuilder();
                    foreach (XmlNode innerNode in node.ChildNodes)
                    {
                        switch (innerNode.Name)
                        {
                        case "br":
                            pText.AppendLine();
                            break;

                        case "span":
                            bool italic = false;
                            if (innerNode.Attributes["style"] != null && styleDic.ContainsKey(innerNode.Attributes["style"].Value))
                            {
                                if (styleDic[innerNode.Attributes["style"].Value].Contains("italic"))
                                {
                                    italic = true;
                                    pText.Append("<i>");
                                }
                            }
                            if (!italic && innerNode.Attributes != null)
                            {
                                var fs = innerNode.Attributes.GetNamedItem("tts:fontStyle");
                                if (fs != null && fs.Value == "italic")
                                {
                                    italic = true;
                                    pText.Append("<i>");
                                }
                            }
                            if (innerNode.HasChildNodes)
                            {
                                foreach (XmlNode innerInnerNode in innerNode.ChildNodes)
                                {
                                    if (innerInnerNode.Name == "br")
                                    {
                                        pText.AppendLine();
                                    }
                                    else
                                    {
                                        pText.Append(innerInnerNode.InnerText);
                                    }
                                }
                            }
                            else
                            {
                                pText.Append(innerNode.InnerText);
                            }
                            if (italic)
                            {
                                pText.Append("</i>");
                            }
                            break;

                        default:
                            pText.Append(innerNode.InnerText);
                            break;
                        }
                    }
                    string start = node.Attributes["begin"].InnerText;
                    string text  = pText.ToString();
                    text = text.Replace(Environment.NewLine + "</i>", "</i>" + Environment.NewLine);
                    text = text.Replace("<i></i>", string.Empty);
                    if (node.Attributes["end"] != null)
                    {
                        string end = node.Attributes["end"].InnerText;
                        double dBegin, dEnd;
                        if (!start.Contains(":") && Utilities.CountTagInText(start, ".") == 1 && !start.Contains(":") && Utilities.CountTagInText(start, ".") == 1 &&
                            double.TryParse(start, out dBegin) && double.TryParse(end, out dEnd))
                        {
                            subtitle.Paragraphs.Add(new Paragraph(text, dBegin * 1000.0, dEnd * 1000.0));
                        }
                        else
                        {
                            if (start.Length == 8 && start[2] == ':' && start[5] == ':' &&
                                end.Length == 8 && end[2] == ':' && end[5] == ':')
                            {
                                Paragraph p     = new Paragraph();
                                string[]  parts = start.Split(new[] { ':' });
                                p.StartTime = new TimeCode(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), 0);
                                parts       = end.Split(new[] { ':' });
                                p.EndTime   = new TimeCode(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), 0);
                                p.Text      = text;
                                subtitle.Paragraphs.Add(p);
                            }
                            else
                            {
                                subtitle.Paragraphs.Add(new Paragraph(TimedText10.GetTimeCode(start, false), TimedText10.GetTimeCode(end, false), text));
                            }
                        }
                    }
                    else if (node.Attributes["dur"] != null)
                    {
                        TimeCode duration  = TimedText10.GetTimeCode(node.Attributes["dur"].InnerText, false);
                        TimeCode startTime = TimedText10.GetTimeCode(start, false);
                        TimeCode endTime   = new TimeCode(TimeSpan.FromMilliseconds(startTime.TotalMilliseconds + duration.TotalMilliseconds));
                        subtitle.Paragraphs.Add(new Paragraph(startTime, endTime, text));
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    _errorCount++;
                }
            }
            subtitle.Renumber(1);
        }
        public string ConvertMarkdownToHTML(string markdown)
        {
            if (!NetworkUtilities.IsNetworkAvailable())
            {
                return("<strong>" + LocalizationProvider.GetLocalizedString("Error_NoNetworkConnection", false, "MarkdownPadStrings") + "</strong>");
            }
            IAuthenticator authenticator = null;

            if (!this._settings.Markdown_GFM_AnonymousMode)
            {
                authenticator = new HttpBasicAuthenticator(this._settings.Markdown_GFM_Username, SettingsProvider.DecryptString(this._settings.Markdown_GFM_Password).ToInsecureString());
            }
            RestClient restClient = new RestClient
            {
                BaseUrl       = "https://api.github.com",
                Authenticator = authenticator,
                Proxy         = WebRequest.DefaultWebProxy
            };
            RestRequest restRequest = new RestRequest
            {
                Resource      = "markdown",
                RequestFormat = RestSharp.DataFormat.Json,
                Method        = Method.POST
            };

            restRequest.AddBody(new
            {
                text = markdown,
                mode = "gfm"
            });
            IRestResponse restResponse = restClient.Execute(restRequest);

            try
            {
                this.CheckResponse(restResponse);
            }
            catch (RestResponseException ex)
            {
                GitHubFlavoredMarkdownProcessor._logger.ErrorException("GFM RestResponseException", ex);
                string text = string.Empty;
                if (ex.Response == null)
                {
                    GitHubFlavoredMarkdownProcessor._logger.ErrorException("GFM RestResponseException: Response was null", ex);
                    text = ex.Message;
                }
                else
                {
                    if (ex.Response.ErrorException != null)
                    {
                        GitHubFlavoredMarkdownProcessor._logger.ErrorException("GFM RestResponseException: Response was not null, and an Response ErrorException was present.", ex.Response.ErrorException);
                        text = ex.Response.ErrorMessage;
                    }
                    else
                    {
                        GitHubFlavoredMarkdownProcessor._logger.ErrorException("GFM RestResponseException: Error message received from GFM API, deserializing JSON...\n" + ex.Response, ex);
                        try
                        {
                            JsonDeserializer jsonDeserializer = new JsonDeserializer();
                            System.Collections.Generic.Dictionary <string, string> dictionary = jsonDeserializer.Deserialize <System.Collections.Generic.Dictionary <string, string> >(ex.Response);
                            if (dictionary.ContainsKey("message"))
                            {
                                HttpStatusCode statusCode        = ex.Response.StatusCode;
                                string         statusDescription = ex.Response.StatusDescription;
                                string         arg = dictionary["message"];
                                text = string.Format("{0} ({1}): {2}", statusCode, statusDescription, arg);
                                string text2 = text;
                                text = string.Concat(new string[]
                                {
                                    text2,
                                    "<br /><br />",
                                    LocalizationProvider.GetLocalizedString("Error_GitHubFlavoredMarkdownMessage2", false, "MarkdownPadStrings"),
                                    "<br /><h4>Technical Details</h4><pre><code>",
                                    ex.Response.Content,
                                    "</code></pre>"
                                });
                            }
                        }
                        catch (System.Runtime.Serialization.SerializationException ex2)
                        {
                            GitHubFlavoredMarkdownProcessor._logger.ErrorException("GFM: Error deserializing error", ex2);
                            text = string.Concat(new object[]
                            {
                                LocalizationProvider.GetLocalizedString("Gfm_Error_UnexpectedErrorResponse", false, "MarkdownPadStrings"),
                                "<br /><br /><h4>Technical Details</h4><pre><code>",
                                ex,
                                "</code></pre><br /><pre><code>",
                                ex.Response.Content,
                                "</code></pre><br /><pre><code>",
                                ex2,
                                "</code></pre>"
                            });
                        }
                    }
                }
                return(string.Concat(new string[]
                {
                    "<p>",
                    LocalizationProvider.GetLocalizedString("Error_GitHubFlavoredMarkdownMessage1", false, "MarkdownPadStrings"),
                    "</p><p><strong>",
                    text,
                    "</strong></p><p>",
                    LocalizationProvider.GetLocalizedString("IfBugPersists", false, "MarkdownPadStrings"),
                    "</p>"
                }));
            }
            return(restResponse.Content);
        }
Ejemplo n.º 44
0
        internal override Expression ResolveNames(Parser parser, System.Collections.Generic.Dictionary <string, Executable> lookup, string[] imports)
        {
            FunctionDefinition funcDef; // used in multiple places.
            FieldDeclaration   fieldDec;

            this.Root = this.Root.ResolveNames(parser, lookup, imports);
            Expression root  = this.Root;
            string     field = this.StepToken.Value;

            if (root is PartialNamespaceReference)
            {
                // already a fully qualified namespace, therefore imports don't matter.
                string fullyQualifiedName = ((PartialNamespaceReference)root).Name + "." + field;
                if (lookup.ContainsKey(fullyQualifiedName))
                {
                    return(Resolver.ConvertStaticReferenceToExpression(lookup[fullyQualifiedName], this.FirstToken, this.FunctionOrClassOwner));
                }

                throw new ParserException(this.FirstToken, "Could not find class or function by the name of: '" + fullyQualifiedName + "'");
            }

            if (root is ClassReference)
            {
                ClassDefinition cd = ((ClassReference)root).ClassDefinition;

                funcDef = cd.GetMethod(field, false);
                if (funcDef != null)
                {
                    if (!funcDef.IsStaticMethod)
                    {
                        string className    = cd.NameToken.Value;
                        string functionName = funcDef.NameToken.Value;

                        throw new ParserException(this.DotToken, "'" + className + "." + functionName + "' is not a static method, but it is being used as though it is static.");
                    }

                    return(new FunctionReference(this.FirstToken, funcDef, this.FunctionOrClassOwner));
                }

                fieldDec = cd.GetField(field, false);
                if (fieldDec != null)
                {
                    if (!fieldDec.IsStaticField)
                    {
                        throw new ParserException(this.DotToken, "Cannot make a static reference to a non-static field.");
                    }

                    return(new FieldReference(this.FirstToken, fieldDec, this.FunctionOrClassOwner));
                }

                // TODO: nested classes, enums, constants

                // TODO: show spelling suggestions.
                throw new ParserException(this.StepToken, "No static fields or methods named '" + field + "' on the class " + cd.NameToken.Value + ".");
            }

            if (root is BaseKeyword)
            {
                ClassDefinition thisClass = null;
                if (this.FunctionOrClassOwner != null)
                {
                    if (this.FunctionOrClassOwner is FunctionDefinition)
                    {
                        thisClass = this.FunctionOrClassOwner.FunctionOrClassOwner as ClassDefinition;
                    }
                    else
                    {
                        thisClass = this.FunctionOrClassOwner as ClassDefinition;
                    }
                }

                if (thisClass == null)
                {
                    throw new ParserException(root.FirstToken, "'base' keyword can only be used inside classes.");
                }

                ClassDefinition cd = thisClass.BaseClass;
                if (cd == null)
                {
                    throw new ParserException(root.FirstToken, "'base' keyword can only be used inside classes that extend from another class.");
                }

                FunctionDefinition fd = cd.GetMethod(field, true);
                if (fd == null)
                {
                    throw new ParserException(this.DotToken, "Cannot find a method by that name in the base class chain.");
                }

                if (fd.IsStaticMethod)
                {
                    throw new ParserException(this.DotToken, "Cannot reference static methods using 'base' keyword.");
                }

                return(new BaseMethodReference(this.FirstToken, this.DotToken, this.StepToken, this.FunctionOrClassOwner));
            }

            if (root is ThisKeyword)
            {
                ClassDefinition cd = null;
                if (this.FunctionOrClassOwner != null)
                {
                    if (this.FunctionOrClassOwner is FunctionDefinition)
                    {
                        funcDef = this.FunctionOrClassOwner as FunctionDefinition;
                        if (funcDef.IsStaticMethod)
                        {
                            throw new ParserException(this.Root.FirstToken, "'this' keyword cannot be used in static methods.");
                        }
                        cd = funcDef.FunctionOrClassOwner as ClassDefinition;
                        if (cd == null)
                        {
                            throw new ParserException(this.Root.FirstToken, "'this' keyword must be used inside a class.");
                        }
                    }
                    else if (this.FunctionOrClassOwner is ClassDefinition)
                    {
                        cd = (ClassDefinition)this.FunctionOrClassOwner;
                    }
                }

                if (cd == null)
                {
                    throw new ParserException(this.Root.FirstToken, "'this' keyword is not allowed here.");
                }

                funcDef = cd.GetMethod(field, true);
                if (funcDef != null)
                {
                    if (funcDef.IsStaticMethod)
                    {
                        throw new ParserException(this.DotToken, "This method is static and must be referenced by the class name, not 'this'.");
                    }
                    return(new FunctionReference(this.FirstToken, funcDef, this.FunctionOrClassOwner));
                }

                FieldDeclaration fieldDef = cd.GetField(field, true);
                if (fieldDef != null)
                {
                    if (fieldDef.IsStaticField)
                    {
                        throw new ParserException(this.DotToken, "This field is static and must be referenced by the class name, not 'this'.");
                    }

                    return(new FieldReference(this.FirstToken, fieldDef, this.FunctionOrClassOwner));
                }

                // TODO: show suggestions in the error message for anything close to what was typed.
                throw new ParserException(this.StepToken, "The class '" + cd.NameToken.Value + "' does not have a field named '" + field + "'.");
            }

            return(this);
        }
        public virtual void SetObjects(uint count, object[] punk)
        {
            if (punk == null)
                return;

            if(count > 0)
            {
                if(punk[0] is ProjectConfig)
                {
                    ArrayList configs = new ArrayList();

                    for(int i = 0; i < count; i++)
                    {
                        ProjectConfig config = (ProjectConfig)punk[i];

                        if(this.project == null || (this.project != (punk[0] as ProjectConfig).ProjectMgr))
                        {
                            this.project = config.ProjectMgr;
                        }

                        configs.Add(config);
                    }

                    this.projectConfigs = (ProjectConfig[])configs.ToArray(typeof(ProjectConfig));
                }
                else if(punk[0] is NodeProperties)
                {
                    if (this.project == null || (this.project != (punk[0] as NodeProperties).Node.ProjectMgr))
                        this.project = (punk[0] as NodeProperties).Node.ProjectMgr;

                    System.Collections.Generic.Dictionary<string, ProjectConfig> configsMap = new System.Collections.Generic.Dictionary<string, ProjectConfig>();

                    for(int i = 0; i < count; i++)
                    {
                        NodeProperties property = (NodeProperties)punk[i];
                        IVsCfgProvider provider;
                        ErrorHandler.ThrowOnFailure(property.Node.ProjectMgr.GetCfgProvider(out provider));
                        uint[] expected = new uint[1];
                        ErrorHandler.ThrowOnFailure(provider.GetCfgs(0, null, expected, null));
                        if(expected[0] > 0)
                        {
                            ProjectConfig[] configs = new ProjectConfig[expected[0]];
                            uint[] actual = new uint[1];
                            ErrorHandler.ThrowOnFailure(provider.GetCfgs(expected[0], configs, actual, null));

                            foreach(ProjectConfig config in configs)
                            {
                                if(!configsMap.ContainsKey(config.ConfigName))
                                {
                                    configsMap.Add(config.ConfigName, config);
                                }
                            }
                        }
                    }

                    if(configsMap.Count > 0)
                    {
                        if(this.projectConfigs == null)
                        {
                            this.projectConfigs = new ProjectConfig[configsMap.Keys.Count];
                        }
                        configsMap.Values.CopyTo(this.projectConfigs, 0);
                    }
                }
            }
            else
            {
                this.project = null;
            }

            if(this.active && this.project != null)
            {
                UpdateObjects();
            }
        }
Ejemplo n.º 46
0
        static void _Initialize()
        {
            lock (_Cached)
            {
                if (_CachePoller != null)
                {
                    return;
                }

                foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
                {
                    try
                    {
                        if (!_Evaluated.ContainsKey(asm.Location))
                        {
                            _Evaluated[asm.Location] = File.GetLastWriteTimeUtc(asm.Location);
                        }
                        else
                        {
                            continue;
                        }

                        AssemblyName aName = new AssemblyName(asm.FullName);

                        lock (_AssemblyByName)
                            _AssemblyByName[aName] = asm;

                        if (!_Cached.Contains(System.IO.Path.Combine(STEM.Sys.IO.Path.GetDirectoryName(asm.Location), TransformFilename(asm.Location)).ToUpper(System.Globalization.CultureInfo.CurrentCulture)))
                        {
                            _Cached.Add(System.IO.Path.Combine(STEM.Sys.IO.Path.GetDirectoryName(asm.Location), TransformFilename(asm.Location)).ToUpper(System.Globalization.CultureInfo.CurrentCulture));
                            _CachedAssemblies[System.IO.Path.Combine(STEM.Sys.IO.Path.GetDirectoryName(asm.Location), TransformFilename(asm.Location))] = asm;
                        }

                        if (!_Cached.Contains(asm.Location.ToUpper(System.Globalization.CultureInfo.CurrentCulture)))
                        {
                            _Cached.Add(asm.Location.ToUpper(System.Globalization.CultureInfo.CurrentCulture));
                            _CachedAssemblies[asm.Location] = asm;
                        }
                    }
                    catch { }
                }

                List <FileInfo> infos = new List <FileInfo>();
                foreach (string file in STEM.Sys.IO.Directory.STEM_GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll|*.so|*.a|*.lib", false))
                {
                    infos.Add(new FileInfo(file));
                }

                foreach (FileInfo file in infos.OrderByDescending(i => i.LastWriteTimeUtc))
                {
                    if (!file.FullName.EndsWith("STEM.Auth.dll", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (!_Evaluated.ContainsKey(file.FullName.ToUpper(System.Globalization.CultureInfo.CurrentCulture)))
                        {
                            try
                            {
                                Assembly asm = Assembly.LoadFile(file.FullName);
                                _Evaluated[asm.Location] = File.GetLastWriteTimeUtc(asm.Location);
                            }
                            catch { }
                        }
                    }
                }

                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolve);
                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(AssemblyResolve);
                AppDomain.CurrentDomain.TypeResolve += new ResolveEventHandler(TypeResolve);

                if (_CachePoller == null)
                {
                    _CachePoller = new Thread(new ThreadStart(CachePoller));
                    _CachePoller.IsBackground = true;
                    _CachePoller.Start();
                }
            }
        }
Ejemplo n.º 47
0
 public bool ItemExists(int id)
 {
     return(items.ContainsKey(id) || itemsData.ContainsKey(id));
 }
Ejemplo n.º 48
0
        public ActionResult SaveOrder(Dokument dok)
        {
            if (!MusicStore.Models.Module.User.IsAuthenticated) return RedirectToAction("Index", "Home");
            if (MusicStore.Models.Module.User.GetCurrentRole() != MusicStore.Models.Module.User.Klient) return RedirectToAction("Index", "Home");

            DbModule module = DbModule.GetInstance();
            dok.DataZamowienia = DateTime.Now;
            dok.NumerDokumentu = Dokument.GetLastNumber();
            module.AddRow(dok);

            string[] koszyk = Request.Cookies["Cart"].Value.ToString().Split(',');
            var dict = new System.Collections.Generic.Dictionary<int, int>();

            if (!String.IsNullOrEmpty(Request.Cookies["Cart"].Value))
                foreach (string Ids in koszyk)
                {
                    int Id = int.Parse(Ids);
                    if (!dict.ContainsKey(Id))
                    {
                        dict.Add(Id, 1);
                    }
                    else
                    {
                        dict[Id] += 1;
                    }
                }

            var dict2 = new System.Collections.Generic.Dictionary<Album, int>();
            decimal wartosc = 0;
            string waluta = "";
            foreach (var obiekt in dict)
            {
                var album = module.Albumy.Where(x => x.Id == obiekt.Key).First();
                dict2.Add(album, obiekt.Value);
                wartosc += album.BruttoValue * obiekt.Value;

                if (waluta == "")
                {
                    waluta = album.BruttoSymbol;
                }
                else if (waluta != album.BruttoSymbol)
                {
                    waluta = "(Wiele walut)";
                    wartosc = 0;
                }
            }
            int lp = 1;
            foreach(var poz in dict2)
            {
                PozycjaDokumentu pozycja = new PozycjaDokumentu(dok);
                pozycja.AlbumName = poz.Key.Nazwa + " (" + poz.Key.Artysta.Nazwa + ")";
                pozycja.CenaBrutto = poz.Key.BruttoValue;
                pozycja.Ilosc = poz.Value;
                pozycja.Lp = lp;
                pozycja.State = RowState.Added;
                pozycja.Waluta = poz.Key.BruttoSymbol;

                module.AddRow(pozycja);

                var album = poz.Key;
                album.StanIlosc -= pozycja.Ilosc;
                module.Update(album);
                lp++;
            }
            ViewBag.NumerDokumentu = dok.NumerDokumentu;
            return View();
        }