GetValues() private method

private GetValues ( Type enumType ) : Array
enumType Type
return Array
Exemplo n.º 1
0
    public static T RandomEnumValue <T>() where T : struct, System.IConvertible
    {
        System.Array values = Enum.GetValues(typeof(T));
        Random       random = new Random();

        return((T)values.GetValue(random.Next(values.Length)));
    }
    private void Init()
    {
        Array stimulations = Enum.GetValues(typeof(PossibleFingerStimulations));
        Array light_effects = Enum.GetValues(typeof(PossibleLightEffectSide));
        Array stimulation_starts = Enum.GetValues(typeof(PossibleStimulationStart));
        Array object_colors = Enum.GetValues(typeof(PossibleObjectColor));

        foreach (PossibleFingerStimulations stimulation in stimulations)
        {
            foreach (PossibleLightEffectSide light_effect in light_effects)
            {
                foreach (PossibleStimulationStart stimulation_start in stimulation_starts)
                {
                    foreach (PossibleObjectColor object_color in object_colors)
                    {
                        for (int run = 0; run < StateMachine.numberOfRuns; run++)
                        {
                            experiments.Add(new Experiment(stimulation, light_effect, stimulation_start, object_color));
                        }
                    }
                }
            }
        }
        Shuffle();
    }
Exemplo n.º 3
0
        public ModifyForm(Modify hook, MethodDefinition method)
        {
            InitializeComponent();
            this.hook              = hook;
            this.method            = method;
            textBox                = new TextBox();
            textBox.Dock           = DockStyle.Fill;
            comboBox               = new ComboBox();
            comboBox.Dock          = DockStyle.Fill;
            comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox.DisplayMember = "Text";
            comboBox.ValueMember   = "Value";
            var ops = typeof(OpCodes).GetFields(BindingFlags.Static | BindingFlags.Public).OrderBy(f => f.Name);

            foreach (var op in ops)
            {
                opcodes.Items.Add(op.Name.ToLower());
            }
            opcodes.AutoCompleteSource = AutoCompleteSource.ListItems;
            opcodes.AutoCompleteMode   = AutoCompleteMode.SuggestAppend;
            var optypevalues = Enum.GetValues(typeof(Modify.OpType));

            foreach (var op in optypevalues)
            {
                optypes.Items.Add(op);
            }
            SaveButton.Visible = false;
        }
Exemplo n.º 4
0
        public async Task <List <WeatherForecast> > GenerateForecasts(string city,
                                                                      DateTimeOffset startDate,
                                                                      int numOfDays, int averageTemp)
        {
            var rng     = new Random();
            var maxEnum = Enum.GetValues(typeof(Summary))
                          .Cast <Int32>().Max();

            var forecasts = Enumerable.Range(0, numOfDays - 1).Select(index => new WeatherForecast
            {
                Id           = Guid.NewGuid().ToString(),
                City         = city,
                CreationTime = Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow),
                Date         = Timestamp.FromDateTimeOffset(startDate.AddDays(index)),
                TemperatureC = averageTemp + rng.Next(-20, 55),
                Summary      = ((Summary)rng.Next(maxEnum)),
                Context      = Context.InShade
            }).ToList()
            ;
            await _pgContext.AddRangeAsync(forecasts);

            await _pgContext.SaveChangesAsync();

            return(forecasts);
            // var sampleTopic = new CreateTopicSample();
            // sampleTopic.PublishMessage("project", "topic");
        }
