Search Results

Search found 325 results on 13 pages for 'immutable'.

Page 9/13 | < Previous Page | 5 6 7 8 9 10 11 12 13  | Next Page >

  • Why don't purely functional languages use reference counting?

    - by Zifre
    In purely functional languages, data is immutable. With reference counting, creating a reference cycle requires changing already created data. It seems like purely functional languages could use reference counting without worrying about the possibility of cycles. Am is right? If so, why don't they? I understand that reference counting is slower than GC in many cases, but at least it reduces pause times. It would be nice to have the option to use reference counting in cases where pause times are bad.

    Read the article

  • postgres - ERROR: syntax error at or near "COST"

    - by cino21122
    EDIT Taking COST 100 out made the command go through, however, I'm still unable to run my query because it yields this error: ERROR: function group_concat(character) does not exist HINT: No function matches the given name and argument types. You may need to add explicit type casts. The query I'm running is this: select tpid, group_concat(z) as z, group_concat(cast(r as char(2))) as r, group_concat(to_char(datecreated,'DD-Mon-YYYY HH12:MI am')) as datecreated, group_concat(to_char(datemodified,'DD-Mon-YYYY HH12:MI am')) as datemodified from tpids group by tpid order by tpid, zip This function seems to work fine locally, but moving it online yields this error... Is there something I'm missing? CREATE OR REPLACE FUNCTION group_concat(text, text) RETURNS text AS $BODY$ SELECT CASE WHEN $2 IS NULL THEN $1 WHEN $1 IS NULL THEN $2 ELSE $1 operator(pg_catalog.||) ',' operator(pg_catalog.||) $2 END $BODY$ LANGUAGE 'sql' IMMUTABLE COST 100; ALTER FUNCTION group_concat(text, text) OWNER TO j76dd3;

    Read the article

  • How to handle value types when embedding IronPython in C#?

    - by kloffy
    There is a well known issue when it comes to using .NET value types in IronPython. This has recently caused me a headache when trying to use Python as an embedded scripting language in C#. The problem can be summed up as follows: Given a C# struct such as: struct Vector { public float x; public float y; } And a C# class such as: class Object { public Vector position; } The following will happen in IronPython: obj = Object() print obj.position.x # prints ‘0’ obj.position.x = 1 print obj.position.x # still prints ‘0’ As the article states, this means that value types are mostly immutable. However, this is a problem as I was planning on using a vector library that is implemented as seen above. Are there any workarounds for working with existing libraries that rely on value types? Modifying the library would be the very last resort, but I'd rather avoid that.

    Read the article

  • return new string vs .ToString()

    - by Leroy Jenkins
    Take the following code: public static string ReverseIt(string myString) { char[] foo = myString.ToCharArray(); Array.Reverse(foo); return new string(foo); } I understand that strings are immutable, but what I dont understand is why a new string needs to be called return new string(foo); instead of return foo.ToString(); I have to assume it has something to do with reassembling the CharArray (but thats just a guess). Whats the difference between the two and how do you know when to return a new string as opposed to returning a System.String that represents the current object?

    Read the article

  • java serialization and final fields

    - by mdma
    I have an class defining an immutable value type that I now need to serialize. The immutability comes from the final fields which are set in the constructor. I've tried serializing, and it works (surprisingly?) - but I've no idea how. Here's an example of the class public class MyValueType implements Serializable { private final int value; private transient int derivedValue; public MyValueType(int value) { this.value = value; this.derivedValue = derivedValue(value); } // getters etc... } Given that the class doesn't have a no arg constructor, how can it be instantiated and the final field set? (An aside - I noticed this class particularly because IDEA wasn't generating a "no serialVersionUID" inspection warning for this class, yet successfully generated warnings for other classes that I've just made serializable.)

    Read the article

  • Problem creating PostGIS template database

    - by omat
    I am trying to build a template geographic database for PostGIS (1.5) on Mac OS X Snow Leopard (10.6) for my GeoDjango application. I am following: http://docs.djangoproject.com/en/dev/ref/contrib/gis/install/#creating-a-spatial-database-template-for-postgis I've managed to come up to the point where the provided postgis.sql should be run (i.e. psql -d template_postgis -f $POSTGIS_SQL_PATH/postgis.sql) At that point I am getting an error at the first SQL statement that is tried to be run. When I try that on the psql prompt the result is as follows: template_postgis=# CREATE OR REPLACE FUNCTION st_spheroid_in(cstring) RETURNS spheroid AS '/usr/local/pgsql/lib/postgis-1.5','ellipsoid_in' LANGUAGE 'C' IMMUTABLE STRICT; NOTICE: type "spheroid" is not yet defined DETAIL: Creating a shell type definition. ERROR: could not load library "/usr/local/pgsql/lib/postgis-1.5.so": dlopen(/usr/local/pgsql/lib/postgis-1.5.so, 10): Symbol not found: _DatumGetFloat4 Referenced from: /usr/local/pgsql/lib/postgis-1.5.so Expected in: /opt/local/lib/postgresql83/bin/postgres in /usr/local/pgsql/lib/postgis1.5.so Any ideas what might have been messed up?

    Read the article

  • How can I define pre/post-increment behavior in Perl objects?

    - by Zaid
    Date::Simple objects display this behavior. In the case of Date::Simple objects, $date++ returns the next day's date. Date::Simple objects are immutable. After assigning $date1 to $date2, no change to $date1 can affect $date2. This means, for example, that there is nothing like a set_year operation, and $date++ assigns a new object to $date. How can one custom define the pre/post-incremental behavior of an object, such that ++$object or $object-- performs a particular action? I've skimmed over perlboot, perltoot, perltooc and perlbot, but I don't see any examples showing how this can be done.

    Read the article

  • Can you decode a mutable Bitmap from an InputStream?

    - by Daniel Lew
    Right now I've got an Android application that: Downloads an image. Does some pre-processing to that image. Displays the image. The dilemma is that I would like this process to use less memory, so that I can afford to download a higher-resolution image. However, when I download the image now, I use BitmapFactory.decodeStream(), which has the unfortunate side effect of returning an immutable Bitmap. As a result, I'm having to create a copy of the Bitmap before I can start operating on it, which means I have to have 2x the size of the Bitmap's memory allocated (at least for a brief period of time; once the copy is complete I can recycle the original). Is there a way to decode an InputStream into a mutable Bitmap?

    Read the article

  • Using Python tuples as vectors

    - by Etaoin
    I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice. The trouble is when I need to implement things like addition and scalar multiplication. If a and b are vectors, and c is a number, the best I can think of is this: tuple(map(lambda x,y: x + y, a, b)) # add vectors 'a' and 'b' tuple(map(lambda x: x * c, a)) # multiply vector 'a' by scalar 'c' which seems inelegant; there should be a clearer, simpler way to get this done -- not to mention avoiding the call to tuple, since map returns a list. Is there a better option?

    Read the article

  • arguments into instance methods in ruby

    - by aharon
    So, I'd like to be able to make a call x = MyClass.new('good morning', 'good afternoon', 'good evening', 'good night', ['hello', 'goodbye']) that would add methods to the class whose values are the values of the arguments. So now: p x.methods #> [m_greeting, a_greeting, e_greeting, n_greeting, r_greeting, ...] And p x.m_greeting #> "good morning" p x.r_greeting #> ['hello', 'goodbye'] I realize that this is sort of what instance variables are to do (and that if I wanted them immutable I could make them frozen constants) but, for reasons beyond my control, I need to make methods instead. Thanks!

    Read the article

  • How to update an element with a List using LINQ and C#

    - by Addie
    I have a list of objects and I'd like to update a particular member variable within one of the objects. I understand LINQ is designed for query and not meant to update lists of immutable data. What would be the best way to accomplish this? I do not need to use LINQ for the solution if it is not most efficient. Would creating an Update extension method work? If so how would I go about doing that? EXAMPLE: (from trade in CrudeBalancedList where trade.Date.Month == monthIndex select trade).Update( trade => trade.Buy += optionQty);

    Read the article

  • Is it possible to create thread-safe collections without locks?

    - by Andrey
    This is pure just for interest question, any sort of questions are welcome. So is it possible to create thread-safe collections without any locks? By locks I mean any thread synchronization mechanisms, including Mutex, Semaphore, and even Interlocked, all of them. Is it possible at user level, without calling system functions? Ok, may be implementation is not effective, i am interested in theoretical possibility. If not what is the minimum means to do it? EDIT: Why immutable collections don't work. This of class Stack with methods Add that returns another Stack. Now here is program: Stack stack = new ...; ThreadedMethod() { loop { //Do the loop stack = stack.Add(element); } } this expression stack = stack.Add(element) is not atomic, and you can overwrite new stack from other thread. Thanks, Andrey

    Read the article

  • Does MATLAB perform tail call optimization?

    - by Shea Levy
    I've recently learned Haskell, and am trying to carry the pure functional style over to my other code when possible. An important aspect of this is treating all variables as immutable, i.e. constants. In order to do so, many computations that would be implemented using loops in an imperative style have to be performed using recursion, which typically incurs a memory penalty due to the allocation a new stack frame for each function call. In the special case of a tail call (where the return value of a called function is immediately returned to the callee's caller), however, this penalty can be bypassed by a process called tail call optimization (in one method, this can be done by essentially replacing a call with a jmp after setting up the stack properly). Does MATLAB perform TCO by default, or is there a way to tell it to?

    Read the article

  • Method hiding with interfaces

    - by fearofawhackplanet
    interface IFoo { int MyReadOnlyVar { get; } } class Foo : IFoo { int MyReadOnlyVar { get; set; } } public IFoo GetFoo() { return new Foo { MyReadOnlyVar = 1 }; } Is the above an acceptable way of implementing a readonly/immutable object? The immutability of IFoo can be broken with a temporary cast to Foo. In general (non-critical) cases, is hiding functionality through interfaces a common pattern? Or is it considered lazy coding? Or even an anti-pattern?

    Read the article

  • Instantiating a python class in C#

    - by Jekke
    I've written a class in python that I want to wrap into a .net assembly via IronPython and instantiate in a C# application. I've migrated the class to IronPython, created a library assembly and referenced it. Now, how do I actually get an instance of that class? The class looks (partially) like this: class PokerCard: "A card for playing poker, immutable and unique." def __init__(self, cardName): The test stub I wrote in C# is: using System; namespace pokerapp { class Program { static void Main(string[] args) { var card = new PokerCard(); // I also tried new PokerCard("Ah") Console.WriteLine(card.ToString()); Console.ReadLine(); } } } What do I have to do in order to instantiate this class in C#?

    Read the article

  • Alternatives to nested interfaces (not possible in C#)

    - by ericdes
    I'm using interfaces in this case mostly as a handle to an immutable instance of an object. The problem is that nested interfaces in C# are not allowed. Here is the code: public interface ICountry { ICountryInfo Info { get; } // Nested interface results in error message: // Error 13 'ICountryInfo': interfaces cannot declare types public interface ICountryInfo { int Population { get; } string Note { get; } } } public class Country : ICountry { CountryInfo Info { get; set; } public class CountryInfo : ICountry.ICountryInfo { int Population { get; set; } string Note { get; set; } ..... } ..... } I'm looking for an alternative, anybody would have a solution?

    Read the article

  • Java: is Exception class thread-safe?

    - by Vilius Normantas
    As I understand, Java's Exception class is certainly not immutable (methods like initCause and setStackTrace give some clues about that). So is it at least thread-safe? Suppose one of my classes has a field like this: private final Exception myException; Can I safely expose this field to multiple threads? I'm not willing to discuss concrete cases where and why this situation could occur. My question is more about the principle: can I tell that a class which exposes field of Exception type is thread-safe? Another example: class CustomException extends Exception { ... } Is this class thread-safe?

    Read the article

  • Hashing a python method to regenerate output when method is modified

    - by Seth Johnson
    I have a python method that has a deterministic result. It takes a long time to run and generates a large output: def time_consuming_method(): # lots_of_computing_time to come up with the_result return the_result I modify time_consuming_method from time to time, but I would like to avoid having it run again while it's unchanged. [Time_consuming_method only depends on functions that are immutable for the purposes considered here; i.e. it might have functions from Python libraries but not from other pieces of my code that I'd change.] The solution that suggests itself to me is to cache the output and also cache some "hash" of the function. If the hash changes, the function will have been modified, and we have to re-generate the output. Is this possible or a ridiculous idea? If this isn't a terrible idea, is the best implementation to write f = """ def ridiculous_method(): a = # # lots_of_computing_time return a """ , use the hashlib module to compute a hash for f, and use compile or eval to run it as code?

    Read the article

  • replace values in form.data when form fails validation

    - by John
    Hi I have a form field which requires a json object as its value when it is rendered. When the form is submitted it returns a comma seperated string of ids as its value (not a json string). however if the form does not validate i want to turn this string of ids back into a json string so it will display properly (is uses jquery to render the json object correctly). how would i do this? I was thinking of overwriting the form.clean method but when I tried to change self.data['fieldname'] I got the error 'This QueryDict instance is immutable' and when i tried to change self.cleaned_data['fieldname'] it didn't make a difference to the value of the field. Thanks

    Read the article

  • Implementing a multimap in Swift with Arrays and Dictionaries

    - by stuffy
    I'm trying to implement a basic multimap in Swift. Here's a relevant (non-functioning) snippet: class Multimap<K: Hashable, V> { var _dict = Dictionary<K, V[]>() func put(key: K, value: V) { if let existingValues = self._dict[key] { existingValues += value } else { self._dict[key] = [value] } } } However, I'm getting an error on the existingValues += value line: Could not find an overload for '+=' that accepts the supplied arguments This seems to imply that the value type T[] is defined as an immutable array, but I can't find any way to explicitly declare it as mutable. Is this possible in Swift?

    Read the article

  • Visual Studio 2010 + Resharper Tools|Options|Environment|Fonts and Colors

    - by Gerard
    About fonts and colors in the VS2010 C# text editor with Resharper installed. In the following method: public void Method() { var lis = new System.Collections.ArrayList(); var exc = new System.NotImplementedException(); } ArrayList gets another color as NotImplementedException in the VS2010 text editor, because I edited the color scheme. What would be the difference in these kinds of types so that the color scheme handles them differently? Note that I have Resharper installed but I also tried almost all Resharper entries. I would like to have the ame color for both, but the color of the NotImplementedException type seems immutable.

    Read the article

  • What's the best way of using a pair (triple, etc) of values as one value in C#?

    - by Yacoder
    That is, I'd like to have a tuple of values. The use case on my mind: Dictionary<Pair<string, int>, object> or Dictionary<Triple<string, int, int>, object> Are there built-in types like Pair or Triple? Or what's the best way of implementing it? Update There are some general-purpose tuples implementations described in the answers, but for tuples used as keys in dictionaries you should additionaly verify correct calculation of the hash code. Some more info on that in another question. Update 2 I guess it is also worth reminding, that when you use some value as a key in dictionary, it should be immutable.

    Read the article

  • Appending an element to a collection using LINQ

    - by SRKX
    I am trying to process some list with a functional approach in C#. The idea is that I have a collection of Tuple<T,double> and I want to change the Item 2 of some element T. The functional way to do so, as data is immutable, is to take the list, filter for all elements where the element is different from the one to change, and the append a new tuple with the new values. My problem is that I do not know how to append the element at the end. I would like to do: public List<Tuple<T,double>> Replace(List<Tuple<T,double>> collection, T term,double value) { return collection.Where(x=>!x.Item1.Equals(term)).Append(Tuple.Create(term,value)); } But there is no Append method. Is there something else?

    Read the article

  • error: polymorphic expression with default arguments

    - by 0__
    This following bugs me: trait Foo[ A ] class Bar[ A ]( set: Set[ Foo[ A ]] = Set.empty ) This yields <console>:8: error: polymorphic expression cannot be instantiated to expected type; found : [A]scala.collection.immutable.Set[A] required: Set[Foo[?]] class Bar[ A ]( set: Set[ Foo[ A ]] = Set.empty ) ^ It is quite annoying that I have to repeat the type parameter in Set.empty. Why does the type inference fail with this default argument? The following works: class Bar[ A ]( set: Set[ Foo[ A ]] = { Set.empty: Set[ Foo[ A ]]}) Please note that this has nothing to do with Set in particular: case class Hallo[ A ]() class Bar[ A ]( hallo: Hallo[ A ] = Hallo.apply ) // nope Strangely not only this works: class Bar[ A ]( hallo: Hallo[ A ] = Hallo.apply[ A ]) ...but also this: class Bar[ A ]( hallo: Hallo[ A ] = Hallo() ) // ???

    Read the article

  • Java - JPA - @Version annotation

    - by Yatendra Goel
    I am new to JPA. I am cofused about the @Version annotation. How it works? I have googled it and found various answers whose extract is as follows: JPA uses a version field in your entities to detect concurrent modifications to the same datastore record. When the JPA runtime detects an attempt to concurrently modify the same record, it throws an exception to the transaction attempting to commit last. But still I am not sure how it works? ================================================================================== Also as from the following lines: You should consider version fields immutable. Changing the field value has undefined results. Does it mean that we should declare our version field as final

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13  | Next Page >