error: Return value transfers ownership but method return type hasn't been declared to transfer ownership - vala

The following code:
public string add_button_tooltip_markup {
get { return add_button.get_tooltip_markup (); }
set { add_button.tooltip_markup = value; }
}
Gives me the following error:
error: Return value transfers ownership but method return type hasn't been declared to transfer ownership
get { return add_button.get_tooltip_markup (); }
I'm using Vala 0.40.10.
What's the best way to solve this in Vala?

Mark the getter as owned, as follows:
public string add_button_tooltip_markup {
owned get { return add_button.get_tooltip_markup (); }
set { add_button.tooltip_markup = value; }
}
See the following page for more detail:
https://wiki.gnome.org/Projects/Vala/ReferenceHandling

Related

C# Indexers with Ref Return Gets that also Support Sets

Am I doing something wrong here, or as of C# 7.2 Indexers that return by ref and allow set are not supported?
Works:
public ref byte this[int index] {
get {
return ref bytes[index];
}
}
Works too:
public byte this[int index] {
get {
return bytes[index];
}
set {
bytes[index] = value;
}
}
Fails:
public ref byte this[int index] {
get {
return ref bytes[index];
}
set { //<-- CS8147 Properties which return by reference cannot have set accessors
bytes[index] = value;
}
}
Fails too:
public ref byte this[int index] {
get {
return ref bytes[index];
}
}
public byte this[int index] { //<-- CS0111 Type already defines a member called 'this' with the same parameter types
set {
bytes[index] = value;
}
}
So, is there no way to have a ref return yet allow the indexer also support Set?
As #IvanStoev correctly pointed out, there is no need for set, since the value is returned by reference. Therefore the caller of the indexer has complete control over the returned value and can therefore can assign it a new value, with the changes being reflected in the underlying data structure (whose indexer was being called) since the value was returned by reference and not by value.

Resolution of the dependency failed

