FAQ Database Discussion Community


How to create enum from a String

swift,enums,swift2
In Swift 2, can you create an enum from a string? enum Food : Int { case Pizza, Pancakes } let str = "Pizza" let food = Food(name:str) // for example That last line doesn't work, but I'm looking for something like it. Like in Java, you can say Food.valueOf("Pizza")....

Why can't I directly reference my String enum?

java,enums
I thought I would try to start a minecraft mod today. I was going to use an enum class to store thing like my version and modid. public enum Reference { MODID("farming"), VERSION("1.8.0-0.0.1"); private String value; Reference(String string) { String value = string; } @Override public String toString() { return...

MVC - Changing default text in dropdown

asp.net-mvc,razor,enums,html.dropdownlistfor
I have a view model that contains an enum: public class PasswordChangerIndexViewModel { public enum DatabaseTypes { Main = 10, Florida = 20, Illinois = 30, Missouri = 40, NewHampshire = 50, NewJersey = 60, Oklahome = 70 }; [DisplayName("Database")] public DatabaseTypes DatabaseType { get; set; } } And in...

Swift Array Issues

ios,arrays,swift,struct,enums
I have this code: let posState = positionState(pos) if posState != .None { if posState == .Off { boardArray[pos.row][pos.column] == .On } else { boardArray[pos.row][pos.column] == .Off } } The issue I'm having is that when I attempt to change the value of an element in boardArray, nothing happens. Why...

Databinding Enum - The name 'StoreLocation' does not exist in the namespace

c#,wpf,enums,wpfdatagrid
I'm getting a error: The name 'StoreLocation' does not exist in the namespace "clr-namespace:System.Security.Cryptography.X509Certificates;assembly=mscorlib" on line: <x:Type TypeName="crypto:StoreLocation" /> What I'm doing wrong? <UserControl x:Class="Admin.Certificates" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:Admin"...

Enum of enums in Python?

python,python-3.x,enums
Is it possible to have an enum of enums in Python? For example, I'd like to have enumA enumB elementA elementB enumC elementC elementD And for me to be able to refer to elementA as enumA.enumB.elementA, or to refer to elementD as enumA.enumC.elementD. Is this possible? If so, how? EDIT:...

Remove duplication of enumerated elements

c++,enums,enumeration
I have the following enumerator and it's likely to be expanded over the course of program development: enum myEnum { Element1, Element2, Element3 ... ElementX Last }; I have a function that uses the enumerator in the following way: bool CheckEnumValidity(myEnum a) { bool valid = false; switch (a) {...

Enum Java Not saved as Strings with Enumerated Annotation

java,jpa,enums
I am not able to create Enumerations to be saved as Strings in MySQL DB. I have a MySQL table with a field: status varchar(50) Enum public enum Status {OPEN, CLOSED, CANCELLED, DONE} Entity @Column(name="status", nullable=false) private Status status; @Enumerated(EnumType.STRING) public Status getStatus() {return status;} When I launch my application,...

Instantiating all possible combinations of enums

c#,class,enums
I'm having trouble iterating over all possible combinations of enums. I'm not too familiar with them as I've just started C# and am coming in from low level languages like C and assembler. public enum enumA { A1, A2, A3 } public enum enumB { B1, B2, B3 } public...

Efficiently adding element to the top of the list

java,list,arraylist,enums,linked-list
I have an ENUM like this from which I always get what is my localFruit which can be either APPLE or ORANGE or BANANA. public enum Fruits { // it can have more elements here APPLE, ORANGE, BANANA; // some code } So let's say if APPLE is my localFruit,...

Reference Swift enum member without its associated value

swift,enums
I have the following enum: enum State: Equatable { case Loading case Finished case Error(message: String) } func ==(lhs: State, rhs: State) -> Bool { //... } I want to be able to compare enum members. I have overloaded == operator, and it works, but there's a problem: let state:...

Java enum implements interface with Class return type

java,generics,enums
OK, be nice. Here's an enum that implements an interface with a method that returns a 'raw type' which gives me a warning on the getCaste() method in the interface. public enum Thing implements HasCaste { Type1 { @Override public Class getCaste() { return String.class; } }; } interface HasCaste...

Using enum in Android Java programming

java,enums
I'm trying to write a game in android and I want to use enum. This is my enum class: public enum State { INACTIVE(0), ACTIVE(1); private final int value; private State(int value){ this.value = value; } public int getValue() { return value; } } and then I want to use...

Assigning a random enum value a property

c#,enums
Hi have been given a task that I am struggling with. I need to assign a random enum to a property. The code I have is this. public enum PegColour { Red, Green, Blue, Yellow, Black, White } And other class which looks like this public class PegContainer { ///...

How to get Display Text from EnumDropDownListFor on post?

c#,asp.net-mvc,enums,html-helper
Is there a way to get DisplayName (Text) from EnumDropDownListFor helper for enum? Enum: public enum PartnersGroup { [Display(Name="Partner_SystemsGroup",ResourceType=typeof(Global) )] SystemsGroup, [Display(Name="Partner_SoftwarePartners",ResourceType=typeof(Global))] SoftwarePartners, [Display(Name="Partner_IntegrationPartners",ResourceType=typeof(Global))] IntegrationPartners, } Model public class Partner { public PartnersGroup PartnersGroup { get; set; } } Controller // GET: Partners/Create public ActionResult Create() { ---- return...

Enum types may not be instantiated error

java,arrays,enums,playing-cards
I am making a basic card deck at the moment and I've encountered a problem using enums. How do I fix the following error(enum types may not be instantiated) in my code and get the value assigned to each enum public enum Rank { ACE(14), KING(13), QUEEN(12), JACK(11), TEN(10), NINE(9),...

Overflow of an enum type in C?

c,enums,integer-overflow
If I have an enum type, like: enum week{ sunday=0, monday, tuesday, wednesday, thursday, friday, saturday}; and I have: enum week day; day = saturday; day++; What will be the value of day?...

Same enum values for multiple columns

ruby-on-rails,ruby,enums
I need to do something like this: class PlanetEdge < ActiveRecord::Base enum :first_planet [ :earth, :mars, :jupiter] enum :second_planet [ :earth, :mars, :jupiter] end Where my table is a table of edges but each vertex is an integer. However, it seems the abvove is not possible in rails. What might...

Swift protocol that is using an enum with generic associated type

swift,generics,enums,protocols
I'm trying to create a protocol that is using a generic enum in swift. The compiler throws this error: Protocol can only be used as a generic constraint because it has associated type requirements Short code snipped: enum GenericEnum<T> { case Unassociated case Associated(T) } protocol AssociatedProtocol { typealias AssociatedType...

Is creating a constant or enum class for template page efficient? [closed]

php,enums
Basically I'm building a website that need a html like template called from the folder using their file name. Should I use a enum/constant class or should I just call them straight to their filename? Example: abstract class ViewTemplate { const ORDER_HISTORY = 'order_history_template.html'; const PURCHASE_HISTORY = 'purchase_history_template.html'; //etc... }...

Grouping Enums best practice [closed]

c#,enums
If you have an enum where the values can be naturally grouped into subsets. For example: [Flags] public enum Instrument { Lute, Guitar, Flute, Drum } [Flags] public enum InstrumentType { Percussion, String, Wind, } there are many ways this can be accomplished 1) To combine this data into a...

Use enum to show message boxes

c#,enums,messagebox
Is it possible to show a MessageBox according to the selected enum item? E.g.: public enum Messages { UserAlreadyExists, NoUserName, NoPassword, NoUserNameOrPassword } If so, how do I handle each item in order to show a specific MessageBox?...

Getting the value of an enum field

java,enums,byte
I have an enumeration of byte values: public class ByteMessage { public enum Messages { ACK(0x01), CHAT(0x02), TURN(0x02), WAITING(0x03), REMATCH(0x04), DOUBLE(0x05), LOADREQUEST(0x06), LOADCOMPLETE(0x07), ROLL(0x08), DBLACCEPTORDECLINE(0x09), DBLRECV(0x0A), ALERTPEERNOPOSSIBLES(0x0B), UPDATEDIES(0x0C), SETTURN(0x0D), SETFIRSTROLL(0x0E), CALCPOSSIBLEINDEXES(0x0F), LOADGAMEREQUEST(0x10), LOADGAMECOMPLETE(0x11), PUSHSTATUSTEXT(0x12), ISDOUBLESOWNER(0x13); private final byte id; Messages(int id) { this.id = (byte) id; } public byte getId()...

Why can enum arrays be cast to two different IEnumerable types?

c#,arrays,enums
I seemed to have stumbled upon something unusual within C# that I don't fully understand. Say I have the following enum defined: public enum Foo : short { // The values aren't really important A, B } If I declare an array of Foo or retrieve one through Enum.GetValues, I'm...

'float' object is not callable while creating dictionary from Enum in Python

python,dictionary,enums
I've created an Enum in Python 3.4 with some data and a function that returns an ffactor based on the enumeration. I would like to make a dictionary of the ffactors from each Enum. So I tried this: class RaceType(Enum): GS = 0 SC = 1 CL = 2 @property...

Lifetime parameters for an enum within a struct

struct,enums,rust,lifetime
I don't understand why I get an error with this type of structure enum Cell <'a> { Str(&'a str), Double(&'a f32), } struct MyCellRep<'a> { value: &'a Cell, ptr: *const u8, } impl MyCellRep{ fn new_from_str(s: &str) { MyCellRep { value: Cell::Str(&s), ptr: new_sCell(CString::new(&s)) } } fn new_from_double(d: &f32) {...

Accessing enum variables/methods

java,enums
enum ChineseMenu { SOUP_CHICKEN(22), SOUP_VEG(32), NOODLES_NONVEG(23), NOODLES_VEG(55), RICE_NONVEG(43), RICE_VEG(66); private int value; ChineseMenu(int price) { this.value = price; } public int getCost() { return value; } } class ChineseDemo { public static void main(String[] args) { ChineseMenu[] chineseArray = ChineseMenu.values(); for (ChineseMenu menu : chineseArray) { System.out.println("The price of "...

Restrict allowed httpMethods using enum

rest,groovy,enums
I am creating connectors for REST API methods. Some methods has the same method name but performs different HTTP methods. For example, createEntity( HttpMethod httpMethod, CreateEntity model ) can perform POST and GET only. What I want is to have an error when httpMethod is supplied with PUT or DELETE....

How to access enum if inner enum having same name exist

java,enums
Unable to access values from enum defined outside class Test. How to access enumeration constant like Reddel,Jonathan,Goldendel etc enum Apple{ Reddel,Jonathan,Goldendel,Winesap,Cortland; } public class Test{ enum Apple{ Seb,Majj,Dlred,Wipe,Cland; } public static void main(String s[]){ //here I want to access enumeration constant from Apple outside Test. //Apple.Winesap //Apple.Goldendel System.out.println(Apple.Winesap); } }...

Confirming that the value of a UITextField value is a member of an enum

ios,swift,error-handling,enums
I have a UITextField With a UIPickerView to set its value from an enum and a save button the user presses to save their selection. My question is, is there a way to error trap this setup so when the user presses save it will confirm that the value of...

java enum string matching

java,enums
I have an enum as follows: public enum ServerTask { HOOK_BEFORE_ALL_TASKS("Execute"), COPY_MASTER_AND_SNAPSHOT_TO_HISTORY("Copy master db"), PROCESS_CHECKIN_QUEUE("Process Check-In Queue"), ... } I also have a string (lets say string = "Execute") which I would like to make into an instance of the ServerTask enum based on which string in the enum that...

Enum Parse C++ Or Analog

c#,c++,enums
In C# use code: enum COMPUTER_NAME_FORMAT { ComputerNameNetBIOS, ComputerNameDnsHostname, ComputerNameDnsDomain, ComputerNameDnsFullyQualified, ComputerNamePhysicalNetBIOS, ComputerNamePhysicalDnsHostname, ComputerNamePhysicalDnsDomain, ComputerNamePhysicalDnsFullyQualified } string format = "ComputerNameDnsFullyQualified"; (COMPUTER_NAME_FORMAT)Enum.Parse(typeof(COMPUTER_NAME_FORMAT), format) How use this in C++ ?...

Error 1 The type or namespace name * could not be found (are you missing a using directive or an assembly reference?)

c#,generics,enums,typeof
I am trying to make a helper function that return an enum name of any type of enum- working from: https://msdn.microsoft.com/en-us/library/system.enum.getname%28v=vs.110%29.aspx I have run into this error: Error 1 The type or namespace name 'enumType' could not be found (are you missing a using directive or an assembly reference?) From...

How to sort enum using a custom order attribute?

c#,enums
I have an enum like this: enum MyEnum{ [Order(1)] ElementA = 1, [Order(0)] ElementB = 2, [Order(2)] ElementC = 3 } And I want to list its elements sorted by a custom order attribute I wrote, so that I get a list of items sorted. I am getting the Description...

How to create a singleton class using enum

java,enums,singleton
I am trying to create a singleton class in Java. The best available solution with Java5 and above versions seems to be using enum. But I am not sure how to convert my class into a singleton class using enum. Following is my simplified class: public class Employee { private...

Faccing issue in detecting cardType using enum in java

java,android,regex,enums
I am developing an Android Application which accept payment. Here I am getting a problem in detecting a card type. Here I am faccing one issue in CardType.Java Enum return only visa its unable to find any other type of card. I am entering 600206 and my class return visa...

Enum: Switch case for variables of type

swift,enums
How come when I try to unwrap and optional which has the enum friendstate do I get an error when I try to apply it in the switch statement below? The error provied is Enum case "added" not found in type "friendState!" (error replicates for all cases) Is there a...

C#: passing in array of a specific Enum type as params object[] argument

c#,arrays,enums
When attempting to pass in an array of a specific enum type as a function argument via params object[], I am unable to pass in an actual array without casting to object[] first. But if I do so I do not have access to the original enum type. Given the...

An enum constant contains all the enum constants of the same enum class

java,enums
I just realized that an enum constant in Java seems containing all the enumeration constants of the same type. For example, the following code is legitimate: enum State { enable, disable, deleted; } class Test { public static void main(String[] args) { for ( State s : State.enable.disable.values() ) {...

Save an enum in RandomAccessFile

java,enums,randomaccessfile
Ok, I have a class called Encuadernacion.java public enum Encuadernacion { NONE("Ninguno"), RUSTICA("Rustica"), CARTONE("Cartone"), PIEL("Piel"), ESPIRAL("Espiral"), GRAPADA("Grapada"); private final String ENCUADERNAR; Encuadernacion(String descripcion){ this.ENCUADERNAR = descripcion; } public String getDescripcion(){ return ENCUADERNAR; } } and then the book creation called Libro.java public class Libro implements Serializable{ private Encuadernacion encuadernado; public...

Enum switch - VERY URGENT

arrays,list,for-loop,enums,switch-statement
I have this java class where I am writing the code for applying the overrides. I want to know if using ENUM is appropriate or if I need to use the switch case, how can I use it? Also, I have the for loop that I need to use as...

Passing enum as parameter to a constructor [closed]

c++,oop,enums
I got a problem when I want to pass an enum value to a default construtor. My enums are defined like this: typedef enum { DOUBLOON, VICTORYPOINT } ENUMchipType; They are stored in a separate .h file. But when i try to do this: chips m_doubloon(DOUBLOON); I get the following...

Using traits as types in enums

enums,polymorphism,rust,traits
Here's my code: trait UnaryOperator { fn apply(&self, expr: Expression) -> Expression; } pub enum Expression { UnaryOp(UnaryOperator, Expression), Value(i64) } Which gives the following errors: error: the trait 'core::marker::sized' is not implemented for type 'parser::UnaryOperator' note: 'parser::UnaryOperator' does not have a constant size known at compile-time I'm not sure...

How to combine and return enum value

java,enums
I have a coordinate system such as this: public enum Direction { N ( 0, 1), NE ( 1, 1), E ( 1, 0), SE ( 1, -1), S ( 0, -1), SW (-1, -1), W (-1, 0), NW (-1, 1); private int x = 0, y = 0; private...

Obj-C to Swift Bridging issues: NS_ENUM -> enum

objective-c,swift,enums,bridge
I'm using a Obj-C lib in Swift project with a bridging. All are OK except NS_ENUM with custom value: Obj-C (original) typedef NS_ENUM(NSInteger, HTTPStatusCode) { // Informational 1xx HTTPStatusCodeContinue = 100, HTTPStatusCodeSwitchingProtocols = 101, HTTPStatusCodeProcessing = 102, HTTPStatusCodeCheckpoint = 103, ... Swift (with bridging) enum HTTPStatusCode : Int { //...

Storing a String in an Enum object in java [duplicate]

java,database,string,enums
This question already has an answer here: How can I lookup a Java enum from its String value? 7 answers I have this enum Category ,a Question class, a database where question ,option, category,etc are stored. Question class has its getter() and setter() My question is how I can...

How can I ensure that each case defined in an enum class is treated, e.g. using static_assert?

c++,c++11,enums
Assume an enum class enum class MY_ENUM {FOO, BAR}; and a std::map which holds some information about each element in the enum map<MY_ENUM, MyInfoType> enumInfos; How can I ensure at compile time that for each value of the enum there is an entry in the map? I would like to...

How do you implement a Java Enumeration Abstract class and interface?

java,inheritance,enums,abstract-class
I have the following problem. I have a package with different enumeration classes in java. What is the correct approach to avoid repeting myself when adding new methods that are common to all enums? My problem: channel.java public enum Channel { channel1, channel2; } color.java public enum color{ color1, color2;...

How to send enum type to Invoke (delegate) Visual C++

visual-c++,enums,delegates
I've a function to modify a PictureBox, so I need to use a delegate. My function needs an int in order to do its job, and I've created an enum in order to define the values it can have. However, when I'm invoking it, there's a problem because it cannot...

Java Junit Failure For an Attribute Class

java,junit,enums,get
I have the class Mappa that has mappaName as an attribute (to choose from the enum Name) and a method getMappaName that returns it, when i run a test to compare one of the mappaName chosen from Name i get expected FERMI but was:null public class Mappa { private Name...

How to make a Swift String enum available in Objective-C?

objective-c,swift,enums,interop
I have this enum with String values, which will be used to tell an API method that logs to a server what kind of serverity a message has. I'm using Swift 1.2, so enums can be mapped to Objective-C @objc enum LogSeverity : String { case Debug = "DEBUG" case...

About Enum and DataAnnotation

c#,enums,data-annotations,asp.net-mvc-5.2,displayattribute
I have this Enum (Notebook.cs): public enum Notebook : byte { [Display(Name = "Notebook HP")] NotebookHP, [Display(Name = "Notebook Dell")] NotebookDell } Also this property in my class (TIDepartment.cs): public Notebook Notebook { get; set; } It's working perfectly, I just have one "problem": I created an EnumDDLFor and it's...

Hibernate map list of enums without jointable

java,hibernate,enums
I would like to map a list of enums in Hibernate in a specific way. It should be saved as a comma seperated array of strings in a single column, without using a jointable. Just like the following annotation saves a single enum value as a string in the database:...

Usage of enum name as value identifier in Objective-C

objective-c,enums,namespaces,declaration,redefinition
Referring to this post it seems that there is no possibility in Objective-C to define two enums with the same value as in this example: enum AnEnum { AnyValue }; enum AnotherEnum { AnyValue // Error: Redefinition of enumerator 'AnyValue' }; I would like to understand the backgrounds why an...

Spring JPA - default value for enum field in enum

java,spring,hibernate,jpa,enums
We have an entity with an enum field - emailCommunicationStatus, and we want to set a default value for it using JPA annotations - 'UNKNOWN'. However, when we save the entity to the DB, the value of this field is null and not . For the boolean field - isLocked...

Cannot move out of borrowed content when matching an enum

enums,rust
I'm learning this beautiful language, but have some problems. I'm trying to print out a tree (it's a LinkedList right now, but that will be fixed), but it doesn't compile. Why it doesn't work? The compiler says cannot move out of borrowed content at line NodeKind::Branch(next) => { current =...

Stackoverflow exception when using many enumarations inside my class

c#,enums,stack-overflow
Hey guys I have some enum declarations that for unknown reason to me are causing StackOverflowException. I have the following: public enum PrimaryAttribute { Strength, Agility, Intelligence } public enum Class { Tank, Fighter, Sorcerer } public class Hero { public PrimaryAttribute PrimaryAttribute { get; private set; } public Class...

Java use user input to determine enum value

java,enums
I'm currently hardcoding an enum value, which is running through a switch statement. Is it possible to determine the enum based on user input. Choice month = Choice.D; Instead of hardcoding the value D, can I use the user input here? package partyAffil; import java.io.BufferedReader; import java.io.InputStreamReader; public class partyAffil...

What is better to iterate over an EnumMap in java?

java,dictionary,enums,enum-map
Suppose I have declared an enum and corresponding emummap as: enum MyEnum { CONSTANT1, CONSTANT2, CONSTANT3; } EnumMap<MyEnum, String> MyEnumMap = new EnumMap<MyEnum, String>(MyEnum.class); I want to iterate over MyEnumMap, for example, just to print each Entry one by one. What is the best approach(fastest) to iterate over keys in...

Propagate an enum class to a higher level class

c++,oop,c++11,enums,class-design
This is a fairly basic problem but I'd like some input on what the best practice is. My issue is how do you propagate an enum from a sub-class to a higher level class so that it is visible to the main class's caller? For example, say I have a...

Difference between associated and raw values in swift enumerations

swift,enums,enumeration
Swift enumerations have both associated and raw values. But the use cases of these values is not clear to me. So I would really appreciate if anyone can explain the difference between the associated and raw values, an example would be very helpful.

GetCustomAttributes for an enum value return an empty Array

c#,enums,custom-attributes,windows-universal,windows-10
I'm currently working on upgrading a windows 8.1 universal app to a windows 10 UWP app. There is a part of code that was working perfectly before that doesn't work anymore in my Windows 10 UWP app. I have an enum that looks like this : public enum EStaticFile {...

Generating big enum classes with numbers in enum values JAXB, XJC

java,enums,xsd,jaxb,xjc
I'm trying to generate java classes using XJC and I have the following problem: I'm trying to parse this schema which is a big enum type (bigger than default typesafeEnumMaxMembers). So I use following binding: <jxb:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" version="2.1"> <!-- Raise theEnumMemberSizeCap limit --> <jxb:bindings > <jxb:globalBindings typesafeEnumMaxMembers="2000"/> </jxb:bindings> </jxb:bindings>...

What is the type of an object literal key as defined in TypeScript?

javascript,enums,typescript,webstorm,object-literal
I'm not using TypeScript as the primary language for this application, but as the type-hinting assist for JetBrains' WebStorm alongside JSDocs. I'm also using the keyMirror utility to create quasi-enum object literals. Given the following: //enums.js var keyMirror = require('keyMirror'); module.exports = { CRUDVerbs: keyMirror({ //keymirror mirrors the key to...

C# enum typo correction

c#,enums
I am sure everyone made a typo somewhere during the development and realized it after it is released. Well, I am experiencing the same issue except this problem live in the Enum options. I have a enum definition like below in C# public enum SlideShowZoomEffect { NoEffect, ZoomIn, ZoonOut }...

Importing with package name breaking enum comparison in Python

python,import,enums,package
My friend and I are making chess AIs in Python, but we're running into a mysterious problem with enums. We encode the piece types in an enum like so: Piece.py: from enum import Enum class PieceType(Enum): type_one = 1 ... def recognise_type(my_type): print("Passed ", my_type) if my_type is PieceType.type_one: print("Type...

Pass an integer instead of a enum type to a function

c++,enums
I was wondering if there is any way to pass an integer to a function which expects a enum type. I need to use this function: void SetValue(enumtypevalue){ variable = value} that was made by a work mate and the enum is something like: typedef enum { Obj1 = 0,...

Passing C# enum from C++ using mono

c#,c++,.net,enums,mono
Why can't I get the MonoMethod* for the method that takes an enum, and is there a way to list the methods that mono knows about? Here's a reduced example of what I'm trying to do. I tried different combinations of what (Windows) ildasm reported but no success. // enum.cs...

Enums in C++ - how does a function assign a value

c++,enums
I'm trying to understand a C++ code given here. Apologies if the question is too basic, but I am not a regular C++ coder. Here are two Enums defined in the code and a a few functions that operate on the Enums: ... enum Value { VALUE_ZERO = 0, VALUE_DRAW...

Storing lots of different String in one variable

java,arrays,string,enums
Is there an easier way to store multiple strings (which are all unique) in a variable other than an array or an enum? I want to be able to easily access the string also.

Enum inheritance conflict

c++,inheritance,enums
Suppose to have a base class that defines an enum like the following in its header file: class Base{ public: Base(); enum MyEnum1{ A_VALUE=1, B_VALUE=2 }; }; And a derived class that defines in a different enum the same variables but with different values: class Derived : public Base{ public:...

The “trait Clone is is not implemented” when deriving the trait Copy for Enum

enums,copy,rust
The following code: #[derive(Copy)] enum MyEnum { Test } Is giving me this error: error: the trait core::clone::Clone is not implemented for the type MyEnum [E0277] Why is that the case, and how do I fix it?...

Combobox value (binded with an enum) in an instance

c#,combobox,enums
Good day lads! I've got a question. I think I'll be saving loads of text if you would see my form, so here we go! Form: private void Form1_Load(object sender, EventArgs e) { /* Held h1 = new Held("Tank", Lanes.Top); Held h2 = new Held("ADC", Lanes.Bot); Held h3 = new...

In Swift, given a variable that is an enum, how can I tell which case it is?

swift,enums
As a practical example, suppose I define: enum Baby { case Boy (String) case Girl (String) } and then define a variable (or constant) like so: let baby1 = Baby.Boy("Joe") Now I want to pass baby1 to a function that returns a string that depends on whether baby1 is a...

JNA couldn't find the specified procedure in dll file through java

java,c#,dll,enums,jna
I am trying to access dll procedure through java but my java method is unable to find the procedure. The dll file is loaded successfully but the the procedure from C# code named Login I can't call. Below is the def of Procedure in ADHelper.dll: public static ADHelper.LoginResult Login(string UserName,...

Enum validation in Rails 4.2 doesn't work

ruby-on-rails,validation,enums
My User model looks similar to this: class User < ActiveRecord::Base enum type: [:admin, :reviewer, :super_admin ] validates :type, presence: true validates :type, inclusion: { in: User.types.keys } end When I submit anything outside the enum values, the validation doesn't stop the code from running, and I get a 500...

Exposing an enum in a QML signal

c++,qt,enums,qml
I have problems receiving the signal mySignal with the correct enum type in qml. I think I have done everything right: The enum is in a separate class, derived from QObject The enum is registered with Q_ENUMS The class containing enum is registered with qmlRegisterUncreatableType The class the signal is...

How to reduce usage of List in the code?

java,list,collections,enums,set
I have an EnumSet like this so to shuffle the elements, I need to convert it to List. EnumSet<Fruit> otherFruits = EnumSet.complementOf(CURRENT_FRUIT); Below is my code where I am doing shuffling and adding it original result list: private static List<Fruits> getFruits() { EnumSet<Fruits> local = EnumSet.of(CURRENT_FRUIT); // first element in...

Can you pass a typed array to a function within an enum in swift?

function,swift,enums,arguments
In a Swift app, I've created an enum with a function that takes an array of CLBeacon objects as it's only argument (i.e., [CLBeacon]). I get no clang errors with the enum, however when I try to use the enum, clang complains that I can't invoke the function with an...

Looping through an enum, TypeScript and JQuery

jquery,enums,typescript,ienumerable,enumeration
Hello im trying t develop a straight forward todo app using TypeScript and JQuery. I have an enum that lists task types: export enum TaskType { FrontEnd, BackEnd, Designer }; However looping through the emum using jquery.each or for loop, i get the following result, (values then indexes): FrontEnd, BackEnd,...

How fill combobox using with enum - show integers(values) of enum in combobox

c#,winforms,combobox,enums
Here is my enum : Name = Value public enum BitRates { bitrate_32 = 32, bitrate_40 = 40, bitrate_48 = 48, bitrate_56 = 56, bitrate_64 = 64, bitrate_80 = 80, bitrate_96 = 96, bitrate_112 = 112, bitrate_128 = 128, bitrate_160 = 160, bitrate_192 = 192, bitrate_224 = 224, bitrate_256 =...

Enum class members appearing as defined types not enum members

python,python-2.7,enums
I'm implementing an Enum class but it keeps showing up as normal class variables. For example: from enum import Enum class test(Enum): one = 1 two = 2 thr = "three" using this I get: >>> print type(test.one) <type 'int'> >>> print repr(test.one) 1 >>> print test.one 1 >>> print...

What's the cleanest way to set up an enumeration in Python? [duplicate]

python,enums,enumeration
This question already has an answer here: How can I represent an 'Enum' in Python? 43 answers I'm relatively new to Python and I was interested in finding out the simplest way to create an enumeration. The best I've found is something like: (APPLE, BANANA, WALRUS) = range(3) Which...

Implementing enum-based singleton

java,enums,singleton
J. Bloch in his Effective Java suggests we use an enum-based singleton implementation. For instance: public enum Application { INSTANCE; //methods, fields } This implementation is nice in the case of serialization because enums provide us with the capability of serialization by default (and we don't have to be afraid...

WPF DataTrigger using enum fails

c#,wpf,enums,datatrigger
The case: I have a customized ToggleButton that uses a DrawingImage to draw a hexagon to use as template background making it a hexagonally shaped toggle button. I want to change the color (Brush) and border (Pen) of the drawing so the button looks different for different purposes. There’s a...

How to set saved value for EnumDropDownListFor property in edit record

c#,asp.net-mvc,asp.net-mvc-4,enums
I have created Enum for blood group. I have a problem that how to set value which I am getting from data base for Blood Group field in controller. How to set value for Enum_Member_BloodGroup = ? in contoller's Edit action. I am getting data in s.BloodGroup Enum public enum...

Can Scala enumeration maps to an Integer like Java?

java,scala,enums,enumeration
I have an original Java enumeration class, which I can get the corresponding integer value using: Integer blackInteger = ColorEnum.BLACK.getValue() public enum ColorEnum { BLACK(0), BLUE(1), RED(2); private int value; private ColorEnum(int value) { this.value = value; } public int getValue() { return value; } } I then tried to...

WPF Multiple Enum Flags to Converter Parameter?

c#,wpf,enums,flags,valueconverter
I have a control which I need visible if an enum value is (A | B | C). I know how to bind the visibility of a control to a SINGLE enum (A) using a converter. How do I go about doing the same for this case? What would go...

Creating interface for concrete class with enum C#?

c#,interface,dependency-injection,enums,separation-of-concerns
Pardon any mistakes, this is one of my first questions. I would really appreciate some guidance here. I tried searching for previous questions, but I couldn't quite word the question correctly. I'm trying to create a simple Logger with an interface class, but I want to have the interface and...

Switch Statement Not Handling NS_ENUM values

objective-c,enums,switch-statement
I have an enum defined in a objective-c header that looks like this: #import <UIKit/UIKit.h> #import <MapKit/MapKit.h> @interface CustomerAndProspectMapViewController : UIViewController<MKMapViewDelegate> typedef NS_ENUM(NSInteger, TypeEnum) { PROSPECT, CUSTOMER }; @end Then in the implementation I have a function that takes a TypeEnum as a parameter and uses a switch to run...

Convert To Enum Option Not Found In Model

c#,entity-framework,visual-studio-2013,enums
I am using EntityFramework 6 and .NET Framework 4.5. I have created an enum in Model Browser and it appears in Enum Types. But when I right-click on the target field in my diagram, there is no such option as Convert To Enum option like in here.

Is there a better way to show enums in a control, eg combobox

c#,enums,winrt-xaml,win-universal-app
My goal is to present to the user the list of available enum's in a user friendly string format rather than the code value, and display said property when required. Given that the DataAnnotations namespace doesn't exist in 8.1 universal apps, I can't simply apply [Display(Name="Nice display string")]. I have...

Nonfailable enum initializer with default value

swift,enums
Is there a way to define an enum, when initialized from rawValue will default to some value instead of failing? Useful in cases where the value may be unexpected (i.e. server API errors)

Radio Button For Enum (DataAnnotation)

c#,enums,radio-button,data-annotations,html-helper
I have this enum: [Display(Name = "Primary incomplete")] PrimaryIncomplete = 1, [Display(Name = "Primary")] Primary = 2, [Display(Name = "Secondary incomplete")] SecondaryIncomplete = 3, [Display(Name = "Secondary")] Secondary = 4, [Display(Name = "Higher education incomplete")] HigherEducationIncomplete = 5, [Display(Name = "Higher education")] HigherEducation = 6, [Display(Name = "Post-Graduation/MBA")] PostGraduationMBA =...

ES6 read-only enums that can map value to name

enums,ecmascript-6
I would like to define an enum-like structure in JS, but have two requirements: The values be read-only, i.e. no users can assign to them. The values (0, 1, 2, ...) can be mapped back into the names (as with Java's name method) The methods I know to create enums...

Override/reimplement enum in derived class

c++,oop,enums
I'm developing a database program for my college project. I have base class which represents Invoice and derived class for representing a CorrectedInvoice. Finally I want to store the data to the file, so I use enums to indicate in what order are they stored: enum FIELD_ORDER { ID, IVOICE_NUM,...

Function with enum return type can not be resolved in a class of C++

c++,class,enums
My check.h file has an enum as a private variable. I do not know what to do to declare enum as a global entity. I declare a function in check.cpp with enum return type. But it is giving the error as follows. Multiple markers at this line Type 'TStatus'...

Passing an enum type as a parameter? c++

c++,enums
For example i create an enum in one function and save them on an array of animals type, int this case just the cow value, and then i want to pass that array into function2 as a parameter, how do i do it? void function1() { enum animals{cow,cat,dog}; animals array[3];...

Cant bind enum to combobox wpf mvvm

c#,wpf,mvvm,combobox,enums
A have read a lot of method about the ways of binding enum to combobox. So now in .Net 4.5 it should be pretty ease. But my code dont work. Dont really understand why. xaml: <Window x:Class="SmartTrader.Windows.SyncOfflineDataWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="SyncOfflineDataWindow" Height="300" Width="300"> <Grid> <StackPanel> <ComboBox ItemsSource="{Binding StrategyTypes}" SelectedItem="{Binding StrategyType}" />...

Enum not returning value [duplicate]

c++,enums
This question already has an answer here: What is the proper function for comparing two C-style strings? 2 answers AGK_Delete.h class AGK_Delete { private: enum OBJTYPE { text, button }; OBJTYPE TypeConversion(const char * type); }; AGK_Delete.cpp AGK_Delete::OBJTYPE AGK_Delete::TypeConversion(const char * type) { std::cout << type; // it gives...