Exemplo n.º 1
0
        private void HeaderMenuItem_Click(object sender, RoutedEventArgs e)
        {
            switch ((sender as MenuItem).Header as string)
            {
            case "新增":
                tapHeaderClear();
                break;

            case "修改":
                headerSelected = HeaderBox.SelectedIndex;
                if (headerSelected < 0)
                {
                    tapHeaderClear();
                    return;
                }
                var item = ViewModel.HeaderItems[headerSelected];
                HeaderTb.Text      = item.Name;
                HeaderValueTb.Text = item.Value;
                break;

            case "选中":
                var items = new HeaderItem[HeaderBox.SelectedItems.Count];
                HeaderBox.SelectedItems.CopyTo(items, 0);
                ListExtension.Remove(ViewModel.HeaderItems, items);
                break;

            case "全部":
                ViewModel.HeaderItems.Clear();
                break;

            default:
                break;
            }
        }
        public void compute(DateTime startDate, DateTime endDate, int steps = 40)
        {
            var tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
            var etfall    = stockMinutelyRepo.GetStockTransactionWithRedis(code, tradedays.First(), tradedays.Last());
            int duration  = 5;
            int minutes   = 240;

            //var distribution0 = getDistribution(etfall, 500, tradedays.Count()-1, 240);
            //ListToCSV.SaveDataToCSVFile<double>(distribution0, ListToCSV.CreateFile("E:\\result\\vd\\", "distribution"), "distribution");
            for (int i = steps + 1; i < tradedays.Count(); i++)
            {
                List <double> bigVolume         = new List <double>();
                int           endDateNum        = i - 1;
                int           startDateNum      = Math.Max((i - steps - 1), 0);
                var           distribution      = getDistribution(etfall, startDateNum, endDateNum, minutes);
                var           fluctuation       = getFluctuation(etfall, startDateNum, endDateNum, minutes, duration);
                var           distributionToday = getDistributionToday(etfall, distribution, i, minutes);
                for (int j = 0; j < minutes - duration; j++)
                {
                    if (distributionToday[j] - distribution[j] > 0.002)
                    {
                        bigVolume.Add((etfall[i * minutes + j + duration].Close / etfall[i * minutes + j].Close - 1));
                    }
                }
                var all   = ListExtension.mean(fluctuation);
                var today = ListExtension.mean(bigVolume);
                Console.WriteLine("Date:{0},all:{1},  today:{2}!", etfall[i * minutes].DateTime.Date.ToString(), Math.Round(all, 5), Math.Round(today, 5));
            }
        }
Exemplo n.º 3
0
        public void BubbleSortNotIComparableElementTest()
        {
            ObservableCollection <object> wordCountList = new ObservableCollection <object>();

            wordCountList.Add(new Object());
            wordCountList.Add(new WordCountInfo("test1", 1));
            wordCountList.Add(new WordCountInfo("test2", 2));
            ListExtension.BubbleSort(wordCountList);
        }
        /// <summary>
        /// Check if two EnumListContainers are equal
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            if (obj == null || obj.GetType() != this.GetType())
            {
                return(false);
            }

            return(ListExtension.ListsEquivalent(list, ((EnumListContainer <TEnum>)obj).list));
        }
Exemplo n.º 5
0
        public void BubbleSortNullElementTest()
        {
            ObservableCollection <IWordCountInfo> wordCountList = new ObservableCollection <IWordCountInfo>();

            wordCountList.Add(null);
            wordCountList.Add(new WordCountInfo("test1", 1));
            wordCountList.Add(new WordCountInfo("test2", 2));
            ListExtension.BubbleSort(wordCountList);
        }
Exemplo n.º 6
0
    void Start()
    {
        leftHand        = capsuleHandLeftPrefab.GetComponent <MyCapsuleHand>();
        rightHand       = capsuleHandRightPrefab.GetComponent <MyCapsuleHand>();
        expanDialSticks = expanDialSticksPrefab.GetComponent <ExpanDialSticks>();
        // Listen to events
        expanDialSticks.OnConnecting      += HandleConnecting;
        expanDialSticks.OnConnected       += HandleConnected;
        expanDialSticks.OnDisconnected    += HandleDisconnected;
        expanDialSticks.OnXAxisChanged    += HandleXAxisChanged;
        expanDialSticks.OnYAxisChanged    += HandleYAxisChanged;
        expanDialSticks.OnClickChanged    += HandleClickChanged;
        expanDialSticks.OnRotationChanged += HandleRotationChanged;
        expanDialSticks.OnPositionChanged += HandlePositionChanged;
        expanDialSticks.onHoldingChanged  += HandleHoldingChanged;
        expanDialSticks.onReachingChanged += HandleReachingChanged;

        connected = false;
        expanDialSticks.client_MqttConnect();

        // generate potential candidates
        candidates = new List <Vector2Int>();        //= Enumerable.Range(0, nbPins).ToList<int>();
        // get pins inside matrix only
        for (int i = 1; i < expanDialSticks.NbRows - 1; i++)
        {
            for (int j = 1; j < expanDialSticks.NbColumns - 1; j++)
            {
                candidates.Add(new Vector2Int(i, j));
            }
        }
        movingCandidates = new List <Vector3Int>();
        // Generate potential positions for selected candidates
        positionCandidates = new List <int>();
        for (int i = 0; i < nbPositionCandidate; i++)
        {
            positionCandidates.Add(i * stepPositionCandidate);
        }

        // generate trials

        trials = new List <int>();        //= Enumerable.Range(0, nbPins).ToList<int>();
        for (int i = 0; i < maxIconUnder; i++)
        {
            for (int j = 0; j < nbRepeat; j++)
            {
                trials.Add(i);
            }
        }
        ListExtension.Shuffle(trials);
        trials.Insert(0, 0);
        nbTrials    = trials.Count();
        toNextTrial = true;
    }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            MyList <int> list = new MyList <int>();

            list.Add(1);
            list.Add(-2);
            list.Add(10);
            int[] arrList = ListExtension.GetArray <int>(list);
            foreach (int element in arrList)
            {
                Console.WriteLine(element);
            }
            Console.ReadKey();
        }
