I'd like to get the same behaviour as cpp:
enum dxgi_format_gli
{
DXGI_FORMAT_R64_UINT_GLI = 1,
DXGI_FORMAT_R64_SINT_GLI
}
where DXGI_FORMAT_R64_UINT_GLI gets 1 and the next gets 2
the closest I got is:
private var counter: Int = 2;
enum class dxgi_format_gli(i: Int = counter++) {
DXGI_FORMAT_R64_UINT_GLI(1),
DXGI_FORMAT_R64_SINT_GLI()
}
However I'd like it, of course, to be dynamic, that is whenever I call the constructor with a parameter, save that one in counter and all the following constructors increment and get it..
I already made it in java:
public enum Dxgi_format_gli {
DXGI_FORMAT_R64_UINT_GLI(1),
DXGI_FORMAT_R64_SINT_GLI;
public final int value;
private static class Counter {
private static short value = 0;
}
private Dxgi_format_gli() {
value = Counter.value;
Counter.value++;
}
private Dxgi_format_gli(int value) {
this.value = value;
Counter.value++;
}
}
But I didn't make it using Kotlin..
Every enum already has an auto-generated property ordinal:
enum class A {a, b, c}
A.a.ordinal // 0
A.b.ordinal // 1
A.c.ordinal // 2
So technically the easiest way to get what you want is dxgi_format_gli.DXGI_FORMAT_R64_UINT_GLI.ordinal + 1 (I have no idea why don't you want to start with 0 0_o)
You may replace the code in the #griffio's answer with this:
enum class Dxgi_format_gli {
DXGI_FORMAT_R64_UINT_GLI,
DXGI_FORMAT_R64_SINT_GLI;
val value = ordinal + 1
}
I think you just need to set the value and move the increment around to make it work - so the initial counter and value are the same.
enum class Dxgi_format_gli {
DXGI_FORMAT_R64_UINT_GLI(1),
DXGI_FORMAT_R64_SINT_GLI;
val value: Int
private object Counter {
var value: Int = 0
}
constructor() {
Counter.value++
value = Counter.value.toInt()
}
private constructor(value: Int) {
this.value = value
Counter.value = value
}
}
Related
public class A
{
public int A1 { get; set; }
public int A2 { get; set; }
}
static void Main(string[] args)
{
int i = 0;
Method1(i);
Console.WriteLine($"i={i}");
var str = "This is a string";
Method2(str);
Console.WriteLine(str);
var a = new A()
{
A1 = 5,
A2 = 6
};
Method3(a);
Console.WriteLine($"a.A1={a.A1}, a.A2={a.A2}");
Method4(a);
Console.WriteLine($"a.A1={a.A1}, a.A2={a.A2}");
Method5(ref a);
Console.WriteLine($"a.A1={a.A1}, a.A2={a.A2}");
}
private static void Method5(ref A a)
{
a = new A()
{
A1 = 10,
A2 = 11
};
}
private static void Method4(A a)
{
a = new A()
{
A1 = 10,
A2 = 11
};
}
private static void Method3(A a)
{
a.A1 = 6;
}
private static void Method2(string str)
{
str = "This is a new string";
}
private static void Method1(int i)
{
i = 5;
}
the output I expect vs the real output
I thought that output will be :
i=0
This is a string
a.A1=5, a.A2=6
a.A1=5, a.A2=6
a.A1=10, a.A2=11
but the output is :
i=0
This is a string
a.A1=6, a.A2=6
a.A1=6, a.A2=6
a.A1=10, a.A2=11
I will be glad to get explanation how method3 and method 4 are working.
Thanks a lot !
Let us take a look at Method3(a)
private static void Method3(A a)
{
a.A1 = 6;
}
The previous value was 5, right? Now it's declared as 6 and the official value is now 6. You are referring to the variable A1 and giving it a new value!
Console.WriteLine($"a.A1={a.A1}, a.A2={a.A2}");
So basically you override the new value (6) with the old value (5), because you're using a reference type.
So when we hop into Method4(a) the values are A1 = 6 and A2 = 6. The reason to why Method4 isn't changing to A1 = 10 and A2 = 11 is because you are not referring to anything. There is no reference type.
It doesn't know that you're referring to the object a just because you passed the variable name as an argument.
So you've pretty much initialised a new object of class A in Method4 with no references. When it has no references, it doesn't know where to store the values in Method(4) hence why the values aren't changing.
If you look at Method5(a), you use the "ref" keyword that means the ref keyword indicates that a value is passed by reference. The ref points at the object you have initialised at first.
I know it might be confused, but I can highly recommend using debug and then follow it step-by-step. Take your time, note down what is changing and like that you will understand much better.
Read these articles:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref#passing-an-argument-by-reference
https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references
If you find my post helpful, please upvote it.
Happy coding :-)
In Protobuf3 zero is the default value for numeric types, and so they are filtered out when serialized.
I have an application where I need to send a value only when it has changed. For example, x was 1, now x is 0, send this value.
It isn't possible to send only the delta, eg -1, because some of these values are floats or doubles, and we do not want to accrue errors.
There are over 200 different variables in some classes I need to serialize, so solutions like "add a boolean to flag which fields have changed" are possible but not fun. Other suggestions that have a large amount of per-field work or processing are undesirable too.
Is there a simple mechanism to tell protobuf3 to explicitly keep a value even though it is the default value?
Possible solutions:
Send the entire class each time. The main downside here is some fields may have a lot of data.
Use a boolean "has changed" in the schema to indicate if a variable has changed, even if it is 0
Use a magic value. Terrible idea, but possible. Not going to do this.
If you need to distinguish 0 and null then you can use proto3 wrapper types: https://developers.google.com/protocol-buffers/docs/reference/csharp-generated#wrapper_types
There are special wrapper types for such case: StringWrapper, Int32Wrapper and etc. All of the wrapper types that correspond to C# value types (Int32Wrapper, DoubleWrapper, BoolWrapper etc) are mapped to Nullable<T> where T is the corresponding non-nullable type.
Since you tagged protobuf-net, you can do this at the field level:
[ProtoMember(..., IsRequired = true)]
// your field
or globally (here I'm assuming you are using the default model, which is a pretty safe assumption usually):
RuntimeTypeModel.Default.ImplicitZeroDefault = false;
and you're done;
Note: if you're interested in deltas, you can also do this conditionally - for a property Foo, you can add:
private bool ShouldSerializeFoo() { /* your rules here */ }
(this is a name-based pattern used by many serializers and other tools; in some scenarios, it needs to be public, but protobuf-net is usually happy with it non-public)
As a non-trivial example of an object that tracks delta state internally:
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.IO;
static class P
{
static void Main()
{
var obj = new MyType
{
Foo = 42,
Bar = "abc",
Blap = DateTime.Now
};
ShowPayloadSize("original", obj);
obj.MarkClean();
ShowPayloadSize("clean", obj);
obj.Foo = 42;
obj.Bar = "abc";
ShowPayloadSize("set property to same", obj);
obj.Foo = 45;
obj.Bar = "new value";
ShowPayloadSize("set property to different", obj);
obj.MarkClean();
ShowPayloadSize("clean again", obj);
}
static void ShowPayloadSize<T>(string caption, T obj)
{
using var ms = new MemoryStream();
Serializer.Serialize(ms, obj);
Console.WriteLine($"{caption}: {ms.Length} bytes");
}
}
[ProtoContract]
public class MyType
{
private int _dirty = -1; // treat everything as dirty by default
public void MarkClean() => _dirty = 0;
public bool IsDirty => _dirty != 0;
private bool ShouldSerialize(int flag) => (_dirty & flag) != 0;
private void Set<T>(ref T field, T value, int flag)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
_dirty |= flag;
}
}
[ProtoMember(1)]
public int Foo
{
get => _foo;
set => Set(ref _foo, value, 1 << 0);
}
public bool ShouldSerializeFoo() => ShouldSerialize(1 << 0);
private int _foo;
[ProtoMember(2)]
public string Bar
{
get => _bar;
set => Set(ref _bar, value, 1 << 1);
}
public bool ShouldSerializeBar() => ShouldSerialize(1 << 1);
private string _bar;
[ProtoMember(3)]
public DateTime Blap
{
get => _blap;
set => Set(ref _blap, value, 1 << 2);
}
public bool ShouldSerializeBlap() => ShouldSerialize(1 << 2);
private DateTime _blap;
}
I have this viewModel:
public class PhrasesFrameViewModel : ObservableProperty
{
int points1;
public int Points1
{
get { return points1; }
set
{
if (value != points1)
{
points1 = value;
NotifyPropertyChanged("Points1");
}
}
}
When the application starts the value of points1 is set to 0 here:
card.Points1 = App.correctAnswerPerPhrase; // returns a 0
When I look on my screen I see nothing and then debugging I see it's because the setter is checking to see if value (0) is not equal to the default value of points1 (0);
So how can I make it so a 0 appears on the screen when the value is 0 at the start ?
Technically, your code should still work; as during load the value retrieved will be 0 only. But, if you still want to be able to notify on set value; you can use nullable int as type.
int? points1 = null;
public int? Points1
{
get { return points1; }
set
{
if (value != points1)
{
points1 = value;
NotifyPropertyChanged("Points1");
}
}
}
EDIT 1
If type of property on target control is string (for e.g. Entry.Text); then you will need to convert value to string. You can either do that by creating a converter, or a wrapper property.
int points1;
public int Points1
{
get { return points1; }
set
{
if (value != points1)
{
points1 = value;
NotifyPropertyChanged("Points1");
NotifyPropertyChanged("Points1Str");
}
}
}
// bind this property to control
public string Points1Str
{
get { return points1.ToString(); }
set {
int parsedValue = 0;
if (int.TryParse(value, out parsedValue))
points1 = parsedValue;
}
}
I want to summarize rather than compress in a similar manner to run length encoding but in a nested sense.
For instance, I want : ABCBCABCBCDEEF to become: (2A(2BC))D(2E)F
I am not concerned that an option is picked between two identical possible nestings E.g.
ABBABBABBABA could be (3ABB)ABA or A(3BBA)BA which are of the same compressed length, despite having different structures.
However I do want the choice to be MOST greedy. For instance:
ABCDABCDCDCDCD would pick (2ABCD)(3CD) - of length six in original symbols which is less than ABCDAB(4CD) which is length 8 in original symbols.
In terms of background I have some repeating patterns that I want to summarize. So that the data is more digestible. I don't want to disrupt the logical order of the data as it is important. but I do want to summarize it , by saying, symbol A times 3 occurrences, followed by symbols XYZ for 20 occurrences etc. and this can be displayed in a nested sense visually.
Welcome ideas.
I'm pretty sure this isn't the best approach, and depending on the length of the patterns, might have a running time and memory usage that won't work, but here's some code.
You can paste the following code into LINQPad and run it, and it should produce the following output:
ABCBCABCBCDEEF = (2A(2BC))D(2E)F
ABBABBABBABA = (3A(2B))ABA
ABCDABCDCDCDCD = (2ABCD)(3CD)
As you can see, the middle example encoded ABB as A(2B) instead of ABB, you would have to make that judgment yourself, if single-symbol sequences like that should be encoded as a repeated symbol or not, or if a specific threshold (like 3 or more) should be used.
Basically, the code runs like this:
For each position in the sequence, try to find the longest match (actually, it doesn't, it takes the first 2+ match it finds, I left the rest as an exercise for you since I have to leave my computer for a few hours now)
It then tries to encode that sequence, the one that repeats, recursively, and spits out a X*seq type of object
If it can't find a repeating sequence, it spits out the single symbol at that location
It then skips what it encoded, and continues from #1
Anyway, here's the code:
void Main()
{
string[] examples = new[]
{
"ABCBCABCBCDEEF",
"ABBABBABBABA",
"ABCDABCDCDCDCD",
};
foreach (string example in examples)
{
StringBuilder sb = new StringBuilder();
foreach (var r in Encode(example))
sb.Append(r.ToString());
Debug.WriteLine(example + " = " + sb.ToString());
}
}
public static IEnumerable<Repeat<T>> Encode<T>(IEnumerable<T> values)
{
return Encode<T>(values, EqualityComparer<T>.Default);
}
public static IEnumerable<Repeat<T>> Encode<T>(IEnumerable<T> values, IEqualityComparer<T> comparer)
{
List<T> sequence = new List<T>(values);
int index = 0;
while (index < sequence.Count)
{
var bestSequence = FindBestSequence<T>(sequence, index, comparer);
if (bestSequence == null || bestSequence.Length < 1)
throw new InvalidOperationException("Unable to find sequence at position " + index);
yield return bestSequence;
index += bestSequence.Length;
}
}
private static Repeat<T> FindBestSequence<T>(IList<T> sequence, int startIndex, IEqualityComparer<T> comparer)
{
int sequenceLength = 1;
while (startIndex + sequenceLength * 2 <= sequence.Count)
{
if (comparer.Equals(sequence[startIndex], sequence[startIndex + sequenceLength]))
{
bool atLeast2Repeats = true;
for (int index = 0; index < sequenceLength; index++)
{
if (!comparer.Equals(sequence[startIndex + index], sequence[startIndex + sequenceLength + index]))
{
atLeast2Repeats = false;
break;
}
}
if (atLeast2Repeats)
{
int count = 2;
while (startIndex + sequenceLength * (count + 1) <= sequence.Count)
{
bool anotherRepeat = true;
for (int index = 0; index < sequenceLength; index++)
{
if (!comparer.Equals(sequence[startIndex + index], sequence[startIndex + sequenceLength * count + index]))
{
anotherRepeat = false;
break;
}
}
if (anotherRepeat)
count++;
else
break;
}
List<T> oneSequence = Enumerable.Range(0, sequenceLength).Select(i => sequence[startIndex + i]).ToList();
var repeatedSequence = Encode<T>(oneSequence, comparer).ToArray();
return new SequenceRepeat<T>(count, repeatedSequence);
}
}
sequenceLength++;
}
// fall back, we could not find anything that repeated at all
return new SingleSymbol<T>(sequence[startIndex]);
}
public abstract class Repeat<T>
{
public int Count { get; private set; }
protected Repeat(int count)
{
Count = count;
}
public abstract int Length
{
get;
}
}
public class SingleSymbol<T> : Repeat<T>
{
public T Value { get; private set; }
public SingleSymbol(T value)
: base(1)
{
Value = value;
}
public override string ToString()
{
return string.Format("{0}", Value);
}
public override int Length
{
get
{
return Count;
}
}
}
public class SequenceRepeat<T> : Repeat<T>
{
public Repeat<T>[] Values { get; private set; }
public SequenceRepeat(int count, Repeat<T>[] values)
: base(count)
{
Values = values;
}
public override string ToString()
{
return string.Format("({0}{1})", Count, string.Join("", Values.Select(v => v.ToString())));
}
public override int Length
{
get
{
int oneLength = 0;
foreach (var value in Values)
oneLength += value.Length;
return Count * oneLength;
}
}
}
public class GroupRepeat<T> : Repeat<T>
{
public Repeat<T> Group { get; private set; }
public GroupRepeat(int count, Repeat<T> group)
: base(count)
{
Group = group;
}
public override string ToString()
{
return string.Format("({0}{1})", Count, Group);
}
public override int Length
{
get
{
return Count * Group.Length;
}
}
}
Looking at the problem theoretically, it seems similar to the problem of finding the smallest context free grammar which generates (only) the string, except in this case the non-terminals can only be used in direct sequence after each other, so e.g.
ABCBCABCBCDEEF
s->ttDuuF
t->Avv
v->BC
u->E
ABABCDABABCD
s->ABtt
t->ABCD
Of course, this depends on how you define "smallest", but if you count terminals on the right side of rules, it should be the same as the "length in original symbols" after doing the nested run-length encoding.
The problem of the smallest grammar is known to be hard, and is a well-studied problem. I don't know how much the "direct sequence" part adds to or subtracts from the complexity.
I'd like to split a sequence in C# to a sequence of sequences using LINQ. I've done some investigation, and the closest SO article I've found that is slightly related is this.
However, this question only asks how to partition the original sequence based upon a constant value. I would like to partition my sequence based on an operation.
Specifically, I have a list of objects which contain a decimal property.
public class ExampleClass
{
public decimal TheValue { get; set; }
}
Let's say I have a sequence of ExampleClass, and the corresponding sequence of values of TheValue is:
{0,1,2,3,1,1,4,6,7,0,1,0,2,3,5,7,6,5,4,3,2,1}
I'd like to partition the original sequence into an IEnumerable<IEnumerable<ExampleClass>> with values of TheValue resembling:
{{0,1,2,3}, {1,1,4,6,7}, {0,1}, {0,2,3,5,7}, {6,5,4,3,2,1}}
I'm just lost on how this would be implemented. SO, can you help?
I have a seriously ugly solution right now, but have a "feeling" that LINQ will increase the elegance of my code.
Okay, I think we can do this...
public static IEnumerable<IEnumerable<TElement>>
PartitionMontonically<TElement, TKey>
(this IEnumerable<TElement> source,
Func<TElement, TKey> selector)
{
// TODO: Argument validation and custom comparisons
Comparer<TKey> keyComparer = Comparer<TKey>.Default;
using (var iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
yield break;
}
TKey currentKey = selector(iterator.Current);
List<TElement> currentList = new List<TElement> { iterator.Current };
int sign = 0;
while (iterator.MoveNext())
{
TElement element = iterator.Current;
TKey key = selector(element);
int nextSign = Math.Sign(keyComparer.Compare(currentKey, key));
// Haven't decided a direction yet
if (sign == 0)
{
sign = nextSign;
currentList.Add(element);
}
// Same direction or no change
else if (sign == nextSign || nextSign == 0)
{
currentList.Add(element);
}
else // Change in direction: yield current list and start a new one
{
yield return currentList;
currentList = new List<TElement> { element };
sign = 0;
}
currentKey = key;
}
yield return currentList;
}
}
Completely untested, but I think it might work...
alternatively with linq operators and some abuse of .net closures by reference.
public static IEnumerable<IEnumerable<T>> Monotonic<T>(this IEnumerable<T> enumerable)
{
var comparator = Comparer<T>.Default;
int i = 0;
T last = default(T);
return enumerable.GroupBy((value) => { i = comparator.Compare(value, last) > 0 ? i : i+1; last = value; return i; }).Select((group) => group.Select((_) => _));
}
Taken from some random utility code for partitioning IEnumerable's into a makeshift table for logging. If I recall properly, the odd ending Select is to prevent ambiguity when the input is an enumeration of strings.
Here's a custom LINQ operator which splits a sequence according to just about any criteria. Its parameters are:
xs: the input element sequence.
func: a function which accepts the "current" input element and a state object, and returns as a tuple:
a bool stating whether the input sequence should be split before the "current" element; and
a state object which will be passed to the next invocation of func.
initialState: the state object that gets passed to func on its first invocation.
Here it is, along with a helper class (required because yield return apparently cannot be nested):
public static IEnumerable<IEnumerable<T>> Split<T, TState>(
this IEnumerable<T> xs,
Func<T, TState, Tuple<bool, TState>> func,
TState initialState)
{
using (var splitter = new Splitter<T, TState>(xs, func, initialState))
{
while (splitter.HasNext)
{
yield return splitter.GetNext();
}
}
}
internal sealed class Splitter<T, TState> : IDisposable
{
public Splitter(IEnumerable<T> xs,
Func<T, TState, Tuple<bool, TState>> func,
TState initialState)
{
this.xs = xs.GetEnumerator();
this.func = func;
this.state = initialState;
this.hasNext = this.xs.MoveNext();
}
private readonly IEnumerator<T> xs;
private readonly Func<T, TState, Tuple<bool, TState>> func;
private bool hasNext;
private TState state;
public bool HasNext { get { return hasNext; } }
public IEnumerable<T> GetNext()
{
while (hasNext)
{
Tuple<bool, TState> decision = func(xs.Current, state);
state = decision.Item2;
if (decision.Item1) yield break;
yield return xs.Current;
hasNext = xs.MoveNext();
}
}
public void Dispose() { xs.Dispose(); }
}
Note: Here are some of the design decisions that went into the Split method:
It should make only a single pass over the sequence.
State is made explicit so that it's possible to keep side effects out of func.