Все вопросы: [flags]
51 вопросов
Объяснение флагов в Go
Кто-нибудь может объяснить флаги в Go? flag.Parse() var omitNewline = flag.Bool("n", false, "don't print final newline")
Элегантные схемы разрешений в Интернете
В настоящее время я пишу веб-приложение, содержащее около 6–12 страниц.Я хочу, чтобы на каждой из этих страниц пользователь мог выполнять некоторые (или все) из следующих действий: просмотр, добавление, обновление и удаление. Текущая схема разрешений, о которой я подумал, имеет целое число в ...
Проверка значения перечисления [Flags] для одного значения
Если у меня есть enum, помеченный как [Flags], есть ли в .NET способ проверить значение этого типа, чтобы увидеть, содержит ли оно только одно значение?Я могу получить желаемый результат с помощью подсчета битов, но я бы предпочел использовать встроенные функции, если это возможно. При динами...
Флаг Java для включения расширенной информации об отладке сериализации
В настоящее время я борюсь с репликацией HTTP-сеанса на tomcat со сложными объектами. Некоторые объекты реализуют Serializable, но содержат несериализуемые члены. К сожалению, трассировки стека по умолчанию не предоставляют много полезной информации. есть флаг -XX: ????для включения по...
Флаги, перечисление (C)
Я не очень привык программировать с помощью флагов, но думаю, что нашел ситуацию, в которой они могут быть полезны: У меня есть несколько объектов, которые регистрируются как слушатели определенных событий.Какие события они регистрируют, зависит от переменной, которая им отправляется при созд...
Флаги перечисления в JavaScript
Мне нужно эмулировать тип перечисления в Javascript, и подход кажется довольно простым: var MyEnum = {Left = 1; Right = 2; Top = 4; Bottom = 8} Теперь в C # я могу комбинировать эти значения следующим образом: MyEnum left_right = MyEnum.Left | MyEnum.Right и затем я могу проверить,...
Как использовать разные режимы ifstream в c ++?
Согласно справке, если я использую ifstream infile ( "test.txt" , ifstream::in );, это будет Allow input operations on the stream.. Но каковы некоторые примеры "операций ввода"? Подходит ли ifstream infile ( "test.txt" , ifstream::in | ifstream::binary ); синтаксис для использования нескольки...
How to make functions with flag parameters? (C++)
How could I make a function with flags like how Windows' CreateWindow(...style | style,...), for example, a createnum function: int CreateNum(flag flags) //??? { int num = 0; if(flags == GREATER_THAN_TEN) num = 11; if(flags == EVEN && ((num % 2) == 1) num++; ...
How to Compare Flags in C#? (part 2)
Bit flags are a little difficult to understand :) I know about this and this questions and I do understand the answers and I even followed this article from a good friend of mine. But I still cant figure it out when I need to "evolute" more than the standard... What I'm trying to do is this: ...
How to strip a list of tuple with python?
I have an array with some flag for each case. In order to use print the array in HTML and use colspan, I need to convert this : [{'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'...
WPF ComboBox/ListBox with MultiSelect based on Enum with Flags
So I may be pushing the boundaries just a bit... Basically I have the following enum, declared in C# code: [Flags] public enum FlaggedEnum : int { Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8, ... Option16 = 32768, None = 0 } This enum is a member of an objec...
TCP flags present in the header
on my ubuntu 9.04 the /usr/include/netinet/tcp.h defines the tcp header as follows struct tcphdr { u_int16_t source; u_int16_t dest; u_int32_t seq; u_int32_t ack_seq; # if __BYTE_ORDER == __LITTLE_ENDIAN u_int16_t res1:4; u_int16_t doff:4; u_int16_t fin:1; u_in...
Map Enum to [Flags] Enum
I have an Enum, suppose: public enum ItemStatus { Available, Unavailable } I have a method that returns a list of those TVs, based on a filter. And a filter is represented by an Enum: [Flags] public enum ItemStatusFilter { Available = 1, Unavailable = 2 } Question: what is a slick w...
How do I make a Rails ActiveRecord dependent on an attribute?
I have created an ActiveRecord for a customer, and now they would like it so when it's destroyed, it is actually kept around for a manual rollback. What I would like to do is create a boolean attribute called 'active', and it defaults to 1. When a record is destroyed, the attribute is toggled t...
How to use flags enums in Linq to Entities queries?
I have a [Flags] enum like this: [Flags] public enum Status { None = 0, Active = 1, Inactive = 2, Unknown = 4 } A Status enum may contain two values such as: Status s = Status.Active | Status.Unknown; Now I need to create a linq query (LINQ to ADO.NET Entities) and ask for records ...
flagsattribute - negative values?
I have a enum with a flagsattribute, which i use to represent permissions. I use it to compare if (CurrentPermissions & Permission1 == Permission1) etc... [FlagsAttribute] enum MyPermission { None = 0, Permission1 = 1, Permission2 = 2, Permission3 = 4, Permission4 = 8,... ..........
Using binary flags to represent states, options, etc
If I wanted to represent states or options or something similar using binary "flags" so that I could pass them and store them to an object like OPTION1 | OPTION2 where OPTION1 is 0001 and OPTION2 is 0010, so that what gets passed is 0011, representing a mix of the options. How would I do this in...
Why use flags+bitmasks rather than a series of booleans?
Given a case where I have an object that may be in one or more true/false states, I've always been a little fuzzy on why programmers frequently use flags+bitmasks instead of just using several boolean values. It's all over the .NET framework. Not sure if this is the best example, but the .NET...
How to check if any flags of a flag combination are set?
Let's say I have this enum: [Flags] enum Letters { A = 1, B = 2, C = 4, AB = A | B, All = A | B | C, } To check if for example AB is set I can do this: if((letter & Letters.AB) == Letters.AB) Is there a simpler way to check if any of the flags of a combined flag...
Efficient way to find the flags enum length?
Consider this: [Flags] enum Colors { Red=1, Green=2, Blue=4 } Colors myColor=Colors.Red|Colors.Blue; Currently, I'm doing it as follows: int length=myColors.ToString().Split(new char[]{','}).Length; But I hope there is a more efficient way of finding the length, maybe based on ...
Serialize [Flags] enumeration as string
Is there a way to specify that a [Flags] enumeration field in a class should be serialized as the string representation (e.g. "Sunday,Tuesday") rather than the integer value (e.g. 5)? To be more specific, when returning the following SomeClass type in a web service, I want to get a string field ...
Mutually exclusive flags on file_put_contents?
On the file_put_contents() documentation, it says the following: FILE_APPEND: Mutually exclusive with LOCK_EX since appends are atomic and thus there is no reason to lock. LOCK_EX: Mutually exclusive with FILE_APPEND. Yet, a couple of lines bellow I see the following code: <?...
Should command line options in POSIX-style operating systems be underscore style?
Should the name of command line options for a program in a POSIX-style operating system be underscore-style, like --cure_world_hunger or maybe some other style? --cureworldhunger --cure-world-hunger --cureWorldHunger What's most common? What's better style? What's more Bash-friendly (if suc...
Should flags in POSIX-style operating systems be prefixed by "no" or "no_"?
When you have a boolean option and a flag for setting it to false by prefixing "no" to the name, should it be "no" or "no_"? What's most commonly used or better style? For example: --no_foo or --nofoo
Использование побитового флага для первичного ключа?
Я разрабатываю базу данных и думал о необходимости установления связи "один ко многим". Традиционно я использовал обычный PK (как GUID) и настраивал отношения, но вместо этого мне было интересно, если это сделать, почему бы не использовать побитовый флаг в качестве PK. Связь будет потеряна, н...
Сравнение флагов перечисления в C #
Мне нужно определить, установлен ли флаг в значении перечисления, тип которого отмечен атрибутом Flag. Обычно это делается так: (value & flag) == flag Но так как мне нужно сделать это с помощью общего (иногда во время выполнения у меня есть только ссылка "Enum". Я не могу найти про...
Флаги в Python
Я работаю с большой матрицей (250x250x30 = 1875000 ячеек), и мне нужен способ установить произвольное количество флагов для каждой ячейки в этой матрице, простым в использовании и достаточно экономичным способом. . Моим первоначальным планом был массив списков размером 250x250x30, каждый элем...
Выполнение двоичного ИЛИ в COBOL с данными Pic X
У меня есть несколько определенных флагов (в файле заголовка, который находится вне моего контроля), которые выглядят примерно так: * * OPTVAL field for IPV6_ADDR_PREFERENCES_FLAGS * 01 IPV6-ADDR-PREFERENCES-FLAGS PIC X(4). * * IPV6_ADDR_PREFERENCES_FLAGS mappings * 77 IPV6-...
Включить Enum (с атрибутом Flags) без объявления всех возможных комбинаций?
как включить перечисление с установленным атрибутом flags (точнее, используемым для битовых операций)? Я хочу иметь возможность задействовать все случаи в переключателе, который соответствует заявленным значениям. Проблема в том, что если у меня есть следующее перечисление [Flags()]publ...
Ошибка компиляции при переносе с gfortran на ifort
Я пытаюсь перенести программу с gfortran на ifort (Intel Fortran Compiler 11). Я застрял с двумя файлами, которые компилируются только с помощью gfortran: gfortran -x f77 -c daedrid.ff gfortran -x f77-cpp-input -c daedris.ff когда я пытаюсь запустить компилятор Intel fortran с этими файла...