Exemplo n.º 8
0
    /// <summary>
    /// Обновление списка ближайших достопримечательностей.
    /// </summary>
    private void UpdateNearList()
    {
        var landmarks = ListLandmarks.FindAll(a =>
                                              inputDevices.Latitude >= a.Latitude - ZoneRadius && inputDevices.Latitude <= a.Latitude + ZoneRadius &&
                                              inputDevices.Longitude >= a.Longitude - ZoneRadius && inputDevices.Longitude <= a.Longitude + ZoneRadius);

        SubstractNearLandmarks = ListExtension.GetSubstract(ListNearLandmarks, landmarks);

        SubstractNearLandmarks.AddRange(ListExtension.GetSubstract(landmarks, ListNearLandmarks));

        ListNearLandmarks = landmarks;

        OnListNearChanges.Invoke();
    }
Exemplo n.º 9
0
        public void BubbleSortTest()
        {
            ObservableCollection <object> wordCountList = new ObservableCollection <object>();
            WordCountInfo wc1 = new WordCountInfo("test1", 1);
            WordCountInfo wc2 = new WordCountInfo("test2", 2);
            WordCountInfo wc3 = new WordCountInfo("test3", 3);

            wordCountList.Add(wc1);
            wordCountList.Add(wc2);
            wordCountList.Add(wc3);
            ListExtension.BubbleSort(wordCountList);
            Assert.AreSame(wc1, wordCountList[2]);
            Assert.AreSame(wc2, wordCountList[1]);
            Assert.AreSame(wc3, wordCountList[0]);
        }
Exemplo n.º 10
0
        private void InputText_TextChanged(object sender, TextChangedEventArgs e)
        {
            string input = InputText.Text;

            firstfoundObjects.Clear();
            if (String.IsNullOrWhiteSpace(input))
            {
                return;
            }

            ListExtension.BubbleSortGameObjectLevenstein(foundObjects, input);
            for (int i = 0; i < foundObjects.Count && i < 10; ++i)
            {
                firstfoundObjects.Add(foundObjects[i]);
            }
        }
Exemplo n.º 11
0
    private void TriggerOverlay()
    {
        List <Vector2Int> unsafeCandidates = FindAllCandidatesAroundTarget(target);       //FindAllUnsafesUnderDistance(safetyDistance);

        if (currSubChanges.Count() <= unsafeCandidates.Count())
        {
            ListExtension.Shuffle(unsafeCandidates);
            diffCandidates = new List <Vector3Int>();
            for (int i = 0; i < currSubChanges.Count(); i++)
            {
                diffCandidates.Add(new Vector3Int(unsafeCandidates[i].x, unsafeCandidates[i].y, currSubChanges[i]));
            }

            // Output Control
            for (int i = 0; i < expanDialSticks.NbRows; i++)
            {
                for (int j = 0; j < expanDialSticks.NbColumns; j++)
                {
                    expanDialSticks.modelMatrix[i, j].CurrentFeedForwarded = 0;
                }
            }

            foreach (Vector3Int diffCandidate in diffCandidates)
            {
                expanDialSticks.modelMatrix[diffCandidate.x, diffCandidate.y].CurrentFeedForwarded = diffCandidate.z;
            }

            expanDialSticks.triggerSafetyChange();
            safeGuard.Freeze();
            DisplayInstructions("Tourner les cylindres arrêtés <b>du plus descendant au plus ascendant</b>.");

            string shapeChangeMsg = "SHAPE_CHANGE [";
            foreach (Vector3Int diffCandidate in diffCandidates)
            {
                shapeChangeMsg += " " + diffCandidate.ToString() + " ";
            }
            shapeChangeMsg += "]";
            expanDialSticks.client.Publish(MQTT_SYSTEM_RECORDER, System.Text.Encoding.UTF8.GetBytes(shapeChangeMsg), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);

            LogMetrics();
            overlayAppeared = true;
        }
        else
        {
            DisplayInstructions("Veuillez réessayer.");
        }
    }
Exemplo n.º 12
0
    void Start()
    {
        Curves = ListExtension.Shuffle <AnimationCurve>(Curves);
        for (int i = 0; i < Blossoms.Count; i++)
        {
            DOTweenPath path = Blossoms[i].GetComponent <DOTweenPath>();
            Tween       t    = path.GetTween();
            t.SetEase(Curves[i]);
            path.DOPause();
        }

        for (int i = 0; i < Blossoms.Count; i++)
        {
            DoneBlossoms.Add(false);
        }
        StartRace();
    }
