Search Results

Search found 42001 results on 1681 pages for 'type theory'.

Page 11/1681 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Fallback to another existing MIME type when the required is missing in Rails

    - by fifigyuri
    I want to extend the existing supported HTML type of my site by support for iPhone. For this I registered a new MIME type. I created a layout for iphone and also converted some of the html views to iphone version. However, I did not convert all of the html.erb files. I do not see the reason to convert all views, some of them should not change, some partials simply just remain the same. I guess there should be a solution for this case. I tried to search for ways how to fallback to an existing format, but did not find any answer. Does a way to define fallback for MIME types in Rails exist? How does it work? If it doesn't exist and thus I wanted to solve the issue not the right way, what could simply solve the task of extending an existing site by another format? Thanks for your suggestions.

    Read the article

  • Fallback to another exiting MIME type when the required is missing in Rails

    - by fifigyuri
    I want to extend the exiting supported HTML type of my site by support for iPhone. For this I registered a new MIME type. I created a layout for iphone and also converted some of the html views to iphone version. However, I did not convert all of the html.erb-s. I do not see the reason to convert all views, some of them should not change, some partials simply just remain the same. I guess there should be a solution for this case. I tried to search for ways how to fallback to an existing format, but did not find any answer. Does a way to define fallback for MIME types in Rails exist? How does it work? If it doesn't exist and thus I wanted to solve the issue not the right way, what could simply solve the task of extending an existing site by another format? Thanks for your suggestions.

    Read the article

  • The *right* JSON content type?

    - by Oli
    Right I've been messing around with JSON for some time, just pushing it out as text and it hasn't hurt anybody (I know of), but I'd like to start doing things properly. I have seen so many purported "standards" for the JSON content type: application/json application/x-javascript text/javascript text/x-javascript text/x-json But which is right? Or best? I gather that there are security and browser support issues varying between them... (I know there's a similar question, What MIME type if JSON is being returned by a REST API?, but I'd like a slightly more targeted answer.)

    Read the article

  • Wordpress Custom Type permalink containing Taxonomy slug

    - by treznik
    I'm trying to create a permalink pattern for a Custom Type, that includes one of its taxonomies. The taxonomy name is known from the start (so I'm not trying to add or mix all of its taxonomies, just a specific one), but the value will by dynamic, of course. Normally, the Custom Type permalink is built using the rewrite arg with the slug param, but I don't see how I could add a dynamic variable in there. http://codex.wordpress.org/Function_Reference/register_post_type I'm guessing a custom solution is required, but I'm not sure what the best unintrusive approach would be. Is there a known practice for this or has anyone built something similar recently? I'm using WP 3.2.1 btw.

    Read the article

  • Odd behavior when recursively building a return type for variadic functions

    - by Dennis Zickefoose
    This is probably going to be a really simple explanation, but I'm going to give as much backstory as possible in case I'm wrong. Advanced apologies for being so verbose. I'm using gcc4.5, and I realize the c++0x support is still somewhat experimental, but I'm going to act on the assumption that there's a non-bug related reason for the behavior I'm seeing. I'm experimenting with variadic function templates. The end goal was to build a cons-list out of std::pair. It wasn't meant to be a custom type, just a string of pair objects. The function that constructs the list would have to be in some way recursive, with the ultimate return value being dependent on the result of the recursive calls. As an added twist, successive parameters are added together before being inserted into the list. So if I pass [1, 2, 3, 4, 5, 6] the end result should be {1+2, {3+4, 5+6}}. My initial attempt was fairly naive. A function, Build, with two overloads. One took two identical parameters and simply returned their sum. The other took two parameters and a parameter pack. The return value was a pair consisting of the sum of the two set parameters, and the recursive call. In retrospect, this was obviously a flawed strategy, because the function isn't declared when I try to figure out its return type, so it has no choice but to resolve to the non-recursive version. That I understand. Where I got confused was the second iteration. I decided to make those functions static members of a template class. The function calls themselves are not parameterized, but instead the entire class is. My assumption was that when the recursive function attempts to generate its return type, it would instantiate a whole new version of the structure with its own static function, and everything would work itself out. The result was: "error: no matching function for call to BuildStruct<double, double, char, char>::Go(const char&, const char&)" The offending code: static auto Go(const Type& t0, const Type& t1, const Types&... rest) -> std::pair<Type, decltype(BuildStruct<Types...>::Go(rest...))> My confusion comes from the fact that the parameters to BuildStruct should always be the same types as the arguments sent to BuildStruct::Go, but in the error code Go is missing the initial two double parameters. What am I missing here? If my initial assumption about how the static functions would be chosen was incorrect, why is it trying to call the wrong function rather than just not finding a function at all? It seems to just be mixing types willy-nilly, and I just can't come up with an explanation as to why. If I add additional parameters to the initial call, it always burrows down to that last step before failing, so presumably the recursion itself is at least partially working. This is in direct contrast to the initial attempt, which always failed to find a function call right away. Ultimately, I've gotten past the problem, with a fairly elegant solution that hardly resembles either of the first two attempts. So I know how to do what I want to do. I'm looking for an explanation for the failure I saw. Full code to follow since I'm sure my verbal description was insufficient. First some boilerplate, if you feel compelled to execute the code and see it for yourself. Then the initial attempt, which failed reasonably, then the second attempt, which did not. #include <iostream> using std::cout; using std::endl; #include <utility> template<typename T1, typename T2> std::ostream& operator <<(std::ostream& str, const std::pair<T1, T2>& p) { return str << "[" << p.first << ", " << p.second << "]"; } //Insert code here int main() { Execute(5, 6, 4.3, 2.2, 'c', 'd'); Execute(5, 6, 4.3, 2.2); Execute(5, 6); return 0; } Non-struct solution: template<typename Type> Type BuildFunction(const Type& t0, const Type& t1) { return t0 + t1; } template<typename Type, typename... Rest> auto BuildFunction(const Type& t0, const Type& t1, const Rest&... rest) -> std::pair<Type, decltype(BuildFunction(rest...))> { return std::pair<Type, decltype(BuildFunction(rest...))> (t0 + t1, BuildFunction(rest...)); } template<typename... Types> void Execute(const Types&... t) { cout << BuildFunction(t...) << endl; } Resulting errors: test.cpp: In function 'void Execute(const Types& ...) [with Types = {int, int, double, double, char, char}]': test.cpp:33:35: instantiated from here test.cpp:28:3: error: no matching function for call to 'BuildFunction(const int&, const int&, const double&, const double&, const char&, const char&)' Struct solution: template<typename... Types> struct BuildStruct; template<typename Type> struct BuildStruct<Type, Type> { static Type Go(const Type& t0, const Type& t1) { return t0 + t1; } }; template<typename Type, typename... Types> struct BuildStruct<Type, Type, Types...> { static auto Go(const Type& t0, const Type& t1, const Types&... rest) -> std::pair<Type, decltype(BuildStruct<Types...>::Go(rest...))> { return std::pair<Type, decltype(BuildStruct<Types...>::Go(rest...))> (t0 + t1, BuildStruct<Types...>::Go(rest...)); } }; template<typename... Types> void Execute(const Types&... t) { cout << BuildStruct<Types...>::Go(t...) << endl; } Resulting errors: test.cpp: In instantiation of 'BuildStruct<int, int, double, double, char, char>': test.cpp:33:3: instantiated from 'void Execute(const Types& ...) [with Types = {int, int, double, double, char, char}]' test.cpp:38:41: instantiated from here test.cpp:24:15: error: no matching function for call to 'BuildStruct<double, double, char, char>::Go(const char&, const char&)' test.cpp:24:15: note: candidate is: static std::pair<Type, decltype (BuildStruct<Types ...>::Go(BuildStruct<Type, Type, Types ...>::Go::rest ...))> BuildStruct<Type, Type, Types ...>::Go(const Type&, const Type&, const Types& ...) [with Type = double, Types = {char, char}, decltype (BuildStruct<Types ...>::Go(BuildStruct<Type, Type, Types ...>::Go::rest ...)) = char] test.cpp: In function 'void Execute(const Types& ...) [with Types = {int, int, double, double, char, char}]': test.cpp:38:41: instantiated from here test.cpp:33:3: error: 'Go' is not a member of 'BuildStruct<int, int, double, double, char, char>'

    Read the article

  • QotD: Alex Buckley announcing Java™ SE 8 Early Access Builds with Type Annotation Support

    - by $utils.escapeXML($entry.author)
    I am pleased to announce that binary builds of the JSR 308 Reference Implementation are available at http://jdk8.java.net/type-annotations/.Please see the Type Annotations project page for a link to the JSR 308 Specification. There is also a changelog, which is important to review as there have been significant spec changes in 2012.The builds were generated from the type-annotations/type-annotations forest on 9/9. This forest is regularly updated from jdk8/jdk8 and jdk8/tl.Alex Buckley in a post on the type-annotations-dev mailing list.If you want to play with repeating annotations, check out http://jdk8.java.net/type-annotations/ ... thanks to superior code wrangling by Joel Franck (repeating annotations) and Werner Dietl (type annotations), support for repeating annotations on declarations is included in the build.Alex Buckley in a post on the enhanced-metadata-spec-discuss mailing list.

    Read the article

  • Subterranean IL: The ThreadLocal type

    - by Simon Cooper
    I came across ThreadLocal<T> while I was researching ConcurrentBag. To look at it, it doesn't really make much sense. What's all those extra Cn classes doing in there? Why is there a GenericHolder<T,U,V,W> class? What's going on? However, digging deeper, it's a rather ingenious solution to a tricky problem. Thread statics Declaring that a variable is thread static, that is, values assigned and read from the field is specific to the thread doing the reading, is quite easy in .NET: [ThreadStatic] private static string s_ThreadStaticField; ThreadStaticAttribute is not a pseudo-custom attribute; it is compiled as a normal attribute, but the CLR has in-built magic, activated by that attribute, to redirect accesses to the field based on the executing thread's identity. TheadStaticAttribute provides a simple solution when you want to use a single field as thread-static. What if you want to create an arbitary number of thread static variables at runtime? Thread-static fields can only be declared, and are fixed, at compile time. Prior to .NET 4, you only had one solution - thread local data slots. This is a lesser-known function of Thread that has existed since .NET 1.1: LocalDataStoreSlot threadSlot = Thread.AllocateNamedDataSlot("slot1"); string value = "foo"; Thread.SetData(threadSlot, value); string gettedValue = (string)Thread.GetData(threadSlot); Each instance of LocalStoreDataSlot mediates access to a single slot, and each slot acts like a separate thread-static field. As you can see, using thread data slots is quite cumbersome. You need to keep track of LocalDataStoreSlot objects, it's not obvious how instances of LocalDataStoreSlot correspond to individual thread-static variables, and it's not type safe. It's also relatively slow and complicated; the internal implementation consists of a whole series of classes hanging off a single thread-static field in Thread itself, using various arrays, lists, and locks for synchronization. ThreadLocal<T> is far simpler and easier to use. ThreadLocal ThreadLocal provides an abstraction around thread-static fields that allows it to be used just like any other class; it can be used as a replacement for a thread-static field, it can be used in a List<ThreadLocal<T>>, you can create as many as you need at runtime. So what does it do? It can't just have an instance-specific thread-static field, because thread-static fields have to be declared as static, and so shared between all instances of the declaring type. There's something else going on here. The values stored in instances of ThreadLocal<T> are stored in instantiations of the GenericHolder<T,U,V,W> class, which contains a single ThreadStatic field (s_value) to store the actual value. This class is then instantiated with various combinations of the Cn types for generic arguments. In .NET, each separate instantiation of a generic type has its own static state. For example, GenericHolder<int,C0,C1,C2> has a completely separate s_value field to GenericHolder<int,C1,C14,C1>. This feature is (ab)used by ThreadLocal to emulate instance thread-static fields. Every time an instance of ThreadLocal is constructed, it is assigned a unique number from the static s_currentTypeId field using Interlocked.Increment, in the FindNextTypeIndex method. The hexadecimal representation of that number then defines the specific Cn types that instantiates the GenericHolder class. That instantiation is therefore 'owned' by that instance of ThreadLocal. This gives each instance of ThreadLocal its own ThreadStatic field through a specific unique instantiation of the GenericHolder class. Although GenericHolder has four type variables, the first one is always instantiated to the type stored in the ThreadLocal<T>. This gives three free type variables, each of which can be instantiated to one of 16 types (C0 to C15). This puts an upper limit of 4096 (163) on the number of ThreadLocal<T> instances that can be created for each value of T. That is, there can be a maximum of 4096 instances of ThreadLocal<string>, and separately a maximum of 4096 instances of ThreadLocal<object>, etc. However, there is an upper limit of 16384 enforced on the total number of ThreadLocal instances in the AppDomain. This is to stop too much memory being used by thousands of instantiations of GenericHolder<T,U,V,W>, as once a type is loaded into an AppDomain it cannot be unloaded, and will continue to sit there taking up memory until the AppDomain is unloaded. The total number of ThreadLocal instances created is tracked by the ThreadLocalGlobalCounter class. So what happens when either limit is reached? Firstly, to try and stop this limit being reached, it recycles GenericHolder type indexes of ThreadLocal instances that get disposed using the s_availableIndices concurrent stack. This allows GenericHolder instantiations of disposed ThreadLocal instances to be re-used. But if there aren't any available instantiations, then ThreadLocal falls back on a standard thread local slot using TLSHolder. This makes it very important to dispose of your ThreadLocal instances if you'll be using lots of them, so the type instantiations can be recycled. The previous way of creating arbitary thread-static variables, thread data slots, was slow, clunky, and hard to use. In comparison, ThreadLocal can be used just like any other type, and each instance appears from the outside to be a non-static thread-static variable. It does this by using the CLR type system to assign each instance of ThreadLocal its own instantiated type containing a thread-static field, and so delegating a lot of the bookkeeping that thread data slots had to do to the CLR type system itself! That's a very clever use of the CLR type system.

    Read the article

  • Ivar definitions show 'long' type encoding as 'long long' type encoding

    - by Frank C.
    I've found what I think may be a bug with Ivar and Objective-C runtime. I'm using XCode 3.2.1 and associated libraries, developing a 64 bit app on X86_64 (MacBook Pro). Where I would expect the type encoding for the following "longVal" to be 'l', the Ivar encoding is showing a 'q' (which is a 'long long'). Anyone else seeing this? Simplified code and output follows: Code: #import <Foundation/Foundation.h> #import <objc/runtime.h> @interface Bug : NSObject { long longVal; long long longerVal; } @property (nonatomic,assign) long longVal; @property (nonatomic,assign) long long longerVal; @end @implementation Bug @synthesize longVal,longerVal; @end int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; unsigned int ivarCount=0; Ivar *ivars= class_copyIvarList([Bug class], &ivarCount); for(unsigned int x=0;x<ivarCount;x++) { NSLog(@"Name [%@] encoding [%@]", [NSString stringWithCString:ivar_getName(ivars[x]) encoding:NSUTF8StringEncoding], [NSString stringWithCString:ivar_getTypeEncoding(ivars[x]) encoding:NSUTF8StringEncoding]); } [pool drain]; return 0; } And here is output from debug console: This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys000 Loading program into debugger… sharedlibrary apply-load-rules all Program loaded. run [Switching to process 6048] Running… 2010-03-17 22:16:29.138 ivarbug[6048:a0f] Name [longVal] encoding [q] 2010-03-17 22:16:29.146 ivarbug[6048:a0f] Name [longerVal] encoding [q] (gdb) continue Not a pretty picture! -- Frank

    Read the article

  • How would you solve this graph theory handshake problem in python?

    - by Zachary Burt
    I graduated college last year with a degree in Psychology, but I also took a lot of math for fun. I recently got the book "Introductory Graph Theory" by Gary Chartrand to brush up on my math and have some fun. Here is an exercise from the book that I'm finding particularly befuddling: Suppose you and your husband attended a party with three other married couples. Several handshakes took place. No one shook hands with himself (or herself) or with his (or her) spouse, and no one shook hands with the same person more than once. After all the handshaking was completed, suppose you asked each person, including your husband, how many hands he or she had shaken. Each person gave a different answer. a) How many hands did you shake? b) How many hands did your husband shake? Now, I've been reasoning about this for a while, and trying to draw sample graphs that could illustrate a solution, but I'm coming up empty-handed. My logic is this: there are 8 different vertices in the graph, and 7 of them have different degrees. The values for the degrees must therefore be 0, 1, 2, 3, 4, 5, 6, and x. The # of degrees for one married couple is (0, 6). Since all graphs have an even number of odd vertices, x must be either 5, 3, or 1. What's your solution to this problem? And, if you could solve it in python, how would you do it? (python is fun.) Cheers.

    Read the article

  • How would you solve this graph theory handshake problem in python?

    - by Zachary Burt
    I graduated college last year with a degree in Psychology, but I also took a lot of math for fun. I recently got the book "Introductory Graph Theory" by Gary Chartrand to brush up on my math and have some fun. Here is an exercise from the book that I'm finding particularly befuddling: Suppose you and your husband attended a party with three other married couples. Several handshakes took place. No one shook hands with himself (or herself) or with his (or her) spouse, and no one shook hands with the same person more than once. After all the handshaking was completed, suppose you asked each person, including your husband, how many hands he or she had shaken. Each person gave a different answer. a) How many hands did you shake? b) How many hands did your husband shake? Now, I've been reasoning about this for a while, and trying to draw sample graphs that could illustrate a solution, but I'm coming up empty-handed. My logic is this: there are 8 different vertices in the graph, and 7 of them have different degrees. The values for the degrees must therefore be 0, 1, 2, 3, 4, 5, 6, and x. The # of degrees for one married couple is (0, 6). Since all graphs have an even number of odd vertices, x must be either 5, 3, or 1. What's your solution to this problem? And, if you could solve it in python, how would you do it? (python is fun.) Cheers.

    Read the article

  • c++ passing unknown type to a function and any Class type definition

    - by user259789
    I am trying to create a generic class to write and read Objects to/from file. Called it ActiveRecord class only has one method, which saves the class itself: void ActiveRecord::saveRecord(){ string fileName = "data.dat"; ofstream stream(fileName.c_str(), ios::out); if (!stream) { cerr << "Error opening file: " << fileName << endl; exit(1); } stream.write(reinterpret_cast<const char *> (this), sizeof(ActiveRecord)); stream.close(); } now I'm extending this class with User class: class User : public ActiveRecord { public: User(void); ~User(void); string name; string lastName; }; to create and save the user I would like to do something like: User user = User(); user.name = "John"; user.lastName = "Smith" user.save(); how can I get this ActiveRecord::saveRecord() method to take any object, and class definition so it writes whatever i send it: to look like: void ActiveRecord::saveRecord(foo_instance, FooClass){ string fileName = "data.dat"; ofstream stream(fileName.c_str(), ios::out); if (!stream) { cerr << "Error opening file: " << fileName << endl; exit(1); } stream.write(reinterpret_cast<const char *> (foo_instance), sizeof(FooClass)); stream.close(); } and while we're at it, what is the default Object type in c++. eg. in objective-c it's id in java it's Object in AS3 it's Object what is it in C++??

    Read the article

  • Enforce strong type checking in C (type strictness for typedefs)

    - by quinmars
    Is there a way to enforce explicit cast for typedefs of the same type? I've to deal with utf8 and sometimes I get confused with the indices for the character count and the byte count. So it be nice to have some typedefs: typedef unsigned int char_idx_t; typedef unsigned int byte_idx_t; With the addition that you need an explicit cast between them: char_idx_t a = 0; byte_idx_t b; b = a; // compile warning b = (byte_idx_t) a; // ok I know that such a feature doesn't exist in C, but maybe you know a trick or a compiler extension (preferable gcc) that does that. EDIT: I still don't really like the Hungarian notation in general, I couldn't used it for this problem because of project coding conventions, but I used it now in another similar case, where also the types are the same and the meanings are very similar. And I have to admit: it helps. I never would go and declare every integer with a starting "i", but as in Joel's example for overlapping types, it can be life saving.

    Read the article

  • ASP.NET FormView: "Object of type 'System.Int32' cannot be converted to type 'System.String"

    - by Vinzcent
    Hey I have a problem with my FromView. I would like to show some data from a Database Table in my FormView. But some data is from the tupe Int32, while this data should be in a TextBox, a string. How do you convert these Int32's. FormView and my ObjectDataSource <asp:FormView ID="fvDetailOrder" runat="server"> <ItemTemplate> Aantal:<br /> <asp:Label CssClass="txtBox" ID="Label15" runat="server" Text='<%# Eval("COUNT") %>' /><br /> Prijs:<br /> <asp:Label CssClass="txtBox" ID="Label16" runat="server" Text='<%# Eval("PRICE") %>' /><br /> Korting:<br /> <asp:Label CssClass="txtBox" ID="Label17" runat="server" Text='' /><br /> Totaal:<br /> <asp:Label CssClass="txtBox" ID="Label18" runat="server" Text='<%# Eval("AMOUNT") %>' /><br /> Betaald:<br /> <asp:Label CssClass="txtBox" ID="Label19" runat="server" Text='<%# Eval("PAID") %>' /><br /> Datum betaling:<br /> <asp:Label CssClass="txtBox" ID="Label20" runat="server" Text='<%# Eval("PDATE") %>' /><br /> </ItemTemplate> </asp:FormView> <asp:ObjectDataSource ID="objdsOrderID" runat="server" OnSelecting="objdsOrderID_Selecting" SelectMethod="getOrdersByID" TypeName="DAL.OrdersDAL"> <SelectParameters> <asp:Parameter Name="id" Type="Int32" /> </SelectParameters> </asp:ObjectDataSource> My Code behind protected void gvOrdersAdmin_SelectedIndexChanged(object sender, EventArgs e) { fvDetailOrder.DataSource = objdsOrderID; fvDetailOrder.DataBind(); // <-- HERE I GET THE ERROR } protected void objdsOrderID_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) { e.InputParameters["id"] = gvOrdersAdmin.DataKeys[gvOrdersAdmin.SelectedRow.RowIndex].Values[0]; ; } My Data Acces Layer public static DataTable getOrdersByID(string id) { string sql = "SELECT 'AUTHOR' = tblAuthors.FIRSTNAME + ' ' + tblAuthors.LASTNAME, tblBooks.*, tblGenres.*, tblLanguages.*, tblOrders.* FROM tblAuthors INNER JOIN tblBooks ON tblAuthors.AUTHOR_ID = tblBooks.AUTHOR_ID INNER JOIN tblGenres ON tblBooks.GENRE_ID = tblGenres.GENRE_ID INNER JOIN tblLanguages ON tblBooks.LANG_ID = tblLanguages.LANG_ID INNER JOIN tblOrders ON tblBooks.BOOK_ID = tblOrders.BOOK_ID" + " WHERE tblOrders.ID = @id;"; SqlDataAdapter da = new SqlDataAdapter(sql, GetConnectionString()); da.SelectCommand.Parameters["id"].Value = id; DataSet ds = new DataSet(); da.Fill(ds, "Orders"); return ds.Tables["Orders"]; } Thanks a lot, Vincent

    Read the article

  • Reference-type conversion operators: asking for trouble?

    - by Ben
    When I compile the following code using g++ class A {}; void foo(A&) {} int main() { foo(A()); return 0; } I get the following error messages: > g++ test.cpp -o test test.cpp: In function ‘int main()’: test.cpp:10: error: invalid initialization of non-const reference of type ‘A&’ from a temporary of type ‘A’ test.cpp:6: error: in passing argument 1 of ‘void foo(A&)’ After some reflection, these errors make plenty of sense to me. A() is just a temporary value, not an assignable location on the stack, so it wouldn't seem to have an address. If it doesn't have an address, then I can't hold a reference to it. Okay, fine. But wait! If I add the following conversion operator to the class A class A { public: operator A&() { return *this; } }; then all is well! My question is whether this even remotely safe. What exactly does this point to when A() is constructed as a temporary value? I am given some confidence by the fact that void foo(const A&) {} can accept temporary values according to g++ and all other compilers I've used. The const keyword can always be cast away, so it would surprise me if there were any actual semantic differences between a const A& parameter and an A& parameter. So I guess that's another way of asking my question: why is a const reference to a temporary value considered safe by the compiler whereas a non-const reference is not?

    Read the article

  • Returning the same type the function was passed

    - by Ken Bloom
    I have the following code implementation of Breadth-First search. trait State{ def successors:Seq[State] def isSuccess:Boolean = false def admissableHeuristic:Double } def breadthFirstSearch(initial:State):Option[List[State]] = { val open= new scala.collection.mutable.Queue[List[State]] val closed = new scala.collection.mutable.HashSet[State] open.enqueue(initial::Nil) while (!open.isEmpty){ val path:List[State]=open.dequeue() if(path.head.isSuccess) return Some(path.reverse) closed += path.head for (x <- path.head.successors) if (!closed.contains(x)) open.enqueue(x::path) } return None } If I define a subtype of State for my particular problem class CannibalsState extends State { //... } What's the best way to make breadthFirstSearch return the same subtype as it was passed? Supposing I change this so that there are 3 different state classes for my particular problem and they share a common supertype: abstract class CannibalsState extends State { //... } class LeftSideOfRiver extends CannibalsState { //... } class InTransit extends CannibalsState { //... } class RightSideOfRiver extends CannibalsState { //... } How can I make the types work out so that breadthFirstSearch infers that the correct return type is CannibalsState when it's passed an instance of LeftSideOfRiver? Can this be done with an abstract type member, or must it be done with generics?

    Read the article

  • Rails3 renders a js.erb template with a text/html content-type instead of text/javascript

    - by Yannis
    Hi, I'm building a new app with 3.0.0.beta3. I simply try to render a js.erb template to an Ajax request for the following action (in publications_controller.rb): def get_pubmed_data entry = Bio::PubMed.query(params[:pmid])# searches PubMed and get entry @publication = Bio::MEDLINE.new(entry) # creates Bio::MEDLINE object from entry text flash[:warning] = "No publication found."if @publication.title.blank? and @publication.authors.blank? and @publication.journal.blank? respond_to do |format| format.js end end Currently, my get_pubmed_data.js.erb template is simply alert('<%= @publication.title %>') The server is responding with the following alert('Evidence for a herpes simplex virus-specific factor controlling the transcription of deoxypyrimidine kinase.') which is perfectly fine except that nothing happen in the browser, probably because the content-type of the response is 'text/html' instead of 'text/javascript' as shown by the response header partially reproduced here: Status 200 Keep-Alive timeout=5, max=100 Connection Keep-Alive Transfer-Encoding chunked Content-Type text/html; charset=utf-8 Is this a bug or am I missing something? Thanks for your help!

    Read the article

  • Assign Multiple Custom User Roles to a Custom Post Type

    - by OUHSD Webmaster
    Okay here's the situation.... I'm working on a my business website. There will be a work/portfolio area. "Work" is a custom post type. "Designer" is a custom user role. "Client" is a custom user role. In creating a new "Work" post I would like to be able to select both a "designer" and "Client" to assign to the piece of work, as I would assign an author to a regular ol' post. I tried the method from this answer but it did not work for me. ) I placed it in my functions.php file. ` add_filter('wp_dropdown_users', 'test'); function test($output) { global $post; //Doing it only for the custom post type if($post->post_type == 'work') { $users = get_users(array('role'=>'designer')); //We're forming a new select with our values, you can add an option //with value 1, and text as 'admin' if you want the admin to be listed as well, //optionally you can use a simple string replace trick to insert your options, //if you don't want to override the defaults $output .= "<select id='post_author_override' name='post_author_override' class=''>"; foreach($users as $user) { $output .= "<option value='".$user->id."'>".$user->user_login."</option>"; } $output .= "</select>"; } return $output; } ` Any help would be extremely appreciated!

    Read the article

  • Type-safe mapping from Class<T> to Thing<T>

    - by Joonas Pulakka
    I want to make a map-kind of container that has the following interface: public <T> Thing<T> get(Class<T> clazz); public <T> void put(Class<T> clazz, Thing<T> thing); The interesting point is that the Ts in each Class<T><- Thing<T> pair is the same T, but the container should be able to hold many different types of pairs. Initially I tried a (Hash)Map. But, for instance, Map<Class<T>, Thing<T>> is not right, because then T would be same T for all pairs in that map. Of course, Map<Class<?>, Thing<?>> works, but then I don't have type-safety guarantees so that when I get(String.class), I can't be sure that I get a Thing<String> instance back. Is there a way to accomplish the kind of type safety that I'm looking for?

    Read the article

  • Java Generics Class Parameter Type Inference

    - by Pindatjuh
    Given the interface: public interface BasedOnOther<T, U extends BasedList<T>> { public T getOther(); public void staticStatisfied(final U list); } The BasedOnOther<T, U extends BasedList<T>> looks very ugly in my use-cases. It is because the T type parameter is already defined in the BasedList<T> part, so the "uglyness" comes from that T needs to be typed twice. Problem: is it possible to let the Java compiler infer the generic T type from BasedList<T> in a generic class/interface definition? Ultimately, I'd like to use the interface like: class X implements BasedOnOther<BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } } // Does not compile, due to invalid parameter count. Instead: class X implements BasedOnOther<SomeType, BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } }

    Read the article

  • Java Generics Class Type Parameter Inference

    - by Pindatjuh
    Given the interface: public interface BasedOnOther<T, U extends BasedList<T>> { public T getOther(); public void staticStatisfied(final U list); } The BasedOnOther<T, U extends BasedList<T>> looks very ugly in my use-cases. It is because the T type parameter is already defined in the BasedList<T> part, so the "uglyness" comes from that T needs to be typed twice. Problem: is it possible to let the Java compiler infer the generic T type from BasedList<T> in a generic class/interface definition? Ultimately, I'd like to use the interface like: class X extends BasedOnOther<BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } } Instead: class X extends BasedOnOther<SomeType, BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } }

    Read the article

  • Converting string to a simple type

    - by zespri
    .Net framework contains a great class named Convert that allows conversion between simple types, DateTime type and String type. Also the class support conversion of the types implementing IConvertible interface. The class has been implemented in the very first version of .Net framework. There were a few things in the first .Net framework that were not done quite right. For example .Parse methods on simple types would throw an exception if the string couldn't be parsed and there would be no way to check if exception is going to be thrown in advance. A future version of .Net Framework removed this deficiency by introducing the TryParse method that resolved this problem. The Convert class dates back to time of the old Parse method, so the ChangeType method on this class in implemented old style - if conversion can't be performed an exception is thrown. Take a look at the following code: public static T ConvertString<T>(string s, T @default) { try { return (T)Convert.ChangeType(s, typeof(T), CultureInfo.InvariantCulture); } catch (Exception) { return @default; } } This code basically does what I want. However I would pretty much like to avoid the ugly try/catch here. I'm sure, that similar to TryParse, there is a modern method of rewriting this code without the catch-all. Could you suggest one?

    Read the article

  • C# Type conversion between two similar Datatable objects

    - by Ali
    I have .NET project with sync framework and two separate Datasets for MS SQL and Compact SQL. in my base class I have a generic DataTable object. in my derived classed I assign Typed DataTable to the generic object based on whether the application is operating online or offline: example: if (online) _dataTable = new MSSQLDataSet.Customer; else _dataTable = new CompactSQLDataSet.Customer; Now every where in my code i have to check and do a cast based on the current network mode like this: public void changeCustomerID(int ID) { if (online) (MSSQLDataSet.CustomerDataTable)_dataTable)[i].CustomerID = value; else (CompactMSSQLDataSet.CustomerDataTable)_dataTable)[i].CustomerID = value; } but I don't think this is very efficient and I believe it can be done in a smarter way to only use one line of code by dynamically getting the Type of _dataTable on the run time. my problem is at the design time, in order to acess datatable porperties such as "CustomerID" it has to be casted to either MSSQLDataSet.CustomerDataTable or CompactMSSQLDataSet.CustomerDataTable. Is there a way to have a function or a operator to convert the _datatable to its runtime type but still be able to use it's design time properties which are the same between the two types? something like: ((aType)_dataTable)[i].CustomerID = value; //or GetRuntimeType(_dataTable)[i].CustomerID = value;

    Read the article

  • Compile time type determination in C++

    - by dicroce
    A coworker recently showed me some code that he found online. It appears to allow compile time determination of whether a type has an "is a" relationship with another type. I think this is totally awesome, but I have to admit that I'm clueless as to how this actually works. Can anyone explain this to me? template<typename BaseT, typename DerivedT> inline bool isRelated(const DerivedT&) { DerivedT derived(); char test(const BaseT&); // sizeof(test()) == sizeof(char) char (&test(...))[2]; // sizeof(test()) == sizeof(char[2]) struct conversion { enum { exists = (sizeof(test(derived())) == sizeof(char)) }; }; return conversion::exists; } Once this function is defined, you can use it like this: #include <iostream> class base {}; class derived : public base {}; class unrelated {}; int main() { base b; derived d; unrelated u; if( isRelated<base>( b ) ) std::cout << "b is related to base" << std::endl; if( isRelated<base>( d ) ) std::cout << "d is related to base" << std::endl; if( !isRelated<base>( u ) ) std::cout << "u is not related to base" << std::endl; }

    Read the article

  • C# - Calling ToString() on a Reference Type

    - by nfplee
    Given two object arrays I need to compare the differences between the two (when converted to a string). I've reduced the code to the following and the problem still exists: public void Compare(object[] array1, object[] array2) { for (var i = 0; i < array1.Length; i++) { var value1 = GetStringValue(array1[i]); var value2 = GetStringValue(array2[i]); } } public string GetStringValue(object value) { return value != null && value.ToString() != string.Empty ? value.ToString() : ""; } The code executes fine no matter what object arrays I throw at it. However if one of the items in the array is a reference type then somehow the reference is updated. This causes issues later. It appears that this happens when calling ToString() against the object reference. I have updated the GetStringValue method to the following (which makes sure the object is either a value type or string) and the problem goes away. public string GetStringValue(object value) { return value != null && (value.GetType().IsValueType || value is string) && value.ToString() != string.Empty ? value.ToString() : ""; } However this is just a temporary hack as I'd like to be able to override the ToString() method on my reference types and compare them as well. I'd appreciate it if someone could explain why this is happening and offer a potential solution. Thanks

    Read the article

  • Torchlight Black Screen and doesn't show up

    - by Lelouch Reyiz
    When I open it in full screen I get a black screen that covers whole screen,in windowed mode middle of screen.Here is a video: https://copy.com/fvrGw7QIJ8Z0 Terminal Output: alperen@alperen-Inspiron-N5010 /usr/local/games/Torchlight $ ./Torchlight.bin.x86_64 Creating resource group General Creating resource group Internal Creating resource group Autodetect SceneManagerFactory for type 'DefaultSceneManager' registered. Registering ResourceManager for type Material Registering ResourceManager for type Mesh Registering ResourceManager for type Skeleton MovableObjectFactory for type 'ParticleSystem' registered. OverlayElementFactory for type Panel registered. OverlayElementFactory for type BorderPanel registered. OverlayElementFactory for type TextArea registered. Registering ResourceManager for type Font ArchiveFactory for archive type FileSystem registered. ArchiveFactory for archive type Zip registered. FreeImage version: 3.13.1 This program uses FreeImage, a free, open source image library supporting all common bitmap formats. See http://freeimage.sourceforge.net for details Supported formats: bmp,ico,jpg,jif,jpeg,jpe,jng,koa,iff,lbm,mng,pbm,pbm,pcd,pcx,pgm,pgm,png,ppm,ppm,ras,tga,targa,tif,tiff,wap,wbmp,wbm,psd,cut,xbm,xpm,gif,hdr,g3,sgi,exr,j2k,j2c,jp2,pfm,pct,pict,pic,bay,bmq,cr2,crw,cs1,dc2,dcr,dng,erf,fff,hdr,k25,kdc,mdc,mos,mrw,nef,orf,pef,pxn,raf,raw,rdc,sr2,srf,arw,3fr,cine,ia,kc2,mef,nrw,qtk,rw2,sti,drf,dsc,ptx,cap,iiq,rwz DDS codec registering Registering ResourceManager for type HighLevelGpuProgram Registering ResourceManager for type Compositor MovableObjectFactory for type 'Entity' registered. MovableObjectFactory for type 'Light' registered. MovableObjectFactory for type 'BillboardSet' registered. MovableObjectFactory for type 'ManualObject' registered. MovableObjectFactory for type 'BillboardChain' registered. MovableObjectFactory for type 'RibbonTrail' registered. Loading library lib64/OGRE/RenderSystem_GL Installing plugin: GL RenderSystem OpenGL Rendering Subsystem created. Plugin successfully installed Loading library lib64/OGRE/Plugin_ParticleFX Installing plugin: ParticleFX Particle Emitter Type 'Point' registered Particle Emitter Type 'Box' registered Particle Emitter Type 'Ellipsoid' registered Particle Emitter Type 'Cylinder' registered Particle Emitter Type 'Ring' registered Particle Emitter Type 'HollowEllipsoid' registered Particle Affector Type 'LinearForce' registered Particle Affector Type 'ColourFader' registered Particle Affector Type 'ColourFader2' registered Particle Affector Type 'ColourImage' registered Particle Affector Type 'ColourInterpolator' registered Particle Affector Type 'Scaler' registered Particle Affector Type 'Rotator' registered Particle Affector Type 'DirectionRandomiser' registered Particle Affector Type 'DeflectorPlane' registered Plugin successfully installed Loading library lib64/OGRE/Plugin_OctreeSceneManager Installing plugin: Octree & Terrain Scene Manager Plugin successfully installed *-*-* OGRE Initialising *-*-* Version 1.6.5 (Shoggoth) terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr Error: signal: 6 ./Torchlight.bin.x86_64(_ZN10LinuxUtils13crash_handlerEi+0x25)[0x17eb6f5] /lib/x86_64-linux-gnu/libc.so.6(+0x37000)[0x7fc647877000] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x39)[0x7fc647876f89] /lib/x86_64-linux-gnu/libc.so.6(abort+0x148)[0x7fc64787a398] /usr/lib/x86_64-linux-gnu/libstdc++.so.6(_ZN9__gnu_cxx27__verbose_terminate_handlerEv+0x155)[0x7fc6481826b5] /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0x5e836)[0x7fc648180836] /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0x5e863)[0x7fc648180863] /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0x5eaa2)[0x7fc648180aa2] /usr/lib/x86_64-linux-gnu/libstdc++.so.6(_ZSt20__throw_out_of_rangePKc+0x67)[0x7fc6481d25d7] /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0xbe3d3)[0x7fc6481e03d3] ./Torchlight.bin.x86_64(_ZN11CFileSystem21buildMassiveDataGroupEv+0x453)[0x1617805] ./Torchlight.bin.x86_64(_ZN11CFileSystemC1Eb+0x14be)[0x16145ae] ./Torchlight.bin.x86_64(_ZN22CMasterResourceManagerC1EP9CSettings+0x41a)[0xfe1d0a] ./Torchlight.bin.x86_64(_ZN5CGame5setupEb+0x79a)[0x73ceaa] ./Torchlight.bin.x86_64(_ZN5CGame5beginEPv+0x28d)[0x73b839] ./Torchlight.bin.x86_64(main+0x649)[0x146dbe4] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0x7fc647861ec5] ./Torchlight.bin.x86_64[0x739ca9]

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >