Search Results

Search found 1234 results on 50 pages for 'enum'.

Page 40/50 | < Previous Page | 36 37 38 39 40 41 42 43 44 45 46 47  | Next Page >

  • Adivce on Method overloads.

    - by Muhammad Kashif Nadeem
    Please see following methods. public static ProductsCollection GetDummyData(int? customerId, int? supplierId) { try { if (customerId != null && customerId > 0) { Filter.Add(Customres.CustomerId == customerId); } if (supplierId != null && supplierId > 0) { Filter.Add(Suppliers.SupplierId == supplierId); } ProductsCollection products = new ProductsCollection(); products.FetchData(Filter); return products; } catch { throw; } } public static ProductsCollection GetDummyData(int? customerId) { return ProductsCollection GetDummyData(customerId, (int?)null); } public static ProductsCollection GetDummyData() { return ProductsCollection GetDummyData((int?)null); } 1- Please advice how can I make overloads for both CustomerId and SupplierId because only one overload can be created with GetDummyData(int? ). Should I add another argument to mention that first argument is CustomerId or SupplierId for example GetDummyData(int?, string). OR should I use enum as 2nd argument and mention that first argument is CustoemId or SupplierId. 2- Is this condition is correct or just checking 0 is sufficient - if (customerId != null && customerId 0) 3- Using Try/catch like this is correct? 4- Passing (int?)null is correct or any other better approach. Edit: I have found some other posts like this and because I have no knowledge of Generics that is why I am facing this problem. Am I right? Following is the post. http://stackoverflow.com/questions/422625/overloaded-method-calling-overloaded-method

    Read the article

  • Understanding byte order and functions like CFSwapInt32HostToBig

    - by Typeoneerror
    I've got an enumeration in my game. A simple string message with an appended PacketType is being sent with the message (so it knows what to do with the message) over GameKit WIFI connection. I used Apple's GKRocket sample code as a starting point. The code itself is working fantastically; I just want to understand what the line with CFSwapInt32HostToBig is doing. What on earth does that do? and why does it need to do it? My guess is that it's making sure the PacketType value can be converted to an unsigned integer so it can send it reliably, but that doesn't sound all that correct to me. The documentation states "Converts a 32-bit integer from big-endian format to the host’s native byte order." but I don't understand what the means really. typedef enum { PacketTypeStart, // packet to notify games to start PacketTypeRequestSetup, // server wants client info PacketTypeSetup, // send client info to server PacketTypeSetupComplete, // round trip made for completion PacketTypeTurn, // packet to notify game that a turn is up PacketTypeRoll, // packet to send roll to players PacketTypeEnd // packet to end game } PacketType; // .... - (void)sendPacket:(NSData *)data ofType:(PacketType)type { NSLog(@"sendPacket:ofType(%d)", type); // create the data with enough space for a uint NSMutableData *newPacket = [NSMutableData dataWithCapacity:([data length]+sizeof(uint32_t))]; // Data is prefixed with the PacketType so the peer knows what to do with it. uint32_t swappedType = CFSwapInt32HostToBig((uint32_t)type); // add uint to data [newPacket appendBytes:&swappedType length:sizeof(uint32_t)]; // add the rest of the data [newPacket appendData:data]; // Send data checking for success or failure NSError *error; BOOL didSend = [_gkSession sendDataToAllPeers:newPacket withDataMode:GKSendDataReliable error:&error]; if (!didSend) { NSLog(@"error in sendDataToPeers: %@", [error localizedDescription]); } }

    Read the article

  • Q on Python serialization/deserialization

    - by neil
    What chances do I have to instantiate, keep and serialize/deserialize to/from binary data Python classes reflecting this pattern (adopted from RFC 2246 [TLS]): enum { apple, orange } VariantTag; struct { uint16 number; opaque string<0..10>; /* variable length */ } V1; struct { uint32 number; opaque string[10]; /* fixed length */ } V2; struct { select (VariantTag) { /* value of selector is implicit */ case apple: V1; /* VariantBody, tag = apple */ case orange: V2; /* VariantBody, tag = orange */ } variant_body; /* optional label on variant */ } VariantRecord; Basically I would have to define a (variant) class VariantRecord, which varies depending on the value of VariantTag. That's not that difficult. The challenge is to find a most generic way to build a class, which serializes/deserializes to and from a byte stream... Pickle, Google protocol buffer, marshal is all not an option. I made little success with having an explicit "def serialize" in my class, but I'm not very happy with it, because it's not generic enough. I hope I could express the problem. My current solution in case VariantTag = apple would look like this, but I don't like it too much import binascii import struct class VariantRecord(object): def __init__(self, number, opaque): self.number = number self.opaque = opaque def serialize(self): out = struct.pack('>HB%ds' % len(self.opaque), self.number, len(self.opaque), self.opaque) return out v = VariantRecord(10, 'Hello') print binascii.hexlify(v.serialize()) >> 000a0548656c6c6f Regards

    Read the article

  • Factory Method Pattern clarification

    - by nettguy
    My understanding of Factory Method Pattern is (Correct me if i am wrong) Factory Method Pattern "Factory Method allow the client to delegates the product creation (Instance Creation) to the subclass". There are two situation in which we can go for creating Factory Method pattern. (i) When the client is restricted to the product (Instance) creation. (ii) There are multiple products available.But a decision to be made which product instance need to be returned. If you want to create Abstract Method pattern You need to have abstract product Concrete Product Factory Method to return the appropriate product. Example : public enum ORMChoice { L2SQL, EFM, LS, Sonic } //Abstract Product public interface IProduct { void ProductTaken(); } //Concrete Product public class LinqtoSql : IProduct { public void ProductTaken() { Console.WriteLine("OR Mapping Taken:LinqtoSql"); } } //concrete product public class Subsonic : IProduct { public void ProductTaken() { Console.WriteLine("OR Mapping Taken:Subsonic"); } } //concrete product public class EntityFramework : IProduct { public void ProductTaken() { Console.WriteLine("OR Mapping Taken:EntityFramework"); } } //concrete product public class LightSpeed : IProduct { public void ProductTaken() { Console.WriteLine("OR Mapping Taken :LightSpeed"); } } public class Creator { //Factory Method public IProduct ReturnORTool(ORMChoice choice) { switch (choice) { case ORMChoice.EFM:return new EntityFramework(); break; case ORMChoice.L2SQL:return new LinqtoSql(); break; case ORMChoice.LS:return new LightSpeed(); break; case ORMChoice.Sonic:return new Subsonic(); break; default: return null; } } } **Client** Button_Click() { Creator c = new Creator(); IProduct p = c.ReturnORTool(ORMChoice.L2SQL); p.ProductTaken(); } Is my understanding of Factory Method is correct?

    Read the article

  • Accessing Static Methods on a Generic class in c#

    - by mrlane
    Hello, I have the following situation in code, which I suspect may be a bit dodgey: I have a class: abstract class DataAccessBase<T> : IDataAccess where T : AnotherAbstractClass This class DataAccessBase also has a static factory method which creates instances of derived classes of itself using an enum value in a which statement to decide which derived type to create: static IDataAccess CreateInstance(TypeToCreateEnum) Now, the types derived from DataAccessBase<T> are themselves NOT generic, they specify a type for T: class PoLcZoneData : DataAccessBase<PoLcZone> // PoLcZone is derived from AnotherAbstractClass So far I am not sure if this is pushing the limits of good use of generics, but what I am really concerned about is how to access the static CreateInstance() method in the first place: The way I am doing this at the moment is to simply pass any type T where T : AnotherAbstractClass. In particular I am passing AnotherAbstractClass itself. This allows compilation just fine, but it does seem to me that passing any type to a generic class just to get at the statics is a bit dodgey. I have actually simplified the situation somewhat as DataAccessBase<T> is the lower level in the inheritance chain, but the static factory methods exists in a middle tier with classes such as PoLcZoneData being the most derived on the only level that is not generic. What are peoples thoughts on this arrangement?

    Read the article

  • Extract enumeration data from .XSD file

    - by Ram
    Hi, I am trying to read enum from a XSD file. The schema is as follows <xs:schema id="ShipReports-v1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="unqualified" elementFormDefault="qualified" msdata:IsDataSet="true"> <xs:simpleType name="Type"> <xs:restriction base="xs:string"> <xs:enumeration value="Op1" /> <xs:enumeration value="Op2" /> <xs:enumeration value="Op3" /> </xs:restriction> </xs:simpleType> </xs:schema> I also tried using this but I am getting list item count as Zero. Following is the code I am using DataSet _sR = new DataSet(); _sR.ReadXmlSchema(assembly.GetManifestResourceStream("v1.xsd")); XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(_sR.GetXml()); XmlNamespaceManager xMan = new XmlNamespaceManager(xDoc.NameTable); xMan.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); XmlNodeList xNodeList = xDoc.SelectNodes( "//xs:schema/xs:simpleType[@name='Type']/xs:enumeration", xMan); string[] enumVal = new string[xNodeList.Count]; int ctr = 0; foreach (XmlNode xNode in xNodeList) { enumVal[ctr] = xNode.Attributes["value"].Value; ctr++; }

    Read the article

  • Factory Method Implementation

    - by cedar715
    I was going through the 'Factory method' pages in SO and had come across this link. And this comment. The example looked as a variant and thought to implement in its original way: to defer instantiation to subclasses... Here is my attempt. Does the following code implements the Factory pattern of the example specified in the link? Please validate and suggest if this has to undergo any re-factoring. public class ScheduleTypeFactoryImpl implements ScheduleTypeFactory { @Override public IScheduleItem createLinearScheduleItem() { return new LinearScheduleItem(); } @Override public IScheduleItem createVODScheduleItem() { return new VODScheduleItem(); } } public class UseScheduleTypeFactory { public enum ScheduleTypeEnum { CableOnDemandScheduleTypeID, BroadbandScheduleTypeID, LinearCableScheduleTypeID, MobileLinearScheduleTypeID } public static IScheduleItem getScheduleItem(ScheduleTypeEnum scheduleType) { IScheduleItem scheduleItem = null; ScheduleTypeFactory scheduleTypeFactory = new ScheduleTypeFactoryImpl(); switch (scheduleType) { case CableOnDemandScheduleTypeID: scheduleItem = scheduleTypeFactory.createVODScheduleItem(); break; case BroadbandScheduleTypeID: scheduleItem = scheduleTypeFactory.createVODScheduleItem(); break; case LinearCableScheduleTypeID: scheduleItem = scheduleTypeFactory.createLinearScheduleItem(); break; case MobileLinearScheduleTypeID: scheduleItem = scheduleTypeFactory.createLinearScheduleItem(); break; default: break; } return scheduleItem; } }

    Read the article

  • How to detect back button or forward button navigation in a silverlight navigation application

    - by parapura rajkumar
    When a Page is navigated to in silverlight you can override this method. protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); } The NavigationEventArgs has a NavigationMode enumeration which is defined as public enum NavigationMode { New = 0, Back = 1, Forward = 2, Refresh = 3, } But calling e.NavigationMode always throws a NotImplementedException Is there a way in silverlight to detect a page is being navigated to because the user hit the forward/back browser button. What I am trying to achieve is some kind of state that can be preserved when the user hits the back button. For example assume you have a customer page which is showing a list of customers in a datagrid. The user can select a customer and there is a detail view which shows all the orders for that customer. Now within an order item you can click a hyperlink link that takes you to the shipping history of the order which is a separate page. When the user hits the back button I want to go back to the customers page and automatically select the customer he was viewing. Is this possible at all ? I also tried out the fragment navigation feature NavigationService.Navigate(new Uri("#currentcustomerid=" + customer.Id.ToString(), UriKind.Relative)); when the customer selection changes but this adds too many items to the history when the user clicks various customers on the customer page. EDIT There is also an method you can override protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { } which is the same as handling the NavigationService.Navigating event as indicated by BugFinder's answer. In this method e.NavigationMode always returns New when when you hit the Back or Forward Button. The only time this method returns Back is when you explicitly call NavigationService.GoBack()

    Read the article

  • Method return type

    - by sarah xia
    Hi, In my company, a system is designed to have 3 layers. Layer1 is responsible for business logic handling. Layer3 is calling back end systems. Layer2 sits between the two layers so that layer1 doesn't need to know about the back end systems. To replay information from layer3, layer2 needs to define interface to layer1. For example, layer1 wants to check if a PIN from user is correct. It calls layer2 checkPin() method and then layer2 calls the relevant back end system. The checkPin() results could be: correctPin, inCorrectPin and internalError. At the moment, we defined the return type 'int'. So if layer2 returns 0, it means correctPin; if 1 is returned, it means inCorrectPin; if 9 is returned it means internalError. It works. However I feel a bit uneasy about this approach. Are there better ways to do it? For example define an enum CheckPinResult{CORRECT_PIN,INCORRECT_PIN,INTERNAL_ERROR}, and return CheckPinResult type? Thanks, Sarah

    Read the article

  • Why is there unreachable code here?

    - by Richard
    I am writing a c# app and want to output error messages to either the console or a messagebox (Depending on the app type: enum AppTypeChoice { Console, Windows } ), and also control wether the app keeps running or not ( bool StopOnError ). I came up with this method that will check all the criteria, but I'm getting an "unreachable code detected" warning. I can't see why! Here is the whole method (Brace yourselves for some hobbyist code!) public void OutputError(string message) { string standardMessage = "Something went WRONG!. [ But I'm not telling you what! ]"; string defaultMsgBoxTitle = "Aaaaarrrggggggggggg!!!!!"; string dosBoxOutput = "\n\n*** " + defaultMsgBoxTitle + " *** \n\n Message was: '" + message + "'\n\n"; AppTypeChoice appType = DataDefs.AppType; DebugLevelChoice level = DataDefs.DebugLevel; // Decide how much info we should give out here... if (level != DebugLevelChoice.None) { // Give some info.... if (appType == AppTypeChoice.Windows) MessageBox.Show(message, defaultMsgBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); else Console.WriteLine(dosBoxOutput); } else { // Be very secretive... if (appType == AppTypeChoice.Windows) MessageBox.Show(standardMessage, defaultMsgBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); else Console.WriteLine(standardMessage); } // Decide if app falls over or not.. if (DataDefs.StopOnError == true) Environment.Exit(0); // UNREACHABLE CODE HERE } Also, while I have your attention, to get the app type, I'm just using a constant at the top of the file (ie. AppTypeChoice.Console in a Console app etc) - is there a better way of doing this (i mean finding out in code if it is a DOS or Windows app)? Also, I noticed that I can use a messagebox with a fully-qualified path in a Console app...How bad is is to do that ( I mean, will I get tarred and feathered when other developers see it?!) Thanks for your help

    Read the article

  • Masspay and MySql

    - by Mike
    Hi, I am testing Paypal's masspay using their 'MassPay NVP example' and I having difficulty trying to amend the code so inputs data from my MySql database. Basically I have user table in MySql which contains email address, status of payment (paid,unpaid) and balance. CREATE TABLE `users` ( `user_id` int(10) unsigned NOT NULL auto_increment, `email` varchar(100) collate latin1_general_ci NOT NULL, `status` enum('unpaid','paid') collate latin1_general_ci NOT NULL default 'unpaid', `balance` int(10) NOT NULL default '0', PRIMARY KEY (`user_id`) ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci Data : 1 [email protected] paid 100 2 [email protected] unpaid 11 3 [email protected] unpaid 20 4 [email protected] unpaid 1 5 [email protected] unpaid 20 6 [email protected] unpaid 15 I then have created a query which selects users with an unpaid balance of $10 and above : $conn = db_connect(); $query=$conn->query("SELECT * from users WHERE balance >='10' AND status = ('unpaid')"); What I would like to is for each record returned from the query for it to populate the code below: Now the code which I believe I need to amend is as follows: for($i = 0; $i < 3; $i++) { $receiverData = array( 'receiverEmail' => "[email protected]", 'amount' => "example_amount",); $receiversArray[$i] = $receiverData; } However I just can't get it to work, I have tried using mysqli_fetch_array and then replaced "[email protected]" with $row['email'] and "example_amount" with row['balance'] in various methods of coding but it doesn't work. Also I need it to loop to however many rows that were retrieved from the query as <3 in the for loop above. So the end result I am looking for is for the $nvpStr string to pass with something like this: $nvpStr = "&EMAILSUBJECT=test&RECEIVERTYPE=EmailAddress&CURRENCYCODE=USD&[email protected]&L_Amt=11&[email protected]&L_Amt=11&[email protected]&L_Amt=20&[email protected]&L_Amt=20&[email protected]&L_Amt=15"; Thanks

    Read the article

  • In asp.Net, writing code in the control tag generates compile error

    - by Nour Sabouny
    Hi this is really strange !! But look at the following asp code: <div runat="server" id="MainDiv"> <%foreach (string str in new string[]{"First#", "Second#"}) { %> <div id="<%=str.Replace("#","div") %>"> </div> <%} %> </div> now if you put this code inside any web page (and don't worry about the moral of this code, I made it just to show the idea) you'll get this error : Compiler Error Message: CS1518: Expected class, delegate, enum, interface, or struct Of course the error has nothing to do with the real problem, I searched for the code that was generated by asp.net and figured out the following : private void @__RenderMainDiv(System.Web.UI.HtmlTextWriter @__w, System.Web.UI.Control parameterContainer) { @__w.Write("\r\n "); #line 20 "blabla\blabla\Default.aspx" foreach (string str in new string[] { "First#", "Second#" }) { #line default #line hidden @__w.Write("\r\n <div id=\""); #line 22 "blabla\blabla\Default.aspx" @__w.Write(str.Replace("#", "div")); #line default #line hidden @__w.Write("\">\r\n "); } This is the code that was generated from the asp page and this is the method that is meant to render our div (MainDiv), I found out that there is a missing bracket "}" that closes the method or the (for loop). now the problem has three parts: 1- first you should have a server control (in our situation is the MainDiv) and I'm not sure if it is only the div tag. 2- HTML control inside the server control and a code inside it using the double quotation mark ( for example <div id="<%=str instead of <div id='<%=str. 3-Any keyword which has block brackets e.g.:for{},while{},using{}...etc. now removing any part, will solve the problem !!! how is this happening ?? any ideas ? BTW: please help me to make the question more obvious, because I couldn't find the best words to describe the problem.

    Read the article

  • C++ error: expected initializer before ‘&’ token

    - by Werner
    Hi, the following piece of C++ code compiled two years ago in a suse 10.1 Linux machine. #ifndef DATA_H #define DATA_H #include <iostream> #include <iomanip> inline double sqr(double x) { return x*x; } enum Direction { X,Y,Z }; inline Direction next(const Direction d) { switch(d) { case X: return Y; case Y: return Z; case Z: return X; } } inline ostream& operator<<(ostream& os,const Direction d) { switch(d) { case X: return os << "X"; case Y: return os << "Y"; case Z: return os << "Z"; } } ... ... Now, I am trying to compile it on Ubuntu 9.10 and I get the error: data.h:20: error: expected initializer before ‘&’ token which is referred to the line of: inline ostream& operator<<(ostream& os,const Direction d) the g++ used on this machine is: Using built-in specs. Target: x86_64-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.4.1-4ubuntu9' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --program-suffix=-4.4 --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --disable-werror --with-arch-32=i486 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu Thread model: posix gcc version 4.4.1 (Ubuntu 4.4.1-4ubuntu9) Could you give me some hint about this error? Thanks

    Read the article

  • How to associate static entity instances in a Session without database retrieval

    - by Michael Hedgpeth
    I have a simple Result class that used to be an Enum but has evolved into being its own class with its own table. public class Result { public static readonly Result Passed = new Result(StatusType.Passed) { Id = [Predefined] }; public static readonly Result NotRun = new Result(StatusType.NotRun) { Id = [Predefined] }; public static readonly Result Running = new Result(StatusType.Running) { Id = [Predefined] }; } Each of these predefined values has a row in the database at their predefined Guid Id. There is then a failed result that has an instance per failure: public class FailedResult : Result { public FailedResult(string description) : base(StatusType.Failed) { . . . } } I then have an entity that has a Result: public class Task { public Result Result { get; set; } } When I save a Task, if the Result is a predefined one, I want NHibernate to know that it doesn't need to save that to the database, nor does it need to fetch it from the database; I just want it to save by Id. The way I get around this is when I am setting up the session, I call a method to load the static entities: protected override void OnSessionOpened(ISession session) { LockStaticResults(session, Result.Passed, Result.NotRun, Result.Running); } private static void LockStaticResults(ISession session, params Result[] results) { foreach (var result in results) { session.Load(result, result.Id); } } The problem with the session.Load method call is it appears to be fetching to the database (something I don't want to do). How could I make this so it does not fetch the database, but trusts that my static (immutable) Result instances are both up to date and a part of the session?

    Read the article

  • What are the hibernate annotations used to persist a value typed Map with an enumerated type as a ke

    - by Jason Novak
    I am having trouble getting the right hibernate annotations to use on a value typed Map with an enumerated class as a key. Here is a simplified (and extremely contrived) example. public class Thing { public String id; public Letter startLetter; public Map<Letter,Double> letterCounts = new HashMap<Letter, Double>(); } public enum Letter { A, B, C, D } Here are my current annotations on Thing @Entity public class Thing { @Id public String id; @Enumerated(EnumType.STRING) public Letter startLetter; @CollectionOfElements @JoinTable(name = "Thing_letterFrequencies", joinColumns = @JoinColumn(name = "thingId")) @MapKey(columns = @Column(name = "letter", nullable = false)) @Column(name = "count") public Map<Letter,Double> letterCounts = new HashMap<Letter, Double>(); } Hibernate generates the following DDL to create the tables for my MySql database create table Thing (id varchar(255) not null, startLetter varchar(255), primary key (id)) type=InnoDB; create table Thing_letterFrequencies (thingId varchar(255) not null, count double precision, letter tinyblob not null, primary key (thingId, letter)) type=InnoDB; Notice that hibernate tries to define letter (my map key) as a tinyblob, however it defines startLetter as a varchar(255) even though both are of the enumerated type Letter. When I try to create the tables I see the following error BLOB/TEXT column 'letter' used in key specification without a key length I googled this error and it appears that MySql has issues when you try to make a tinyblob column part of a primary key, which is what hibernate needs to do with the Thing_letterFrequencies table. So I would rather have letter mapped to a varchar(255) the way startLetter is. Unfortunately, I've been fussing with the MapKey annotation for a while now and haven't been able to make this work. I've also tried @MapKeyManyToMany(targetEntity=Product.class) without success. Can anyone tell me what are the correct annotations for my letterCounts map so that hibernate will treat the letterCounts map key the same way it does startLetter?

    Read the article

  • MSTest unit test passes by itself, fails when other tests are run

    - by Sarah Vessels
    I'm having trouble with some MSTest unit tests that pass when I run them individually but fail when I run the entire unit test class. The tests test some code that SLaks helped me with earlier, and he warned me what I was doing wasn't thread-safe. However, now my code is more complicated and I don't know how to go about making it thread-safe. Here's what I have: public static class DLLConfig { private static string _domain; public static string Domain { get { return _domain = AlwaysReadFromFile ? readCredentialFromFile(DOMAIN_TAG) : _domain ?? readCredentialFromFile(DOMAIN_TAG); } } } And my test is simple: string expected = "the value I know exists in the file"; string actual = DLLConfig.Domain; Assert.AreEqual(expected, actual); When I run this test by itself, it passes. When I run it alongside all the other tests in the test class (which perform similar checks on different properties), actual is null and the test fails. I note this is not a problem with a property whose type is a custom Enum type; maybe I'm having this problem with the Domain property because it is a string? Or maybe it's a multi-threaded issue with how MSTest works?

    Read the article

  • Set fields with instrospection - Problem with String.valueOf(String)

    - by fabb
    Hey there! I'm setting public fields of the Object 'this' via reflection. Both the field name and the value are given as String. I use several various field types: Boolean, Integer, Float, Double, an own enum, and a String. It works with all of them except with a String. The exception that gets thrown is that no method with the Signature String.valueOf(String) exists... Now I use a dirty instanceof workaround to detect if each field is a String and in that case just copy the value to the field. private void setField(String field, String value) throws Exception { Field wField = this.getClass().getField(field); if(wField.get(this) instanceof String){ //TODO dirrrrty hack //stupid workaround as java.lang.String.valueOf(java.lang.String) fails... wField.set(this, value); }else{ Method parseMethod = wField.getType().getMethod("valueOf", new Class[]{String.class}); wField.set(this, parseMethod.invoke(wField, value)); } } Any ideas how to avoid that workaround? Do you think java.lang.String should support the method valueOf(String)? thanks, fabb

    Read the article

  • verilog / systemverilog -- What is the behavior of blocking statements across two always blocks?

    - by miles.sherman
    I am wondering about the behavior of the below code. There are two always blocks, one is combinational to calculate the next_state signal, the other is sequential which will perform some logic and determine whether or not to shutdown the system. It does this by setting the shutdown_now signal high and then calling state <= next_state. My question is if the conditions become true that the shutdown_now signal is set (during clock cycle n) in a blocking manner before the state <= next_state line, will the state during clock cycle n+1 be SHUTDOWN or RUNNING? In other words, does the shutdown_now = 1'b1 line block across both state machines since the state signal is dependent on it through the next_state determination? enum {IDLE, RUNNING, SHUTDOWN} state, next_state; logic shutdown_now; // State machine (combinational) always_comb begin case (state) IDLE: next_state <= RUNNING; RUNNING: next_state <= shutdown ? SHUTDOWN : RUNNING; SHUTDOWN: next_state <= SHUTDOWN; default: next_state <= SHUTDOWN; endcase end // Sequential Behavior always_ff @ (posedge clk) begin // Some code here if (/*some condition) begin shutdown_now = 1'b0; end else begin shutdown_now = 1'b1; end state <= next_state; end

    Read the article

  • Design problem with callback functions in android

    - by Franz Xaver
    Hi folks! I'm currently developing an app in android that is accessing wifi values, that is, the application needs to scan for all access point and their specific signal strengths. I know that I have to extend the class BroadcastReceiver overwriting the method BroadcastReceiver.onReceive(Context context, Intent intent) which is called when the values are ready. Perhaps there exist solutions provided by the android system itself but I'm relatively new to android so I could need some help. The problem I encountered is that I got one class (an activity, thus controlled by the user) that needs this scan results for two different things (first to save the values in a database or second, to use them for further calculations but not both at one moment!) So how to design the callback system in order to "transport" the scan results from onReceive(Context context, Intent intent) to the operation intended by the user? My first solution was to define enums for each use case (save or use for calculations) which wlan-interested classes have to submit when querying for the values. But that would force the BroadcastReceiverextending class to save the current enum and use it as a parameter in the callback function of the querying class (this querying class needs to know what it asked for when getting backcalled) But that seems to me kind of dirty ;) So anyone a good idea for this?

    Read the article

  • Partial template specialization: matching on properties of specialized template parameter

    - by Kenzo
    template <typename X, typename Y> class A {}; enum Property {P1,P2}; template <Property P> class B {}; class C {}; Is there any way to define a partial specialization of A such that A<C, B<P1> > would be A's normal template, but A<C, B<P2> > would be the specialization? Replacing the Y template parameter by a template template parameter would be nice, but is there a way to partially specialize it based on P then? template <typename X, template <Property P> typename Y> class A {}; // template <typename X> class A<X,template<> Y<P2> > {}; <-- not valid Is there a way by adding traits to a specialization template<> B<P2> and then using SFINAE in A?

    Read the article

  • Advice on Method overloads.

    - by Muhammad Kashif Nadeem
    Please see following methods. public static ProductsCollection GetDummyData(int? customerId, int? supplierId) { try { if (customerId != null && customerId > 0) { Filter.Add(Customres.CustomerId == customerId); } if (supplierId != null && supplierId > 0) { Filter.Add(Suppliers.SupplierId == supplierId); } ProductsCollection products = new ProductsCollection(); products.FetchData(Filter); return products; } catch { throw; } } public static ProductsCollection GetDummyData(int? customerId) { return ProductsCollection GetDummyData(customerId, (int?)null); } public static ProductsCollection GetDummyData() { return ProductsCollection GetDummyData((int?)null); } 1- Please advice how can I make overloads for both CustomerId and SupplierId because only one overload can be created with GetDummyData(int? ). Should I add another argument to mention that first argument is CustomerId or SupplierId for example GetDummyData(int?, string). OR should I use enum as 2nd argument and mention that first argument is CustoemId or SupplierId. 2- Is this condition is correct or just checking 0 is sufficient - if (customerId != null && customerId 0) 3- Using Try/catch like this is correct? 4- Passing (int?)null is correct or any other better approach. Edit: I have found some other posts like this and because I have no knowledge of Generics that is why I am facing this problem. Am I right? Following is the post. http://stackoverflow.com/questions/422625/overloaded-method-calling-overloaded-method

    Read the article

  • error LNK2001: unresolved external symbol

    - by numerical25
    I am receiving this error >GXRenderManager.obj : error LNK2001: unresolved external symbol "private: static class GXRenderer * GXRenderManager::renderDevice" (?renderDevice@GXRenderManager@@0PAVGXRenderer@@A) The following is my code... GXDX.h class GXDX: public GXRenderer { public: void Render(); void StartUp(); }; GXGL.h class GXGL: public GXRenderer { public: void Render(); void StartUp(); }; GXRenderer class GXRenderer { public: virtual void Render() = 0; virtual void StartUp() = 0; }; GXRenderManager.h #ifndef GXRM #define GXRM #include <windows.h> #include "GXRenderer.h" #include "GXDX.h" #include "GXGL.h" enum GXDEVICE { DIRECTX, OPENGL }; class GXRenderManager { public: static int Ignite(GXDEVICE); private: static GXRenderer *renderDevice; }; #endif GXRenderManager.cpp #include "GXRenderManager.h" int GXRenderManager::Ignite(GXDEVICE DeviceType) { switch(DeviceType) { case DIRECTX: GXRenderManager::renderDevice = new GXDX; return 1; break; case OPENGL: GXRenderManager::renderDevice = new GXGL; return 1; break; default: return 0; } } main.cpp #include "GXRenderManager.h" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { return 0; } I am not trying to get it to do anything. I am just trying to compile with no errors. I am new with all this so if anyone can give me a hand. that will be great. thanks

    Read the article

  • Reloading the model of a TTTableViewController

    - by user341338
    My problem is that I have a Register Controller and a Login Controller. The Login Screen displays a Login Screen or a Logout Screen depending if a user is logged in. Now when a user registers, does not close the app, and then goes to the Login Screen it will still display a Login Screen, although there is a logged in user already. This is because the Screen is created when the application loads and does not change afterwards. I tried doing this: - (id)init { if (self = [super init]) { [self invalidateModel]; [self reload]; but that did not work, since it is only called on the first init. then i tried: - (void)viewDidLoad { [self invalidateModel]; [self reload]; } But that method had the same problem. Then I found this method: - (TTNavigationMode)navigationModeForURL:(NSString*)URL; with the following options: typedef enum { TTNavigationModeNone, TTNavigationModeCreate, // a new view controller is created each time TTNavigationModeShare, // a new view controller is created, cached and re-used TTNavigationModeModal, // a new view controller is created and presented modally TTNavigationModeExternal, // an external app will be opened } TTNavigationMode; It seems like TTNavigationModeCreate would be the right thing to use, but I have no clue how to use it. Any help? Thnx.

    Read the article

  • Foreign key not working in MySQL: Why can I INSERT a value that's not in the foreign column?

    - by stalepretzel
    I've created a table in MySQL: CREATE TABLE actions ( A_id int NOT NULL AUTO_INCREMENT, type ENUM('rate','report','submit','edit','delete') NOT NULL, Q_id int NOT NULL, U_id int NOT NULL, date DATE NOT NULL, time TIME NOT NULL, rate tinyint(1), PRIMARY KEY (A_id), CONSTRAINT fk_Question FOREIGN KEY (Q_id) REFERENCES questions(P_id), CONSTRAINT fk_User FOREIGN KEY (U_id) REFERENCES users(P_id)); This created the table I wanted just fine (although a "DESCRIBE actions;" command showed me that the foreign keys were keys of type MUL, and I'm not sure what this means). However, when I try to enter a Q_id or a U_id that does not exist in the questions or users tables, MySQL still allows these values. What did I do wrong? How can I prevent a table with a foreign key from accepting invalid data? If I add TYPE=InnoDB to the end, I get an error: ERROR 1005 (HY000): Can't create table './quotes/actions.frm' (errno: 150) Why might that happen? I'm told that it's important to enforce data integrity with functional foreign keys, but also that InnoDB should not be used with MySQL. What do you recommend?

    Read the article

  • How can i use complextype class or multi type class is it generic collection?

    - by programmerist
    i need a complex returning type. i have 4 class returning types COMPLEXTYPE must include Company, Muayene, Radyoloji, Satis because i must return data switch case situation how can i do? Maybe i need generic collections How can i do that? public class GenoTipController { public COMPLEXTYPE Generate(DataModelType modeltype) { _Company company = null; _Muayene muayene = null; _Radyoloji radyoloji = null; _Satis satis = null; switch (modeltype) { case DataModelType.Radyoloji: radyoloji = new Radyoloji(); return radyoloji; break; case DataModelType.Satis: satis = new Satis(); return satis; break; case DataModelType.Muayene: muayene = new Muayene(); return muayene; break; case DataModelType.Company: company = new Company(); return company; break; default: break; } } } public class CompanyView { public static List GetPersonel() { GenoTipController controller = new GenoTipController(); _Company company = controller.Generate(DataModelType.Company); return company.GetPersonel(); } } public enum DataModelType { Radyoloji, Satis, Muayene, Company }

    Read the article

< Previous Page | 36 37 38 39 40 41 42 43 44 45 46 47  | Next Page >