Exemplo n.º 13
0
            /// <summary>
            /// Gets the first invalid number - where the previous numbers
            /// don't contain a pair that add up to it.
            /// </summary>
            /// <returns>The invalid number.</returns>
            public long GetInvalidNumber()
            {
                for (int i = preambleCount; i < numbers.Count; ++i)
                {
                    long number   = numbers[i];
                    var  preamble = numbers.GetRange(i - preambleCount, preambleCount);

                    bool isNumberValid = ListExtension.GetPairs <long>(preamble)
                                         .Count(x => x.Item1 + x.Item2 == number) != 0;

                    if (!isNumberValid)
                    {
                        return(number);
                    }
                }

                return(0);
            }
Exemplo n.º 14
0
        private void RuleMenuItem_Click(object sender, RoutedEventArgs e)
        {
            switch ((sender as MenuItem).Header as string)
            {
            case "选中":
                var items = new RuleGroupItem[RuleBox.SelectedItems.Count];
                RuleBox.SelectedItems.CopyTo(items, 0);
                ListExtension.Remove(ViewModel.RuleItems, items);
                break;

            case "全部":
                ViewModel.RuleItems.Clear();
                break;

            default:
                break;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Check if two IntListContainers are equal
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return(false);
            }

            if (obj.GetType() != GetType())
            {
                if (obj.GetType() == typeof(List <int>))
                {
                    return(ListExtension.ListsEquivalent(list, (List <int>)obj));
                }

                return(false);
            }

            return(ListExtension.ListsEquivalent(list, ((IntListContainer)obj).list));
        }
Exemplo n.º 16
0
    /// <summary>
    /// Отправление запроса к серверу и обновление списка достопримечательностей.
    /// </summary>
    /// <returns></returns>
    private IEnumerator UpdateList()
    {
        var url =
            $"http://ec2-18-188-47-246.us-east-2.compute.amazonaws.com/api/showanimation/{inputDevices.Latitude}/{inputDevices.Longitude}";

        using (var webRequest = UnityWebRequest.Get(url))
        {
            _timeLoading += Time.fixedDeltaTime;

            if (_timeLoading > 0.5f)
            {
                LoadingWindow.SetActive(true);
            }

            yield return(webRequest.SendWebRequest());

            _timeLoading = 0f;

            LoadingWindow.SetActive(false);

            if (webRequest.isNetworkError)
            {
                ErrorWindow.SetActive(true);
            }
            else
            {
                ErrorWindow.SetActive(false);
                var json = webRequest.downloadHandler.text;
                var list = JsonHelper.FromJson <Landmark>(json).ToList();

                SubstractLandmarks = ListExtension.GetSubstract(ListLandmarks, list);

                SubstractLandmarks.AddRange(ListExtension.GetSubstract(list, ListLandmarks));

                ListLandmarks = list;

                OnListChanges.Invoke();

                UpdateNearList();
                UpdateCity();
            }
        }
    }
Exemplo n.º 17
0
    private void UpdateMainList()
    {
        if (Server.ListLandmarks.Count == 0)
        {
            MainLandmarksBlock.SetActive(false);
            return;
        }

        MainLandmarksBlock.SetActive(true);

        ClearBlock(MainLandmarksBlock);

        var ost = ListExtension.GetSubstract(Server.ListNearLandmarks, Server.ListLandmarks);

        foreach (var landmark in ost)
        {
            AddButton(landmark, MainLandmarksBlock.transform);
        }
    }
Exemplo n.º 18
0
        void SpeakTo()
        {
            Data.CurrentEligibleConversations = ConversationData.CheckEligibleConversations();
            if (Data.CurrentEligibleConversations.Count < 1)
            {
                Debug.Log("NOTHING IS ELIGIBLE");
                return;
            }
            foreach (Conversation conversation in Data.SaidToday)
            {
                if (Data.CurrentEligibleConversations.Contains(conversation))
                {
                    Data.CurrentEligibleConversations.Remove(conversation);
                }
            }
            if (Data.CurrentEligibleConversations.Count < 1)
            {
                Data.SaidToday.Clear();
                Data.CurrentEligibleConversations = ConversationData.CheckEligibleConversations();
            }
            Data.CurrentEligibleConversations = ListExtension.Shuffle <Conversation>(Data.CurrentEligibleConversations);
            Data.CurrentEligibleConversations = Data.CurrentEligibleConversations.OrderByDescending(c => c.LookupInt("Priority")).ToList <Conversation>();
            Conversation picked = Data.CurrentEligibleConversations[0];

            Field field = picked.fields.Find(f => string.Equals(f.title, "SaidToday"));

            if (field != null)
            {
                field.value = "True";
            }

            field = picked.fields.Find(f => string.Equals(f.title, "SaidThisGame"));
            if (field != null)
            {
                field.value = "True";
            }

            Data.SaidToday.Add(picked);
            DialogueManager.StartConversation(picked.Title);
        }
Exemplo n.º 19
0
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            switch ((sender as MenuItem).Header as string)
            {
            case "新增":
                tapClear();
                break;

            case "修改":
                var item = ViewModel.RuleItems[RuleBox.SelectedIndex];
                ViewModel.SelectedIndex = RuleBox.SelectedIndex;
                PluginCb.SelectedIndex  = ViewModel.PluginIndexOf(item.Name);
                Param2Tb.Text           = item.Param2;
                Param1Tb.Text           = item.Param1;
                break;

            case "上移":
                ViewModel.MoveUp(RuleBox.SelectedIndex);
                break;

            case "下移":
                ViewModel.MoveDown(RuleBox.SelectedIndex);
                break;

            case "选中":
                var items = new RuleItem[RuleBox.SelectedItems.Count];
                RuleBox.SelectedItems.CopyTo(items, 0);
                ListExtension.Remove(ViewModel.RuleItems, items);
                break;

            case "全部":
                ViewModel.RuleItems.Clear();
                break;

            default:
                break;
            }
        }