Exemplo n.º 5
0
 /// <summary>
 ///     Initialize the task
 /// </summary>
 /// <param name="instance"></param>
 public override void Initialize(EFSService instance)
 {
     // Allocates all critical section
     foreach (Step step in Enum.GetValues(typeof(Step)))
     {
         instance.StepAccess[step] = new Mutex(true, step.ToString());
     }
 }
        public TimerEvents(IClock clock)
        {
            void CreateDefaultEvents()
            {
                const string couldNotAddErr     = "Could not add {0} to ConcurrentDictionary";
                var          defaultSunriseTime = new TimeSpan(05, 30, 00);
                var          defaultSunsetTime  = new TimeSpan(19, 30, 00);

                foreach (Enums.TimedEvent timedEvent in Enum.GetValues(typeof(Enums.TimedEvent)))
                {
                    var err = string.Format(couldNotAddErr, timedEvent);

                    switch (timedEvent)
                    {
                    case Enums.TimedEvent.UpdateSunsetSunrise:
                        if (!_events.TryAdd(timedEvent, new Domain.TimedEvent(new TimeSpan(02, 00, 00), false)))
                        {
                            Log.Error(new Exception(err), err);
                        }

                        break;

                    case Enums.TimedEvent.OnSunrise:
                        if (!_events.TryAdd(timedEvent, new Domain.TimedEvent(defaultSunriseTime, false)))
                        {
                            Log.Error(new Exception(err), err);
                        }

                        break;

                    case Enums.TimedEvent.OnSunset:
                        if (!_events.TryAdd(timedEvent, new Domain.TimedEvent(defaultSunsetTime, false)))
                        {
                            Log.Error(new Exception(err), err);
                        }

                        break;

                    case Enums.TimedEvent.OnLightsOff:
                        var enabled = clock.Now.Within(defaultSunsetTime, defaultSunriseTime);

                        if (!_events.TryAdd(timedEvent, new Domain.TimedEvent(clock.Now.AddTimeSpan(15.Minutes()), enabled)))
                        {
                            Log.Error(new Exception(err), err);
                        }

                        break;

                    default:
                        _events.TryAdd(timedEvent, EmptyTimedEvent);
                        break;
                    }
                }
            }

            _events = new ConcurrentDictionary <Enums.TimedEvent, Domain.TimedEvent>();
            CreateDefaultEvents();
        }
Exemplo n.º 7
0
        internal static object RandomEnum(Type enumType, params object[] excludeValues)
        {
            if (!enumType.IsEnum)
            {
                throw new ArgumentException("enumType must be an enum");
            }

            var values = Enum.GetValues(enumType);

            return(GetNonExcludedValue(() => values.GetValue(Random.Next(values.Length)), excludeValues));
        }
Exemplo n.º 8
0
            public static T GetPreviousValue <T>(T value)
                where T : IFormattable, IConvertible, IComparable
            {
                Array values = SEnum.GetValues(typeof(T));

                for (int i = 0; i < values.Length; i++)
                {
                    if (values.GetValue(i).Equals(value))
                    {
                        return((T)values.GetValue(Math.ClampRewind(i - 1, 0, values.Length - 1)));
                    }
                }

                throw new ArgumentException();
            }
Exemplo n.º 9
0
            public static int ToIndex <T>(T value)
                where T : IFormattable, IConvertible, IComparable
            {
                Array values = SEnum.GetValues(typeof(T));

                for (int i = 0; i < values.Length; i++)
                {
                    if (values.GetValue(i).Equals(value))
                    {
                        return(i);
                    }
                }

                throw new ArgumentException("Enum Value " + value + " Not Defined");
            }