I have the following code:
CancellationPolicyService
using MyApp.Model.Models;
using Repository.Pattern.Repositories;
using Service.Pattern;
namespace MyApp.Service
{
public interface ICancellationPolicyService : IService<CancellationPolicy>
{
}
public class CancellationPolicyService : Service<CancellationPolicy>, ICancellationPolicyService
{
public CancellationPolicyService(IRepositoryAsync<CancellationPolicy> repository)
: base(repository)
{
}
}
}
Inside UnityConfig.cs:
.RegisterType<ICancellationPolicyService, CancellationPolicyService>()
In DataCacheService:
namespace MyApp.Service
{
public class DataCacheService
{
private ICancellationPolicyService CancellationPolicyService
{
get { return _container.Resolve<ICancellationPolicyService>(); }
}
public DataCacheService(IUnityContainer container)
{
_container = container;
MainCache = new MemoryCache("MainCache");
GetCachedItem(CacheKeys.CancellationPolicies);
}
public object GetCachedItem(CacheKeys CacheKeyName)
{
lock (_lock)
{
if (!MainCache.Contains(CacheKeyName.ToString()))
{
switch (CacheKeyName)
{
case CacheKeys.CancellationPolicies:
var cancellationpolicies = CancellationPolicyService.Queryable().ToList();
UpdateCache(CacheKeys.CancellationPolicies, cancellationpolicies);
break;
}
};
return MainCache[CacheKeyName.ToString()] as Object;
}
}
}
}
And when I call DataCacheService I get an error saying the following:
InvalidOperationException - The current type, Repository.Pattern.Repositories.IRepositoryAsync`1[MyApp.Model.Models.CancellationPolicy], is an interface and cannot be constructed. Are you missing a type mapping?
Do you have an idea, why that is? I would be thankful for any kind of hint.
It sounds like you haven't registered IRepositoryAsync<CancellationPolicy>. Add that registration to your unity registration as well.
Assuming that the implementation of IRepositoryAsync<CancellationPolicy> is CancellationPolicyRepository:
.RegisterType<IRepositoryAsync<CancellationPolicy>, CancellationPolicyRepository>()
Or someting like this if you have a generic repository.
.RegisterType<IRepositoryAsync<CancellationPolicy>, MyGenericRepository<CancellationPolicyRepository>>()
use this one:
RegisterType<yourInterface>().As<yourClass>().AsSelf();
it might work.

Dart: How to convert variable identifier names to strings only for variables of a certain type

Using Dart here.
As the above title suggests, I have a class (shown below) that has three bool instance variables. What I want to do is create a function that inspects the identifier names of these instance variables and prints each of them out in a string. The .declarations getter that comes with the ClassMirror class ALMOST does this, except it also gives me the name of the Constructor and any other methods I have in the class. This is no good. So really what I want is a way to filter by type (i.e., only give me the boolean identifiers as strings.) Any way to do this?
class BooleanHolder {
bool isMarried = false;
bool isBoard2 = false;
bool isBoard3 = false;
List<bool> boolCollection;
BooleanHolder() {
}
void boolsToStrings() {
ClassMirror cm = reflectClass(BooleanHolder);
Map<Symbol, DeclarationMirror> map = cm.declarations;
for (DeclarationMirror dm in map.values) {
print(MirrorSystem.getName(dm.simpleName));
}
}
}
OUTPUT IS:
isMarried
isBoard2
isBoard3
boolsToStrings
BooleanHolder
Sample code.
import "dart:mirrors";
void main() {
var type = reflectType(Foo);
var found = filter(type, [reflectType(bool), reflectType(int)]);
for(var element in found) {
var name = MirrorSystem.getName(element.simpleName);
print(name);
}
}
List<VariableMirror> filter(TypeMirror owner, List<TypeMirror> types) {
var result = new List<VariableMirror>();
if (owner is ClassMirror) {
for (var declaration in owner.declarations.values) {
if (declaration is VariableMirror) {
var declaredType = declaration.type;
for (var type in types) {
if (declaredType.isSubtypeOf(type)) {
result.add(declaration);
}
}
}
}
}
return result;
}
class Foo {
bool bool1 = true;
bool bool2;
int int1;
int int2;
String string1;
String string2;
}
Output:
bool1
bool2
int1
int2

Twitter4J, documentation about possible fields

I'm starting working with Twitter4J and I would like to figure out what each method does.
I'm implementing UserStreamListener which has a lot of methods what don't have JavaDoc,, as:
public void onException(Exception ex) {
public void onBlock(User arg0, User arg1)
public void onDeletionNotice(long arg0, long arg1)
public void onDirectMessage(DirectMessage arg0)
...
So, I don't know when they are exactly executed and what the params mean. I downloaded the code of Twitter4J and I have seen a class where you can see how the library is generating the events, but when I try to link that information with Twitter, I don't find more information.
I found this web https://dev.twitter.com/docs/platform-objects/tweets , but it isn't this information.
public final class JSONObjectType {
public enum Type {
SENDER,
STATUS,
DIRECT_MESSAGE,
DELETE,
LIMIT,
STALL_WARNING,
SCRUB_GEO,
FRIENDS,
FAVORITE,
UNFAVORITE,
FOLLOW,
UNFOLLOW,
USER_LIST_MEMBER_ADDED,
USER_LIST_MEMBER_DELETED,
USER_LIST_SUBSCRIBED,
USER_LIST_UNSUBSCRIBED,
USER_LIST_CREATED,
USER_LIST_UPDATED,
USER_LIST_DESTROYED,
USER_UPDATE,
BLOCK,
UNBLOCK,
DISCONNECTION,
UNKNOWN
}
private static final Logger logger = Logger.getLogger(JSONObjectType.class);
/**
* Determine the respective object type for a given JSONObject. This
* method inspects the object to figure out what type of object it
* represents. This is useful when processing JSON events of mixed type
* from a stream, in which case you may need to know what type of object
* to construct, or how to handle the event properly.
*
* #param json the JSONObject whose type should be determined
* #return the determined JSONObjectType, or null if not recognized
*/
public static Type determine(JSONObject json) {
// This code originally lived in AbstractStreamImplementation.
// I've moved it in here to expose it as a public encapsulation of
// the object type determination logic.
if (!json.isNull("sender")) {
return Type.SENDER;
} else if (!json.isNull("text")) {
return Type.STATUS;
} else if (!json.isNull("direct_message")) {
return Type.DIRECT_MESSAGE;
} else if (!json.isNull("delete")) {
return Type.DELETE;
} else if (!json.isNull("limit")) {
return Type.LIMIT;
} else if (!json.isNull("warning")) {
return Type.STALL_WARNING;
} else if (!json.isNull("scrub_geo")) {
return Type.SCRUB_GEO;
} else if (!json.isNull("friends")) {
return Type.FRIENDS;
} else if (!json.isNull("event")) {
String event;
try {
event = json.getString("event");
if ("favorite".equals(event)) {
return Type.FAVORITE;
} else if ("unfavorite".equals(event)) {
return Type.UNFAVORITE;
} else if ("follow".equals(event)) {
return Type.FOLLOW;
} else if ("unfollow".equals(event)) {
return Type.UNFOLLOW;
} else if (event.startsWith("list")) {
if ("list_member_added".equals(event)) {
return Type.USER_LIST_MEMBER_ADDED;
} else if ("list_member_removed".equals(event)) {
return Type.USER_LIST_MEMBER_DELETED;
} else if ("list_user_subscribed".equals(event)) {
return Type.USER_LIST_SUBSCRIBED;
} else if ("list_user_unsubscribed".equals(event)) {
return Type.USER_LIST_UNSUBSCRIBED;
} else if ("list_created".equals(event)) {
return Type.USER_LIST_CREATED;
} else if ("list_updated".equals(event)) {
return Type.USER_LIST_UPDATED;
} else if ("list_destroyed".equals(event)) {
return Type.USER_LIST_DESTROYED;
}
} else if ("user_update".equals(event)) {
return Type.USER_UPDATE;
} else if ("block".equals(event)) {
return Type.BLOCK;
} else if ("unblock".equals(event)) {
return Type.UNBLOCK;
}
} catch (JSONException jsone) {
try {
logger.warn("Failed to get event element: ", json.toString(2));
} catch (JSONException ignore) {
}
}
} else if (!json.isNull("disconnect")) {
return Type.DISCONNECTION;
}
return Type.UNKNOWN;
}
}
For example, if the JSON is coming "event" and "block", the method onBlock will be executed. But, where is the information about all the possible fields in a Tweet???
You may find the information you need in Twitter's Streaming message types documentation, specifically, take a look at the Events section which describes the message format:
{
"target": TARGET_USER,
"source": SOURCE_USER,
"event":"EVENT_NAME",
"target_object": TARGET_OBJECT,
"created_at": "Sat Sep 4 16:10:54 +0000 2010"
}
Additionally, this documentation for UserStreamListener will help with the argument names of the methods, for example the onBlock method:
onBlock(User source, User blockedUser)

TinyIoC Returning Same instance

I am new to the dependency injection pattern and I am having issues getting a new instance of a class from container.Resolve in tinyioc it just keeps returning the same instance rather than a new instance. Now for the code
public abstract class HObjectBase : Object
{
private string _name = String.Empty;
public string Name
{
get
{
return this._name;
}
set
{
if (this._name == string.Empty && value.Length > 0 && value != String.Empty)
this._name = value;
else if (value.Length < 1 && value == String.Empty)
throw new FieldAccessException("Objects names cannot be blank");
else
throw new FieldAccessException("Once the internal name of an object has been set it cannot be changed");
}
}
private Guid _id = new Guid();
public Guid Id
{
get
{
return this._id;
}
set
{
if (this._id == new Guid())
this._id = value;
else
throw new FieldAccessException("Once the internal id of an object has been set it cannot be changed");
}
}
private HObjectBase _parent = null;
public HObjectBase Parent
{
get
{
return this._parent;
}
set
{
if (this._parent == null)
this._parent = value;
else
throw new FieldAccessException("Once the parent of an object has been set it cannot be changed");
}
}
}
public abstract class HZoneBase : HObjectBase
{
public new HObjectBase Parent
{
get
{
return base.Parent;
}
set
{
if (value == null || value.GetType() == typeof(HZoneBase))
{
base.Parent = value;
}
else
{
throw new FieldAccessException("Zones may only have other zones as parents");
}
}
}
private IHMetaDataStore _store;
public HZoneBase(IHMetaDataStore store)
{
this._store = store;
}
public void Save()
{
this._store.SaveZone(this);
}
}
And the derived class is a dummy at the moment but here it is
public class HZone : HZoneBase
{
public HZone(IHMetaDataStore store)
: base(store)
{
}
}
Now since this is meant to be an external library I have a faced class for accessing
everything
public class Hadrian
{
private TinyIoCContainer _container;
public Hadrian(IHMetaDataStore store)
{
this._container = new TinyIoCContainer();
this._container.Register(store);
this._container.AutoRegister();
}
public HZoneBase NewZone()
{
return _container.Resolve<HZoneBase>();
}
public HZoneBase GetZone(Guid id)
{
var metadataStore = this._container.Resolve<IHMetaDataStore>();
return metadataStore.GetZone(id);
}
public List<HZoneBase> ListRootZones()
{
var metadataStore = this._container.Resolve<IHMetaDataStore>();
return metadataStore.ListRootZones();
}
}
However the test is failing because the GetNewZone() method on the Hadrian class keeps returning the same instance.
Test Code
[Fact]
public void ListZones()
{
Hadrian instance = new Hadrian(new MemoryMetaDataStore());
Guid[] guids = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
int cnt = 0;
foreach (Guid guid in guids)
{
HZone zone = (HZone)instance.NewZone();
zone.Id = guids[cnt];
zone.Name = "Testing" + cnt.ToString();
zone.Parent = null;
zone.Save();
cnt++;
}
cnt = 0;
foreach (HZone zone in instance.ListRootZones())
{
Assert.Equal(zone.Id, guids[cnt]);
Assert.Equal(zone.Name, "Testing" + cnt.ToString());
Assert.Equal(zone.Parent, null);
}
}
I know its probably something simple I'm missing with the pattern but I'm not sure, any help would be appreciated.
First, please always simplify the code to what is absolutely necessary to demonstrate the problem, but provide enough that it will actually run; I had to guess what MemoryMetaDataStore does and implement it myself to run the code.
Also, please say where and how stuff fails, to point others straight to the issue. I spent a few minues figuring out that the exception I was getting was your problem and you weren't even getting to the assertions.
That said, container.Resolve<HZoneBase>() will always return the same instance because that's how autoregistration in TinyIoC works - once an abstraction has been resolved, the same instance is always returned for subsequent calls.
To change this, add the following line to the Hadrian constructor:
this._container.Register<HZoneBase, HZone>().AsMultiInstance();
This will tell the container to create a new instance for each resolution request for HZoneBase.
Also, Bassetassen's answer about the Assert part is correct.
In general, if you want to learn DI, you should read Mark Seemann's excellent book "Dependency Injection in .NET" - not quite an easy read as the whole topic is inherently complex, but it's more than worth it and will let you get into it a few years faster than by learning it on your own.
In your assert stage you are not incrementing cnt. You are also using the actual value as the expected one in the assert. This will be confusing, becuase it says something is excpected when it actually is the actual value that is returned.
The assert part should be:
cnt = 0;
foreach (HZone zone in instance.ListRootZones())
{
Assert.Equal(guids[cnt], zone.Id);
Assert.Equal("Testing" + cnt.ToString(), zone.Name);
Assert.Equal(null, zone.Parent);
cnt++;
}

Resources