Exemplo n.º 20
0
    private void GetSourcePath(object sender, RoutedEventArgs e)
    {
        FolderBrowserDialog sourcePath = new FolderBrowserDialog();
        DialogResult        result     = sourcePath.ShowDialog();
        string strSourcePath           = sourcePath.SelectedPath;

        SqSv1.srcPathList.Add(strSourcePath);

        DirectoryInfo dirInfo = new DirectoryInfo(strSourcePath);

        foreach (FileInfo f in dirInfo.GetFiles())
        {
            if (!ListExtension.Contains(f.Extension))
            {
                ListExtension.Add(f.Extension);
            }
        }

        for (int i = 0; i < ListExtension.Count; i++)
        {
            lstB1.Items.Add(ListExtension[i]);
        }
    }
        private List <Conversation> ShuffleConversations(List <Conversation> pList)
        {
            List <Conversation> conversationList = ListExtension.Shuffle <Conversation>(pList);

            return(conversationList);
        }
Exemplo n.º 22
0
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            GUILayout.Space(10);

            #region Inspector

            GUILayout.BeginVertical("Easy Build System - Parts Collection", "window", GUILayout.Height(10));

            GUILayout.BeginVertical("box");

            GUI.color = MainEditor.GetEditorColor;

            GUILayout.BeginHorizontal();

            GUILayout.Label("Parts Collection Settings", EditorStyles.boldLabel);

            #region Parts Collection Settings

            if (GUILayout.Button(Help ? "Hide Help" : "Show Help", GUILayout.Width(100)))
            {
                Help = !Help;
            }

            GUI.color = Color.white;

            GUILayout.EndHorizontal();

            if (Help)
            {
                EditorGUILayout.HelpBox("This component allows to store all the Parts Behaviour which will be used during the runtime by the Build Manager component.\n" +
                                        "Check that some elements of the list below does not contains the same ids.\n" +
                                        "You can consult the documentation to find more information about this feature.", MessageType.Info);

                GUI.color = MainEditor.GetEditorColor;

                if (GUILayout.Button("Open Documentation Link"))
                {
                    Application.OpenURL(Constants.DOCS_LINK);
                }

                GUI.color = Color.white;
            }

            GUI.enabled = false;

            EditorGUILayout.ObjectField("Script", target, typeof(BuilderBehaviour), true);

            GUI.enabled = true;

            GUILayout.BeginVertical();

            if (Target.Parts.Count == 0)
            {
                GUILayout.BeginHorizontal("box");

                GUI.color = new Color(1.5f, 1.5f, 0f);

                GUILayout.Label("The list does not contains of part(s).");

                GUI.color = Color.white;

                GUILayout.EndHorizontal();
            }
            else
            {
                GUILayout.BeginHorizontal();

                GUI.color = MainEditor.GetEditorColor;

                if (GUILayout.Button("Sort Alphabetically"))
                {
                    Target.Parts = Target.Parts.OrderBy(e => e.Name).ToList();
                }

                if (GUILayout.Button("Sort Numerically"))
                {
                    Target.Parts = Target.Parts.OrderBy(e => e.Id).ToList();
                }

                GUI.color = Color.white;

                GUILayout.EndHorizontal();

                ScrollPosition = EditorGUILayout.BeginScrollView(ScrollPosition, false, false, GUILayout.Height(150));

                try
                {
                    foreach (PartBehaviour Part in Target.Parts)
                    {
                        if (Part == null)
                        {
                            Target.Parts.Remove(Part);

                            EditorUtility.SetDirty(target);

                            return;
                        }

                        GUILayout.BeginHorizontal("box");

                        GUILayout.BeginVertical();

                        GUILayout.Space(2);

                        GUILayout.Label("[ID:" + Part.Id + "] " + Regex.Replace(Part.Name.ToString(), "([a-z])([A-Z])", "$1 $2"));

                        GUI.color = Color.white;

                        GUILayout.Space(2);

                        GUILayout.EndVertical();

                        if (GUILayout.Button("Up", GUILayout.Width(50)))
                        {
                            try
                            {
                                ListExtension.Move <PartBehaviour>(Target.Parts, Target.Parts.IndexOf(Part), ListExtension.MoveDirection.Up);
                            }
                            catch
                            {
                            }
                        }

                        if (GUILayout.Button("Down", GUILayout.Width(50)))
                        {
                            try
                            {
                                ListExtension.Move <PartBehaviour>(Target.Parts, Target.Parts.IndexOf(Part), ListExtension.MoveDirection.Down);
                            }
                            catch
                            {
                            }
                        }

                        GUI.color = MainEditor.GetEditorColor;

                        if (GUILayout.Button("Configure Part", GUILayout.Width(100)))
                        {
                            Selection.activeGameObject = Part.gameObject;
                        }

                        GUI.color = new Color(1.5f, 0, 0);

                        if (GUILayout.Button("Remove", GUILayout.Width(80)))
                        {
                            Target.Parts.Remove(Part);

                            EditorUtility.SetDirty(target);

                            return;
                        }

                        GUI.color = Color.white;

                        GUILayout.EndHorizontal();
                    }
                }
                catch { }

                GUILayout.Space(100);

                EditorGUILayout.EndScrollView();
            }

            try
            {
                GUILayout.BeginVertical("box");

                GUILayout.BeginVertical();

                GUILayout.BeginHorizontal();

                PrefabToAdd = (PartBehaviour)EditorGUILayout.ObjectField("Base Part :", PrefabToAdd, typeof(PartBehaviour), false);

                GUILayout.EndHorizontal();

                GUI.enabled = PrefabToAdd != null;

                GUI.color = MainEditor.GetEditorColor;

                if (GUILayout.Button("Add Part At List"))
                {
                    if (PrefabToAdd == null)
                    {
                        Debug.LogError("<b><color=cyan>[Easy Build System]</color></b> : Empty field.");
                        return;
                    }

                    if (Target.Parts.Contains(PrefabToAdd) == false)
                    {
                        Target.Parts.Add(PrefabToAdd);

                        PrefabToAdd = null;

                        EditorUtility.SetDirty(target);

                        Repaint();
                    }
                    else
                    {
                        Debug.LogError("<b><color=cyan>[Easy Build System]</color></b> : This part already exists in the collection.");
                    }
                }

                GUI.color = Color.white;

                GUI.enabled = true;

                GUI.color = new Color(1.5f, 1.5f, 0);

                if (GUILayout.Button("Clear All Part(s) List"))
                {
                    if (EditorUtility.DisplayDialog("Easy Build System - Information", "Do you want remove all the part(s) from the collection ?", "Ok", "Cancel"))
                    {
                        Target.Parts.Clear();

                        Debug.Log("<b><color=cyan>[Easy Build System]</color></b> : The collection has been clear !.");
                    }
                }

                GUI.color = Color.white;

                GUILayout.EndVertical();

                GUILayout.EndVertical();
            }
            catch { }

            GUILayout.Space(3);

            GUILayout.EndVertical();

            #endregion Parts Collection Settings

            GUILayout.EndVertical();

            GUILayout.EndVertical();

            #endregion Inspector

            serializedObject.ApplyModifiedProperties();

            GUILayout.Space(10);
        }