Exemplo n.º 10
0
        public MainForm()
        {
            InitializeComponent();

            CategoryComboBox.Items.Add("All");
            var categories = Enum.GetValues(typeof(NoteCategory)).Cast <object>().ToArray();

            CategoryComboBox.Items.AddRange(categories);
            CategoryComboBox.SelectedItem = "All";

            _project = ProjectManager.LoadFromFile(ProjectManager.DefaultPath);
            RefreshListBox();

            //Выбирает последнюю просматреваемую заметку, если таковая существует в списке
            if (_viewedNotes.Count != 0)
            {
                NoteListBox.SelectedIndex = _project.SelectedNoteIndex;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 根据枚举值,获取指定枚举类的成员描述
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="val">成员的值</param>
        /// <returns></returns>
        public static string GetDescriptionString(this Type type, int?val)
        {
            var values = from SEnum e in SEnum.GetValues(type)
                         select new { id = e.ToInt(), name = e.GetDescriptionString() };

            if (!val.HasValue)
            {
                val = 0;
            }

            try
            {
                return(values.ToList().Find(c => c.id == val).name);
            }
            catch
            {
                return("");
            }
        }
Exemplo n.º 12
0
        public void RefreshParametersFromDatabase()
        {
            miAddNewParameter.Enabled = Options.CanNewParameters();

            olvParameters.ClearObjects();

            //add all parameters from all levels
            foreach (ParameterLevel level in Enum.GetValues(typeof(ParameterLevel)))
            {
                var parametersFoundAtThisLevel = Options.ParameterManager.ParametersFoundSoFarInQueryGeneration[level];

                //add them to the collection
                if (parametersFoundAtThisLevel.Any())
                {
                    olvParameters.AddObjects(parametersFoundAtThisLevel);
                }
            }

            DisableRelevantObjects();
            parameterEditorScintillaControl1.RegenerateSQL();

            UpdateTabVisibility();
        }
Exemplo n.º 13
0
 public static int GetLength <T>()
     where T : IFormattable, IConvertible, IComparable
 {
     return(SEnum.GetValues(typeof(T)).Length);
 }
Exemplo n.º 14
0
        public void ConfigureAuthServices(IServiceCollection services, WebApiConfiguration configuration)
        {
            /* Configure sharing cookies between application.
             * See https://docs.microsoft.com/en-us/aspnet/core/security/cookie-sharing?tabs=aspnetcore2x for details */
            services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(configuration.Web.CookieKeyRingDirectory))
            .SetApplicationName("ulearn");

            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.Name              = configuration.Web.CookieName;
                options.Cookie.Expiration        = TimeSpan.FromDays(14);
                options.Cookie.Domain            = configuration.Web.CookieDomain;
                options.LoginPath                = "/users/login";
                options.LogoutPath               = "/users/logout";
                options.Events.OnRedirectToLogin = context =>
                {
                    /* Replace standard redirecting to LoginPath */
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(Task.CompletedTask);
                };
                options.Events.OnRedirectToAccessDenied = context =>
                {
                    /* Replace standard redirecting to AccessDenied */
                    context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    return(Task.CompletedTask);
                };
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = configuration.Web.Authentication.Jwt.Issuer,
                    ValidAudience    = configuration.Web.Authentication.Jwt.Audience,
                    IssuerSigningKey = JwtBearerHelpers.CreateSymmetricSecurityKey(configuration.Web.Authentication.Jwt.IssuerSigningKey)
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Instructors", policy => policy.Requirements.Add(new CourseRoleRequirement(CourseRoleType.Instructor)));
                options.AddPolicy("CourseAdmins", policy => policy.Requirements.Add(new CourseRoleRequirement(CourseRoleType.CourseAdmin)));
                options.AddPolicy("SysAdmins", policy => policy.RequireRole(new List <string> {
                    LmsRoleType.SysAdmin.GetDisplayName()
                }));

                foreach (var courseAccessType in Enum.GetValues(typeof(CourseAccessType)).Cast <CourseAccessType>())
                {
                    var policyName = courseAccessType.GetAuthorizationPolicyName();
                    options.AddPolicy(policyName, policy => policy.Requirements.Add(new CourseAccessRequirement(courseAccessType)));
                }
            });
        }
Exemplo n.º 15
0
        public static T RandomEnumValue <T>()
        {
            var v = Enum.GetValues(typeof(T));

            return((T)v.GetValue(new Random().Next(v.Length)));
        }
Exemplo n.º 16
0
    public static Location getRandomLocation()
    {
        var enums = Enum.GetValues(typeof(Location));

        return((Location)Random.Range(0, enums.Length));
    }
    protected void OnTriggerEnter(Collider coll)
    {
        if (coll.tag == "EnemyBullet")
        {
            if (gameObject.layer == LayerMask.NameToLayer("EnemyEntity"))
            {
                return;
            }

            ParticleFactory.GetInstance().CreateOnceParticle <ParticleExplosion>(coll.gameObject.GetComponent <Collider>().ClosestPointOnBounds(transform.position))
            .SetExplosionParticleNumber(10)
            .SetMinExplosionDistance(1.0f)
            .SetMaxExplosionDistance(3.0f)
            .SetExplosionParticleLifeTime(0.4f)
            .SetExplosionParticleColor(new Color(Random.Range(0.5f, 1.0f), Random.Range(0.5f, 1.0f), Random.Range(0.5f, 1.0f)))
            .Play();

            if (m_Core.isPenetrable() == false)
            {
                Destroy(coll.gameObject.transform.parent.gameObject);
            }

            Material material = GetComponentInChildren <MeshRenderer>().material;

            if (m_Core.IsInvincible() == false)
            {
                m_Core.SetHp <EntityCore>(m_Core.GetHp() - ManagerPool.GetInstance().GetManager <PlayerManager>().GetPlayerGun().GetBulletDamage());
            }

            if (m_Core.GetHp() <= 0)
            {
                PlayerManager playerManager = ManagerPool.GetInstance().GetManager <PlayerManager>();
                playerManager.SetPlayerScore(playerManager.GetPlayerScore() + m_Core.GetScore());

                ParticleFactory.GetInstance().CreateOnceParticle <ParticleExplosion>(gameObject.transform.position)
                .SetExplosionParticleColor(new Color(Random.Range(0.5f, 1.0f), Random.Range(0.5f, 1.0f), Random.Range(0.5f, 1.0f)))
                .Play();
                Destroy(gameObject);

                material.DOKill();
            }
            else
            {
                DOTween.Sequence()
                .Append(material.DOColor(Color.white, 0.05f))
                .Append(material.DOColor(m_Core.GetColor(), 0.05f));
            }
        }

        if (coll.tag == "PlayerBullet")
        {
            if (gameObject.layer == LayerMask.NameToLayer("PlayerEntity"))
            {
                return;
            }

            ParticleFactory.GetInstance().CreateOnceParticle <ParticleExplosion>(coll.gameObject.GetComponent <Collider>().ClosestPointOnBounds(transform.position))
            .SetExplosionParticleNumber(10)
            .SetMinExplosionDistance(1.0f)
            .SetMaxExplosionDistance(3.0f)
            .SetExplosionParticleLifeTime(0.4f)
            .SetExplosionParticleColor(new Color(Random.Range(0.5f, 1.0f), Random.Range(0.5f, 1.0f), Random.Range(0.5f, 1.0f)))
            .Play();

            if (m_Core.isPenetrable() == false)
            {
                Destroy(coll.gameObject.transform.parent.gameObject);
            }

            Material material = GetComponentInChildren <MeshRenderer>().material;

            if (m_Core.IsInvincible() == false)
            {
                m_Core.SetHp <EntityCore>(m_Core.GetHp() - ManagerPool.GetInstance().GetManager <PlayerManager>().GetPlayerGun().GetBulletDamage());
            }

            if (m_Core.GetHp() <= 0)
            {
                PlayerManager playerManager = ManagerPool.GetInstance().GetManager <PlayerManager>();
                ItemManager   itemManager   = ManagerPool.GetInstance().GetManager <ItemManager>();

                playerManager.SetPlayerScore(playerManager.GetPlayerScore() + m_Core.GetScore());

                ParticleFactory.GetInstance().CreateOnceParticle <ParticleExplosion>(gameObject.transform.position)
                .SetExplosionParticleColor(new Color(Random.Range(0.5f, 1.0f), Random.Range(0.5f, 1.0f), Random.Range(0.5f, 1.0f)))
                .Play();

                float randNum = Random.Range(0.0f, 1000.0f);
                if (randNum <= 1000.0f)
                {
                    ItemType itemType = (ItemType)Random.Range(1, Enum.GetValues(typeof(ItemType)).Cast <int>().Max() + 1);
                    itemManager.SpawnItem(itemType, gameObject.transform.position);
                }

                Destroy(gameObject);
                material.DOKill();
            }
            else
            {
                if (m_Core.IsInvincible() == false)
                {
                    DOTween.Sequence()
                    .Append(material.DOColor(Color.white, 0.05f))
                    .Append(material.DOColor(m_Core.GetColor(), 0.05f));
                }
            }
        }
    }
Exemplo n.º 18
0
 public static T FromIndex <T>(int index)
     where T : IFormattable, IConvertible, IComparable
 {
     return((T)SEnum.GetValues(typeof(T)).GetValue(index));
 }