Exemplo n.º 23
0
 public void ShuffleSymbols()
 {
     ListExtension.Shuffle <Symbol>(m_RandomSymbols);
 }
Exemplo n.º 24
0
    private void TriggerNextTrial()
    {
        if (trials.Count() > 0)
        {
            List <Vector3Int> unsafes;
            List <Vector3Int> safes;
            //Vector2Int rightCandidatePosition = new Vector2Int(rightCandidate.x, rightCandidate.y);
            bool candidatesFound = false;
            int  iconFactorIndex = -1;
            while (!candidatesFound)
            {
                iconFactorIndex++;
                if (iconFactorIndex < trials.Count())
                {
                    currIconUnder = trials[iconFactorIndex];
                    Debug.Log("Looking for candidates (" + currIconUnder + ")...");

                    // get all pins under and around user body
                    unsafes = FindAllUnsafesUnderDistance(safetyDistance);
                    safes   = FindAllSafesAboveDistance(safetyDistance);

                    // prevent same candidates
                    unsafes.RemoveAll(x => movingCandidates.Contains(x));
                    safes.RemoveAll(x => movingCandidates.Contains(x));
                    // candidates to find under or above
                    int nbUnderCandidates  = currIconUnder;
                    int nbAroundCandidates = maxIconUnder - currIconUnder;
                    Predicate <Vector3Int> hasPotentialRightCandidate = candidate => Math.Abs(positionCandidates.Last() - candidate.z) >= stepPositionCandidate;
                    List <Vector3Int>      potentialRightCandidates   = new List <Vector3Int>();
                    potentialRightCandidates.AddRange(unsafes.FindAll(hasPotentialRightCandidate));
                    potentialRightCandidates.AddRange(safes.FindAll(hasPotentialRightCandidate));
                    // if there is enough candidates
                    if (unsafes.Count() >= nbUnderCandidates && safes.Count() >= nbAroundCandidates && potentialRightCandidates.Count() > 0)
                    {
                        // Randomly select the right candidate
                        rightCandidate = potentialRightCandidates[Random.Range(0, potentialRightCandidates.Count())];
                        // Get all moving candidates
                        movingCandidates = new List <Vector3Int>();
                        ListExtension.Shuffle(unsafes);
                        ListExtension.Shuffle(safes);
                        bool isSafe = safes.Remove(rightCandidate);
                        //Debug.Log("isSafe => " + isSafe);
                        bool isUnsafe = unsafes.Remove(rightCandidate);
                        //Debug.Log("isUnsafe => " + isUnsafe);
                        // check if right candidates is safe or unsafe to not select him
                        if (isSafe)
                        {
                            movingCandidates.AddRange(unsafes.GetRange(0, nbUnderCandidates));
                            movingCandidates.AddRange(safes.GetRange(0, nbAroundCandidates - 1));
                        }
                        else if (isUnsafe)
                        {
                            movingCandidates.AddRange(unsafes.GetRange(0, nbUnderCandidates - 1));
                            movingCandidates.AddRange(safes.GetRange(0, nbAroundCandidates));
                        }
                        // generate position for moving candidates
                        for (int i = 0; i < movingCandidates.Count(); i++)
                        {
                            Vector3Int movingCandidate = movingCandidates[i];
                            movingCandidate.z   = Math.Abs(positionCandidates[0] - movingCandidate.z) > Math.Abs(positionCandidates[1] - movingCandidate.z) ? positionCandidates[0] : positionCandidates[1];
                            movingCandidates[i] = movingCandidate;
                        }
                        //Debug.Log("movingCandidates.Count() => " + movingCandidates.Count());
                        // Select a wrong candidate
                        wrongCandidate = movingCandidates[Random.Range(0, movingCandidates.Count())];
                        // Add the right candidate to moving candidate
                        rightCandidate.z = positionCandidates.Last();
                        movingCandidates.Add(rightCandidate);


                        candidatesFound = true;
                    }
                    else
                    {
                        //What if?
                    }
                }
                else                 // fails to find candidates for remaining icon factor
                {
                    Debug.Log("Candidates Fail! Adding IconFactor.NoIconUnder.");
                    iconFactorIndex = -1;
                    trials.Insert(0, 0);
                }
            }
            Debug.Log("Candidates Successfully found!");
            trials.RemoveAt(iconFactorIndex);

            // Output Control
            List <int> randomIcons = new List <int>();           //= Enumerable.Range(0, nbPins).ToList<int>();
            for (int i = 1; i < 30; i++)
            {
                randomIcons.Add(i);
            }
            ListExtension.Shuffle(randomIcons);

            for (int i = 0; i < expanDialSticks.NbRows; i++)
            {
                for (int j = 0; j < expanDialSticks.NbColumns; j++)
                {
                    Vector3Int movingCandidate = movingCandidates.Find(l => (l.x == i && l.y == j));
                    if (rightCandidate.x == i && rightCandidate.y == j)
                    {
                        Debug.Log("rightCandidate => " + rightCandidate);
                        // Projector
                        expanDialSticks.modelMatrix[i, j].TargetProjectorTexture = "icon0";
                        // Shape
                        expanDialSticks.modelMatrix[i, j].TargetPosition            = (sbyte)rightCandidate.z;
                        expanDialSticks.modelMatrix[i, j].TargetShapeChangeDuration = shapeChangeDuration;
                    }
                    else if (wrongCandidate.x == i && wrongCandidate.y == j)
                    {
                        Debug.Log("wrongCandidate => " + wrongCandidate);
                        // Projector
                        expanDialSticks.modelMatrix[i, j].TargetProjectorTexture = "icon0";
                        // Shape
                        expanDialSticks.modelMatrix[i, j].TargetPosition            = (sbyte)wrongCandidate.z;
                        expanDialSticks.modelMatrix[i, j].TargetShapeChangeDuration = shapeChangeDuration;
                    }
                    else if (movingCandidate != new Vector3Int())
                    {
                        Debug.Log("movingCandidate => " + movingCandidate);
                        // Projector
                        expanDialSticks.modelMatrix[i, j].TargetProjectorTexture = "icon" + randomIcons.First();
                        randomIcons.RemoveAt(0);
                        // Shape
                        expanDialSticks.modelMatrix[i, j].TargetPosition            = (sbyte)movingCandidate.z;
                        expanDialSticks.modelMatrix[i, j].TargetShapeChangeDuration = shapeChangeDuration;
                    }
                    else
                    {
                        // Projector
                        //expanDialSticks.modelMatrix[i, j].TargetProjectorTexture = "default";
                        expanDialSticks.modelMatrix[i, j].TargetProjectorTexture = "icon" + randomIcons.First();
                        randomIcons.RemoveAt(0);
                    }
                    // Projector
                    expanDialSticks.modelMatrix[i, j].TargetProjectorRotation       = 90f;
                    expanDialSticks.modelMatrix[i, j].TargetProjectorSize           = 2f;
                    expanDialSticks.modelMatrix[i, j].TargetProjectorChangeDuration = 0.1f;
                }
            }
            expanDialSticks.triggerProjectorChange();
            expanDialSticks.triggerShapeChange();

            string participantNumber = "<pos=0%><b>P" + numeroParticipant + "</b>";
            string trialProgress     = "<pos=90%><b>" + trials.Count() + "/" + nbTrials + "</b>";
            string legend            = participantNumber + trialProgress;
            expanDialSticks.setBottomBorderText(TextAlignmentOptions.Center, 16, Color.black, legend, new Vector3(90f, -90f, 0f));
            expanDialSticks.setBorderBackground(Color.white);
            expanDialSticks.triggerTextureChange();
            string iconSituationMsg = "ICON_APPARATUS " + currIconUnder;
            expanDialSticks.client.Publish(MQTT_SYSTEM_RECORDER, System.Text.Encoding.UTF8.GetBytes(iconSituationMsg), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
            string selectCandidateMsg = "SYSTEM_SELECT_PIN ";
            foreach (Vector3Int movingCandidate in movingCandidates)
            {
                selectCandidateMsg += "(" + movingCandidate.x + ", " + movingCandidate.y + ", " + movingCandidate.z + ") ";
            }
            expanDialSticks.client.Publish(MQTT_SYSTEM_RECORDER, System.Text.Encoding.UTF8.GetBytes(selectCandidateMsg), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
            string rightCandidateMsg = "SYSTEM_RIGHT_PIN (" + rightCandidate.x + ", " + rightCandidate.y + ", " + rightCandidate.z + ")";
            expanDialSticks.client.Publish(MQTT_SYSTEM_RECORDER, System.Text.Encoding.UTF8.GetBytes(rightCandidateMsg), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
            string wrongCandidateMsg = "SYSTEM_WRONG_PIN (" + wrongCandidate.x + ", " + wrongCandidate.y + ", " + wrongCandidate.z + ")";
            expanDialSticks.client.Publish(MQTT_SYSTEM_RECORDER, System.Text.Encoding.UTF8.GetBytes(wrongCandidateMsg), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
        }
        else
        {
            Quit();
        }
    }
Exemplo n.º 25
0
    private void TriggerNextTrial()
    {
        if (!landscapeGenerated)
        {
            for (int i = 0; i < expanDialSticks.NbRows; i++)
            {
                for (int j = 0; j < expanDialSticks.NbColumns; j++)
                {
                    expanDialSticks.modelMatrix[i, j].TargetPosition            = (sbyte)Random.Range(minPos, maxPos);
                    expanDialSticks.modelMatrix[i, j].TargetShapeChangeDuration = shapeChangeDuration;
                }
            }
            landscapeGenerated = true;
        }
        if (trials.Count() > 0)
        {
            // Unfreeze hand tracking
            safeGuard.UnFreeze();
            // Extract difficulty and changes
            KeyValuePair <Difficulty, List <List <int> > > difficultyChanges = trials.First();
            currDifficulty = difficultyChanges.Key;
            Debug.Log("currDifficulty -> " + currDifficulty);
            List <List <int> > changes = difficultyChanges.Value;
            currSubChanges = changes.First();
            ExpanDialSticks.SafetyOverlayMode nextOverlay = (ExpanDialSticks.SafetyOverlayMode)currSubChanges.First();
            // new overlay detected
            if (currOverlay != nextOverlay)
            {
                currOverlay = nextOverlay;
                expanDialSticks.SetOverlayMode(currOverlay);
                ResetDisplay();
                newOverlay  = true;
                toNextTrial = false;
                return;
            }
            // current trial;
            currTrial++;
            changes.RemoveAt(0);
            currSubChanges.RemoveAt(0);
            ListExtension.Shuffle(currSubChanges);
            Debug.Log("currSubChanges -> " + currSubChanges);

            // delete difficulty or if any reinsert remaining changes
            if (changes.Count() > 0)
            {
                trials[currDifficulty] = changes;
            }
            else
            {
                trials.Remove(currDifficulty);
            }
            // get a target for user
            target = candidates[Random.Range(0, candidates.Count())];
            // Output Control
            List <int> randomIcons = new List <int>();           //= Enumerable.Range(0, nbPins).ToList<int>();
            for (int i = 1; i < 30; i++)
            {
                randomIcons.Add(i);
            }
            ListExtension.Shuffle(randomIcons);

            for (int i = 0; i < expanDialSticks.NbRows; i++)
            {
                for (int j = 0; j < expanDialSticks.NbColumns; j++)
                {
                    if (target.x == i && target.y == j)
                    {
                        expanDialSticks.modelMatrix[i, j].TargetProjectorTexture = "icon0";
                    }
                    else
                    {
                        expanDialSticks.modelMatrix[i, j].TargetProjectorTexture = "icon" + randomIcons.First();
                        randomIcons.RemoveAt(0);
                    }
                    // Projector
                    expanDialSticks.modelMatrix[i, j].TargetProjectorRotation       = 90f;
                    expanDialSticks.modelMatrix[i, j].TargetProjectorSize           = expanDialSticks.modelMatrix[i, j].Diameter / 3f;
                    expanDialSticks.modelMatrix[i, j].TargetProjectorChangeDuration = 0.1f;
                }
            }
            expanDialSticks.triggerProjectorChange();
            expanDialSticks.triggerShapeChange();

            DisplayInstructions("Tourner le cylindre avec l'icône <b>Avion</b>");

            string trialMsg = "PARTICIPANT " + numeroParticipant + " DIFFICULTY " + currDifficulty + " OVERLAY " + currOverlay + " TARGET (" + target.x + ", " + target.y + ") ";
            expanDialSticks.client.Publish(MQTT_SYSTEM_RECORDER, System.Text.Encoding.UTF8.GetBytes(trialMsg), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);

            toNextTrial     = false;
            overlayAppeared = false;
        }
        else
        {
            Quit();
        }
    }
Exemplo n.º 26
0
    public void GenerateTrials()
    {
        foreach (Difficulty difficulty in difficulties)
        {
            List <List <int> > changes = new List <List <int> >();
            switch (difficulty)
            {
            case Difficulty.Easy:
                for (int i = 0; i < overlays.Count(); i++)
                {
                    List <List <int> > overlayChanges = new List <List <int> >();
                    overlayChanges.Add(new List <int> {
                        (int)overlays[i], 40, 27, 13
                    });;
                    overlayChanges.Add(new List <int> {
                        (int)overlays[i], 27, 13, -13
                    });
                    overlayChanges.Add(new List <int> {
                        (int)overlays[i], 13, -13, -27
                    });
                    overlayChanges.Add(new List <int> {
                        (int)overlays[i], -13, -27, -40
                    });
                    ListExtension.Shuffle(overlayChanges);
                    changes.AddRange(overlayChanges);
                    nbTrials += 4;
                }
                break;

            case Difficulty.Medium:
                for (int i = 0; i < overlays.Count(); i++)
                {
                    List <List <int> > overlayChanges = new List <List <int> >();
                    changes.Add(new List <int> {
                        (int)overlays[i], 40, 32, 24, 16, 8
                    });
                    changes.Add(new List <int> {
                        (int)overlays[i], 24, 16, 8, -8, -16
                    });
                    changes.Add(new List <int> {
                        (int)overlays[i], 16, 8, -8, -16, -24
                    });
                    changes.Add(new List <int> {
                        (int)overlays[i], -8, -16, -24, -32, -40
                    });
                    ListExtension.Shuffle(overlayChanges);
                    changes.AddRange(overlayChanges);
                    nbTrials += 4;
                }
                break;

            case Difficulty.Hard:
                for (int i = 0; i < overlays.Count(); i++)
                {
                    List <List <int> > overlayChanges = new List <List <int> >();
                    changes.Add(new List <int> {
                        (int)overlays[i], 40, 37, 34, 32, 29, 26, 24
                    });
                    changes.Add(new List <int> {
                        (int)overlays[i], 10, 8, 5, 3, -3, -5, -8
                    });
                    changes.Add(new List <int> {
                        (int)overlays[i], 8, 5, 3, -3, -5, -8, -10
                    });
                    changes.Add(new List <int> {
                        (int)overlays[i], -24, -26, -29, -32, -34, -37, -40
                    });
                    ListExtension.Shuffle(overlayChanges);
                    changes.AddRange(overlayChanges);
                    nbTrials += 4;
                }
                break;
            }
            trials.Add(difficulty, changes);
        }
        toNextTrial = true;
    }
Exemplo n.º 27
0
        public async Task <CommonResponse> GetList(ListFilterRequest request)
        {
            try
            {
                if (request.PageSize <= 0)
                {
                    request.PageSize = 10;
                }
                if (request.PageNumber <= 0)
                {
                    request.PageNumber = 1;
                }



                var Sqlrequest    = new DataRequest <Product>();
                var SqlrequestAnd = new DataRequest <Product>();
                Sqlrequest.Query = request.Filter;
                Sqlrequest.Where = x => x.Id != 0;

                if (!String.IsNullOrEmpty(Sqlrequest.Query))
                {
                    if (Sqlrequest.NumberOnly())
                    {
                        SqlrequestAnd.Where = x => x.Id == Sqlrequest.Query.ToLong();
                        Sqlrequest.Where    = ListExtension.PredicateBuilder(Sqlrequest.Where, SqlrequestAnd.Where);
                    }
                    else if (Sqlrequest.lettersonly())
                    {
                        SqlrequestAnd.Where = x => x.Name.Contains(Sqlrequest.Query);
                        Sqlrequest.Where    = ListExtension.PredicateBuilder(Sqlrequest.Where, SqlrequestAnd.Where);
                    }
                    else
                    {
                        SqlrequestAnd.Where = x => x.Id == Sqlrequest.Query.ToLong() || x.Name.Contains(Sqlrequest.Query);
                        Sqlrequest.Where    = ListExtension.PredicateBuilder(Sqlrequest.Where, SqlrequestAnd.Where);
                    }
                }

                if (request.StartDate != null && request.EndDate != null)
                {
                    Sqlrequest.Where    = x => x.ManufactureDate >= request.StartDate && x.ManufactureDate <= request.EndDate;
                    SqlrequestAnd.Where = ListExtension.PredicateBuilder(Sqlrequest.Where, SqlrequestAnd.Where);
                }

                var product = _context.Products.Where(Sqlrequest.Where);

                #region sort preparations

                if (request.IsAsc)
                {
                    switch (request.SortBy)
                    {
                    default:
                    case "0": Sqlrequest.OrderBy = r => r.Id; break;

                    case "1": Sqlrequest.OrderBy = r => r.Name; break;

                    case "2": Sqlrequest.OrderBy = r => r.Price; break;

                    case "3": Sqlrequest.OrderBy = r => r.ManufactureDate; break;

                    case "4": Sqlrequest.OrderBy = r => r.Location; break;

                    case "5": Sqlrequest.OrderBy = r => r.IsAvailable; break;
                    }
                    ;
                }
                else
                {
                    switch (request.SortBy)
                    {
                    default:
                    case "0": Sqlrequest.OrderByDesc = r => r.Id; break;

                    case "1": Sqlrequest.OrderByDesc = r => r.Name; break;

                    case "2": Sqlrequest.OrderByDesc = r => r.Price; break;

                    case "3": Sqlrequest.OrderByDesc = r => r.ManufactureDate; break;

                    case "4": Sqlrequest.OrderByDesc = r => r.Location; break;

                    case "5": Sqlrequest.OrderByDesc = r => r.IsAvailable; break;
                    }
                    ;
                }
                #endregion

                //Order By
                if (request.IsAsc && Sqlrequest.OrderBy != null)
                {
                    product = product.OrderBy(Sqlrequest.OrderBy);
                }

                if (!request.IsAsc && Sqlrequest.OrderByDesc != null)
                {
                    product = product.OrderByDescending(Sqlrequest.OrderByDesc);
                }

                var total = await product.CountAsync();

                if (total == 0)
                {
                    return(CommonResponse.CreateSuccessResponse("No Data Available", null, 200, ""));
                }
                var execute = await product.AsNoTracking().Skip(ListExtension.getPageNumber(request.PageNumber, request.PageSize))
                              .Take(request.PageSize).ToListAsync();

                var response = _mapper.Map <IEnumerable <Product>, IEnumerable <ProductViewModel> >(execute);


                return(CommonResponse.CreatePaginationResponse(
                           "Success",
                           total,
                           response,
                           request.PageSize,
                           request.PageNumber));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error while fetching the records.");
                throw;
            }
        }