Search Results

Search found 1816 results on 73 pages for 'equals'.

Page 18/73 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Use case modelling for calculator

    - by kyrogue
    hi, i need help modelling a use case diagram from a topic, it will be in java GUI Design a Calculator that 1.Allow user to key in a legitimate arithmetic statement that involves number, operator +, - and bracket '(' and ')' ; 2.When user press “Calculate” button, display result; 3.Some legitimate statement would be ((3+2)-4+2) (equals 3) and (-2+3)-(3-1) (equals -1); 4.You should NOT use a pre-existing function that just take in the statement as a parameter and returns the result but you should write the logic of parsing every character in your code. 5.Store the last statement and answer so it is displayed when user press the “Last calculation” button. i have designed two use case diagrams using UML on netbeans 6.5.1, one of the use case i am not sure whether is it containing too much use cases etc, while the other is what i think could be too vague for the topic.i hope to get some feedback on whether the use case diagram are appropriate, thanks.

    Read the article

  • C# Extend array type to overload operators

    - by Episodex
    I'd like to create my own class extending array of ints. Is that possible? What I need is array of ints that can be added by "+" operator to another array (each element added to each), and compared by "==", so it could (hopefully) be used as a key in dictionary. The thing is I don't want to implement whole IList interface to my new class, but only add those two operators to existing array class. I'm trying to do something like this: class MyArray : Array<int> But it's not working that way obviously ;). Sorry if I'm unclear but I'm searching solution for hours now... UPDATE: I tried something like this: class Zmienne : IEquatable<Zmienne> { public int[] x; public Zmienne(int ilosc) { x = new int[ilosc]; } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) { return false; } return base.Equals((Zmienne)obj); } public bool Equals(Zmienne drugie) { if (x.Length != drugie.x.Length) return false; else { for (int i = 0; i < x.Length; i++) { if (x[i] != drugie.x[i]) return false; } } return true; } public override int GetHashCode() { int hash = x[0].GetHashCode(); for (int i = 1; i < x.Length; i++) hash = hash ^ x[i].GetHashCode(); return hash; } } Then use it like this: Zmienne tab1 = new Zmienne(2); Zmienne tab2 = new Zmienne(2); tab1.x[0] = 1; tab1.x[1] = 1; tab2.x[0] = 1; tab2.x[1] = 1; if (tab1 == tab2) Console.WriteLine("Works!"); And no effect. I'm not good with interfaces and overriding methods unfortunately :(. As for reason I'm trying to do it. I have some equations like: x1 + x2 = 0.45 x1 + x4 = 0.2 x2 + x4 = 0.11 There are a lot more of them, and I need to for example add first equation to second and search all others to find out if there is any that matches the combination of x'es resulting in that adding. Maybe I'm going in totally wrong direction?

    Read the article

  • pySerial writes to Arduino Uno get buffered

    - by Bhaktavatsalam Nallanthighal
    I have a Python script that writes short messages to the serial port on my Arduino Uno board using pySerial. There is a loop and depending on some conditions, multiple writes can happen within a loop, something like this: while True: #Conditions block 1 if <CONDITION1>: serial.writelines("INIT") elif <CONDITION2>: serial.writelines("NEW") ... #Conditions block 2 if <CONDITION1>: # Fetch something from the Internet serial.writelines("CHECK") elif <CONDITION2>: # Fetch something from the Internet serial.writelines("STOP") ... But, when my Arduino board receives this it receives the first message as INIT, but the second one is being read as INITSTOP or INITCHECK and third one gets concatenated to the previous messages. My arduino program checks for specific message in this way: if(msg.equals("CHECK")) { // Do something } else if(msg.equals("INIT")) { // Do Something else } Can anyone guide me on this? BTW, I don't think the problem is with the Arduino as it works perfectly when I test it with the Serial Monitor available with the IDE. I've tried adding sleeps of upto 10 seconds before every write, but that did not work out.

    Read the article

  • Updating Android Home Screen TextView

    - by jmontex2
    Hi, How can we update the View of a Home Screen Widget on the onReceive method of AppWidgetProvider?. I am trying to update the TextView of my Home screen widget but it seems that I cant access the TextView of my AppWidgetProvider on onReceive method. Here is a sample code of my onReceive public void onReceive(Context context,Intent intent) { final String action = intent.getAction(); if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) { final int appWidgetId = intent.getExtras().getInt( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) { this.onDeleted(context, new int[] { appWidgetId }); } } else { if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) { String msg = "null"; try { msg = intent.getStringExtra("msg"); } catch (NullPointerException e) { } Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); // code for gathering the text to update the TextView } } super.onReceive(context, intent); }

    Read the article

  • Type casting in TPC inheritance

    - by Mohsen Esmailpour
    I have several products like HotelProduct, FlightProduct ... which derived from BaseProduct class. The table of these products will be generated in TPC manner in database. There is OrderLine class which has a BaseProduct. My problem is when i select an OrderLine with related product i don't know how cast BaseProduct to derived product. for example i have this query: var order = (from odr in _context.Orders join orderLine in _context.OrderLines on odr.Id equals orderLine.OrderId join hotel in _context.Products.OfType<HotelProduct>() on orderLine.ProductId equals hotel.Id where odr.UserId == userId && odr.Id == orderId orderby odr.OrderDate descending select odr).SingleOrDefault(); In OrderLine i have BaseProduct properties not properties of HotelProduct. Is there any way to cast BaseProduct to derived class in OrderLine or any other solutions ?

    Read the article

  • linq to sql using foreign keys returning iqueryable(of myEntity]

    - by Gern Blandston
    I'm trying to use Linq to SQL to return an IQueryable(of Project) when using foreign key relationships. Using the below schema, I want to be able to pass in a UserId and get all the projects created for the company the user is associated with. DB tables: Projects Projid ProjCreator FK (UserId from UserInfo table) Companyid FK (CompanyID from Companies table) UserInfo UserID PK Companyid FK Companies CompanyId PK Description I can get the iqueryable(of project) when simply getting the ProjectCreator with this: Return (From p In db.Projects _ Where p.ProjectCreator = Me.UserId) But I'm having trouble getting the syntax to get a iqueryable(of projects) when using foreign keys. Below gives me an IQueryable(of anonymous) but I can't seem to convince it to give me an IQueryable(of project) even if I try to cast it: Dim retval = (From p In db.Projects _ Join c In db.Companies On p.CompanyId Equals c.CompanyId _ Join u In db.UserInfos On u.CompanyId Equals c.CompanyId _ Where u.Login = UserId)

    Read the article

  • Recursion problem; completely lost

    - by timeNomad
    So I've been trying to solve this assignment whole day, just can't get it. The following function accepts 2 strings, the 2nd (not 1st) possibly containing *'s (asterisks). An * is a replacement for a string (empty, 1 char or more), it can appear appear (only in s2) once, twice, more or not at all, it cannot be adjacent to another * (ab**c), no need to check that. public static boolean samePattern(String s1, String s2) It returns true if strings are of the same pattern. It must be recursive, not use any loops, static & global variables. Can use local variables & method overloading. Can use only these methods: charAt(i), substring(i), substring(i, j), length(). Examples: 1: TheExamIsEasy; 2: "The*xamIs*y" --- true 1: TheExamIsEasy; 2: "Th*mIsEasy*" --- true 1: TheExamIsEasy; 2: "*" --- true 1: TheExamIsEasy; 2: "TheExamIsEasy" --- true 1: TheExamIsEasy; 2: "The*IsHard" --- FALSE I tried comparing the the chars one by one using charAt until an asterisk is encountered, then check if the asterisk is an empty one by comparing is successive char (i+1) with the char of s1 at position i, if true -- continue recursion with i+1 as counter for s2 & i as counter for s1; if false -- continue recursion with i+1 as counters for both. Continue this until another asterisk is found or end of string. I dunno, my brain loses track of things, can't concentrate, any pointers / hints? Am I in the right direction? Also, it's been told that a backtracking technique is to be used to solve this. My code so far (doesn't do the job, even theoretically): public static boolean samePattern(String s1, String s2) { if (s1.equals(s2) || s2 == "*") { return true; } return samePattern(s1, s2, 1); } public static boolean samePattern(String s1, String s2, int i) { if (s1.equals(s2)) return true; if (i == s2.length() - 1) // No *'s found -- not same pattern. return false; if (s1.substring(0, i).equals(s2.substring(0, i))) samePattern(s1, s2, i+1); else if (s2.charAt(i-1) == '*') samePattern(s1.substring(0, i-1), s2.substring(0, i), 1); // new smaller strings. else samePattern(s1.substring(1), s2, i); }

    Read the article

  • Building 'flat' rather than 'tree' LINQ expressions

    - by Ian Gregory
    I'm using some code (available here on MSDN) to dynamically build LINQ expressions containing multiple OR 'clauses'. The relevant code is var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue)))); var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal)); This generates a LINQ expression that looks something like this: (((((ID = 5) OR (ID = 4)) OR (ID = 3)) OR (ID = 2)) OR (ID = 1)) I'm hitting the recursion limit (100) when using this expression, so I'd like to generate an expression that looks like this: (ID = 5) OR (ID = 4) OR (ID = 3) OR (ID = 2) OR (ID = 1) How would I modify the expression building code to do this?

    Read the article

  • C# IQueryable<T> does my code make sense?

    - by Pandiya Chendur
    I use this to get a list of materials from my database.... public IQueryable<MaterialsObj> FindAllMaterials() { var materials = from m in db.Materials join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id select new MaterialsObj() { Id = Convert.ToInt64(m.Mat_id), Mat_Name = m.Mat_Name, Mes_Name = Mt.Name, }; return materials; } But i have seen in an example that has this, public IQueryable<MaterialsObj> FindAllMaterials() { return from m in db.Materials join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id select new MaterialsObj() { Id = Convert.ToInt64(m.Mat_id), Mat_Name = m.Mat_Name, Mes_Name = Mt.Name, }; } Is there a real big difference between the two methods... Assigning my linq query to a variable and returning it... Is it a good/bad practise? Any suggestion which should i use?

    Read the article

  • How to select all parent objects into DataContext using single LINQ query ?

    - by too
    I am looking for an answer to a specific problem of fetching whole LINQ object hierarchy using single SELECT. At first I was trying to fill as much LINQ objects as possible using LoadOptions, but AFAIK this method allows only single table to be linked in one query using LoadWith. So I have invented a solution to forcibly set all parent objects of entity which of list is to be fetched, although there is a problem of multiple SELECTS going to database - a single query results in two SELECTS with the same parameters in the same LINQ context. For this question I have simplified this query to popular invoice example: public static class Extensions { public static IEnumerable<T> ForEach<T>(this IEnumerable<T> collection, Action<T> func) { foreach(var c in collection) { func(c); } return collection; } } public IEnumerable<Entry> GetResults(AppDataContext context, int CustomerId) { return ( from entry in context.Entries join invoice in context.Invoices on entry.EntryInvoiceId equals invoice.InvoiceId join period in context.Periods on invoice.InvoicePeriodId equals period.PeriodId // LEFT OUTER JOIN, store is not mandatory join store in context.Stores on entry.EntryStoreId equals store.StoreId into condStore from store in condStore.DefaultIfEmpty() where (invoice.InvoiceCustomerId = CustomerId) orderby entry.EntryPrice descending select new { Entry = entry, Invoice = invoice, Period = period, Store = store } ).ForEach(x => { x.Entry.Invoice = Invoice; x.Invoice.Period = Period; x.Entry.Store = Store; } ).Select(x => x.Entry); } When calling this function and traversing through result set, for example: var entries = GetResults(this.Context); int withoutStore = 0; foreach(var k in entries) { if(k.EntryStoreId == null) withoutStore++; } the resulting query to database looks like (single result is fetched): SELECT [t0].[EntryId], [t0].[EntryInvoiceId], [t0].[EntryStoreId], [t0].[EntryProductId], [t0].[EntryQuantity], [t0].[EntryPrice], [t1].[InvoiceId], [t1].[InvoiceCustomerId], [t1].[InvoiceDate], [t1].[InvoicePeriodId], [t2].[PeriodId], [t2].[PeriodName], [t2].[PeriodDateFrom], [t4].[StoreId], [t4].[StoreName] FROM [Entry] AS [t0] INNER JOIN [Invoice] AS [t1] ON [t0].[EntryInvoiceId] = [t1].[InvoiceId] INNER JOIN [Period] AS [t2] ON [t2].[PeriodId] = [t1].[InvoicePeriodId] LEFT OUTER JOIN ( SELECT 1 AS [test], [t3].[StoreId], [t3].[StoreName] FROM [Store] AS [t3] ) AS [t4] ON [t4].[StoreId] = ([t0].[EntryStoreId]) WHERE (([t1].[InvoiceCustomerId]) = @p0) ORDER BY [t0].[InvoicePrice] DESC -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [186] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1 SELECT [t0].[EntryId], [t0].[EntryInvoiceId], [t0].[EntryStoreId], [t0].[EntryProductId], [t0].[EntryQuantity], [t0].[EntryPrice], [t1].[InvoiceId], [t1].[InvoiceCustomerId], [t1].[InvoiceDate], [t1].[InvoicePeriodId], [t2].[PeriodId], [t2].[PeriodName], [t2].[PeriodDateFrom], [t4].[StoreId], [t4].[StoreName] FROM [Entry] AS [t0] INNER JOIN [Invoice] AS [t1] ON [t0].[EntryInvoiceId] = [t1].[InvoiceId] INNER JOIN [Period] AS [t2] ON [t2].[PeriodId] = [t1].[InvoicePeriodId] LEFT OUTER JOIN ( SELECT 1 AS [test], [t3].[StoreId], [t3].[StoreName] FROM [Store] AS [t3] ) AS [t4] ON [t4].[StoreId] = ([t0].[EntryStoreId]) WHERE (([t1].[InvoiceCustomerId]) = @p0) ORDER BY [t0].[InvoicePrice] DESC -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [186] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1 The question is why there are two queries and how can I fetch LINQ objects without such hacks?

    Read the article

  • Left outer join null using VB.NET and LINQ

    - by jvcoach23
    I've got what I think is a working left outer join LINQ query, but I'm having problems with the select because of null values in the right hand side of the join. Here is what I have so far Dim Os = From e In oExcel Group Join c In oClassIndexS On c.tClassCode Equals Mid(e.ClassCode, 1, 4) Into right1 = Group _ From c In right1.DefaultIfEmpty I want to return all of e and one column from c called tClassCode. I was wondering what the syntax would be. As you can see, I'm using VB.NET. Update... Here is the query doing join where I get the error: _message = "Object reference not set to an instance of an object." Dim Os = From e In oExcel Group Join c In oClassIndexS On c.tClassCode Equals Mid(e.ClassCode, 1, 4) Into right1 = Group _ From c In right1.DefaultIfEmpty Select e, c.tClassCode If I remove the c.tClassCode from the select, the query runs without error. So I thought perhaps I needed to do a select new, but I don't think I was doing that correctly either.

    Read the article

  • Comparing utf-8 strings in java

    - by cppdev
    Hi, In my java program, I am retrieving some data from xml. This xml has few international characters and is encoded in utf8. Now I read this xml using xml parser. Once I retrieve a particular international string from xml parser, I need to compare it with set of predefined strings. Problem is when i use string.equals on internatinal string comparison fails. How to compare strings with internatinal strins in java ? Here's the line that compares strings string country; if(country.equals("Côte d'Ivoire")) { }

    Read the article

  • MySQL join problem

    - by David
    Table1 has u_name, Table2 has u_name, u_type and u_admin Table1.u_name is unique. But neither of the 3 fields in Table2 is unique. For any value of Table1.u_name, there are 0 to many entries in Table2 that Table2.u_name equals to that value. For any value of Table1.u_name, there are 0 to 1 entries in Table2 that Table2.u_name equals to that value AND Table2.u_type='S' What I want: Use Table1.u_name to get Table1.*, Table2.u_admin where Table1.u_name=Tabl2.u_name and Table2.u_type='S'. If there is no such entry in Table2 we still need to get Table1.* Please help give me some hints. Thank you so much!

    Read the article

  • Linq-to-Sql query advice please

    - by Mantorok
    Hi all Just wondering if this is a good approach, I need to search for items containing all of the specified keywords in a space-delimted string, is this the right approach this? var result = (from row in DataContext.PublishedEvents join link in DataContext.PublishedEvent_EventDateTimes on row.guid equals link.container join time in DataContext.EventDateTimes on link.item equals time.guid orderby row.EventName select new {row, time}); // Split the keyword(s) to limit results with all of those words in. foreach(var keyword in request.Title.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { var val = keyword; result = result.Where(row=>row.row.EventName.Contains(val)); } var end = result.Select(row=>new EventDetails { Title = row.row.EventName, Description = TrimDescription(row.row.Description), StartDate = row.time.StartDate, EndDate = row.time.EndDate, Url = string.Format(ConfigurationManager.AppSettings["EventUrl"], row.row.guid) }); response.Total = end.Count(); response.Result = end.ToArray(); Is there a slick Linq-way of doing all of this in one query? Thanks

    Read the article

  • phing nested if conditions

    - by Matt1776
    Hello - I am having trouble understanding the Phing documentation regarding multiple conditions for a given tag. It implies you cannot have multiple conditions unless you use the tag, but there are no examples of how to use it. Consequently I nested two tags, however I feel silly doing this when I know there is a better way. Does anyone know how I can use the tag to accomplish the following: <if><equals arg1="${deployment.host.type}" arg2="unrestricted" /><then> <if><equals arg1="${db.adapter}" arg2="PDO_MYSQL"/><then> <!-- Code Here --> </then></if> </then></if>

    Read the article

  • Java FileFilter

    - by Mr CooL
    public class DocFilter extends FileFilter { public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = Utils.getExtension(f); if (extension != null) { if (extension.equals(Utils.doc) || extension.equals(Utils.docx) ) { return true; } else { return false; } } return false; } //The description of this filter public String getDescription() { return "Just Document Files"; } } Netbeans compiler warned with the error, "No interface expected here" for above code Anyone has idea what was the problem?? I tried changing the 'extends' to 'implements', however, it didn't seem to work that way. and when I changed to implements, the following code cannot work, chooser.addChoosableFileFilter(new DocFilter()); and with this error, "method addChoosableFileFilter in class javax.swing.JFileChooser cannot be applied to given types required: javax.swing.filechooser.FileFilter" Can anyone help on this? Thanks..

    Read the article

  • Mock Object and Interface

    - by tunl
    I'm a newbie in Unit Test with Mock Object. I use EasyMock. I try to understand this example: import java.io.IOException; public interface ExchangeRate { double getRate(String inputCurrency, String outputCurrency) throws IOException; } import java.io.IOException; public class Currency { private String units; private long amount; private int cents; public Currency(double amount, String code) { this.units = code; setAmount(amount); } private void setAmount(double amount) { this.amount = new Double(amount).longValue(); this.cents = (int) ((amount * 100.0) % 100); } public Currency toEuros(ExchangeRate converter) { if ("EUR".equals(units)) return this; else { double input = amount + cents/100.0; double rate; try { rate = converter.getRate(units, "EUR"); double output = input * rate; return new Currency(output, "EUR"); } catch (IOException ex) { return null; } } } public boolean equals(Object o) { if (o instanceof Currency) { Currency other = (Currency) o; return this.units.equals(other.units) && this.amount == other.amount && this.cents == other.cents; } return false; } public String toString() { return amount + "." + Math.abs(cents) + " " + units; } } import junit.framework.TestCase; import org.easymock.EasyMock; import java.io.IOException; public class CurrencyTest extends TestCase { public void testToEuros() throws IOException { Currency testObject = new Currency(2.50, "USD"); Currency expected = new Currency(3.75, "EUR"); ExchangeRate mock = EasyMock.createMock(ExchangeRate.class); EasyMock.expect(mock.getRate("USD", "EUR")).andReturn(1.5); EasyMock.replay(mock); Currency actual = testObject.toEuros(mock); assertEquals(expected, actual); } } So, i wonder how to Currency use ExchangeRate in toEuros(..) method. rate = converter.getRate(units, "EUR"); The behavior of getRate(..) method is not specified because ExchangeRate is an interface.

    Read the article

  • Formatting a query to enumerate through 2 different datatables

    - by boiler1974
    I have 2 datatables sendTable and recvTable They both have identical column names and numbers of columns "NODE" "DSP Name" "BUS" "IDENT" "STATION" "REF1" "REF2" "REF3" "REF4" "REF5" "REF6" "REF7" "REF8" I need to compare these 2 tables and separate out the mismatches I only need to check Columns 3-11 and Ignore col 1 and 2 I tried at first removing the 2 columns and then loop thru row by row and return matches and mismatches but the problem with this approach is that I no longer have the "NODE" and "DSP Name" associated with the row when I finalize my results So I need help with a query Here is my attempt var samerecordQuery = from r1 in sendTable.AsEnumerable() where r1.Field<int>("BUS").Equals(from r2 in recvTable.AsEnumerable() where r2.Field<int>("BUS")) this obviously doesn't work so how do I format the query to say from r1 cols[3-11] equals r2 cols [3-11] and once I have this I can use the except to pull out the mismatches

    Read the article

  • What is difference between Where and Join in linq ?

    - by Freshblood
    hello What is difference between of these 2 queries ? they are completely equal ? from order in myDB.OrdersSet from person in myDB.PersonSet from product in myDB.ProductSet where order.Persons_Id==person.Id && order.Products_Id==product.Id select new { order.Id, person.Name, person.SurName, product.Model,UrunAdi=product.Name }; and from order in myDB.OrdersSet join person in myDB.PersonSet on order.Persons_Id equals person.Id join product in myDB.ProductSet on order.Products_Id equals product.Id select new { order.Id, person.Name, person.SurName, product.Model,UrunAdi=product.Name };

    Read the article

  • Java Socket Connection is flooding network OR resulting in high ping

    - by user1461100
    i have a little problem with my java socket code. I'm writing an android client application which is sending data to a java multithreaded socket server on my pc through direct(!) wireless connection. It works fine but i want to improve it for mobile applications as it is very power consuming by now. When i remove two special lines in my code, the cpu usage of my mobile device (htc one x) is totally okay but then my connection seems to have high ping rates or something like that... Here is a server code snippet where i receive the clients data: while(true) { try { .... Object obj = in.readObject(); if(obj != null) { Class clazz = obj.getClass(); String className = clazz.getName(); if(className.equals("java.lang.String")) { String cmd = (String)obj; if(cmd.equals("dc")) { System.out.println("Client "+id+" disconnected!"); Server.connectedClients[id-1] = false; break; } if(cmd.substring(0,1).equals("!")) { robot.keyRelease(PlayerEnum.getKey(cmd,id)); } else { robot.keyPress(PlayerEnum.getKey(cmd,id)); } } } } catch .... Heres the client part, where i send my data in a while loop: private void networking() { try { if(client != null) { .... out.writeObject(sendQueue.poll()); .... } } catch .... when i write it this why, i send data everytime the while loop gets executed.. when sendQueue is empty, a null "Object" will be send. this results in "high" network traffic and in "high" cpu usage. BUT: all send comments are received nearly immediately. when i change the code to following: while(true) ... if(sendQueue.peek() != null) { out.writeObject(sendQueue.poll()); } ... the cpu usage is totally okay but i'm getting some laggs.. the commands do not arrive fast enough.. as i said, it works fine (besides cpu usage) if i'm sending data(with that null objects) every while execution. but i'm sure that this is very rough coding style because i'm kind of flooding the network. any hints? what am i doing wrong?? Thanks for your Help! Sincerly yours, maaft

    Read the article

  • c# event fires windows form incorrectly

    - by MikeW
    I'm trying to understand what's happening here. I have a CheckedListBox which contains some ticked and some un-ticked items. I'm trying to find a way of determining the delta in the selection of controls. I've tried some cumbersome like this - but only works part of the time, I'm sure there's a more elegant solution. A maybe related problem is the myCheckBox_ItemCheck event fires on form load - before I have a chance to perform an ItemCheck. Here's what I have so far: void clbProgs_ItemCheck(object sender, ItemCheckEventArgs e) { // i know its awful System.Windows.Forms.CheckedListBox cb = (System.Windows.Forms.CheckedListBox)sender; string sCurrent = e.CurrentValue.ToString(); int sIndex = e.Index; AbstractLink lk = (AbstractLink)cb.Items[sIndex]; List<ILink> _links = clbProgs.DataSource as List<ILink>; foreach (AbstractLink lkCurrent in _links) { if (!lkCurrent.IsActive) { if (!_groupValues.ContainsKey(lkCurrent.Linkid)) { _groupValues.Add(lkCurrent.Linkid, lkCurrent); } } } if (_groupValues.ContainsKey(lk.Linkid)) { AbstractLink lkDirty = (AbstractLink)lk.Clone(); CheckState newValue = (CheckState)e.NewValue; if (newValue == CheckState.Checked) { lkDirty.IsActive = true; } else if (newValue == CheckState.Unchecked) { lkDirty.IsActive = false; } if (_dirtyGroups.ContainsKey(lk.Linkid)) { _dirtyGroups[lk.Linkid] = lkDirty; } else { CheckState oldValue = (CheckState)e.NewValue; if (oldValue == CheckState.Checked) { lkDirty.IsActive = true; } else if (oldValue == CheckState.Unchecked) { lkDirty.IsActive = false; } _dirtyGroups.Add(lk.Linkid, lk); } } else { if (!lk.IsActive) { _dirtyGroups.Add(lk.Linkid, lk); } else { _groupValues.Add(lk.Linkid, lk); } } } Then onclick of a save button - I check whats changed before sending to database: private void btSave_Click(object sender, EventArgs e) { List<AbstractLink> originalList = new List<AbstractLink>(_groupValues.Values); List<AbstractLink> changedList = new List<AbstractLink>(_dirtyGroups.Values); IEnumerable<AbstractLink> dupes = originalList.ToArray<AbstractLink>().Intersect(changedList.ToArray<AbstractLink>()); foreach (ILink t in dupes) { MessageBox.Show("Changed"); } if (dupes.Count() == 0) { MessageBox.Show("No Change"); } } For further info. The definition of type AbstractLink uses: public bool Equals(ILink other) { if (Object.ReferenceEquals(other, null)) return false; if (Object.ReferenceEquals(this, other)) return true; return IsActive.Equals(other.IsActive) && Linkid.Equals(other.Linkid); }

    Read the article

  • Properties are making trouble

    - by DhavalR
    In my application I have added a Properties.cs file which contains properties that I am would use through out the application. I am getting NullReferenceException = Object reference not set to an instance of an object. Here is the code for Properties.cs public class Properties { private static string type1; public static string Type1 { get { return type1; } set { type1= value; } } } And when I access this property in one of my form I am getting error. e.g. if (Properties.Type1.Equals(string.Empty) || Properties.Type1.Equals(null)) { //// Do something }

    Read the article

  • Call Method from LinQ query.

    - by Jitendra Jadav
    Hello Everybody, I am using Linq query and call method Like.. oPwd = objDecryptor.DecryptIt((c.Password.ToString()) it will return null value. Means this will not working. how I Resolve this. Thanks.. var q = from s in db.User join c in db.EmailAccount on s.UserId equals c.UserId join d in db.POPSettings on c.PopSettingId equals d.POPSettingsId where s.UserId == UserId && c.EmailId == EmailId select new { oUserId = s.UserId, oUserName = s.Name, oEmailId = c.EmailId, oEmailAccId = c.EmailAccId, oPwd = objDecryptor.DecryptIt(c.Password.ToString()), oServerName = d.ServerName, oServerAdd = d.ServerAddress, oPOPSettingId = d.POPSettingsId, };

    Read the article

  • help with reflections and annotations in java

    - by Yonatan
    Hello Internet ! I'm having trouble with doubling up on my code for no reason other than my own lack of ability to do it more efficiently... `for (Method curr: all){ if (curr.isAnnotationPresent(anno)){ if (anno == Pre.class){ for (String str : curr.getAnnotation(Pre.class).value()){ if (str.equals(method.getName()) && curr.getReturnType() == boolean.class && curr.getParameterTypes().length == 0){ toRun.add(curr); } } } if (anno == Post.class) { for (String str : curr.getAnnotation(Post.class).value()){ if (str.equals(method.getName()) && curr.getReturnType() == boolean.class && curr.getParameterTypes().length == 0){ toRun.add(curr); } } } } }` anno is a parameter - Class, and Pre and Post are my annotations, both have a value() which is an array of strings. Of course, this is all due to the fact that i let Eclipse auto fill code that i don't understand yet.

    Read the article

  • Unexpected StackOverflowError in KeyListener

    - by BillThePlatypus
    I am writing a program that can write sets of questions for review to a file for another program to read. The possible answers are typed into JTextFields at the bottom. It has code to ensure that there won't bew more than one blank JTextField at the end. When I type in answers, at varying points it will throw a StackOverflowError. The stack trace: Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) and the code: package writer; import java.awt.BorderLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import main.QuestionSet; public class SetPanel extends JPanel implements KeyListener { private QuestionSet set; private WriterPanel writer; private JPanel top=new JPanel(new BorderLayout()),controls=new JPanel(new GridLayout(1,0)),answerPanel=new JPanel(new GridLayout(0,1)); private JSplitPane split; private JTextField title=new JTextField(); private JTextArea question=new JTextArea(); private ArrayList<JTextField> answers=new ArrayList<JTextField>(); public SetPanel(QuestionSet s,WriterPanel writer) { super(new BorderLayout()); top.add(controls,BorderLayout.PAGE_START); title.setFont(title.getFont().deriveFont(40f)); title.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } @Override public void keyPressed(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } @Override public void keyReleased(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } }); title.getDocument().addDocumentListener(new DocumentListener(){ @Override public void insertUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } @Override public void removeUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } @Override public void changedUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } }); top.add(title,BorderLayout.PAGE_END); this.add(top,BorderLayout.PAGE_START); question.setLineWrap(true); question.setWrapStyleWord(true); question.setFont(question.getFont().deriveFont(20f)); question.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); }}); split=new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,new JScrollPane(question),new JScrollPane(answerPanel)); split.setDividerLocation(150); this.add(split,BorderLayout.CENTER); answers.add(new JTextField()); answerPanel.add(answers.get(0)); answers.get(0).addKeyListener(this); } private void fitTitle() { if(title==null||title.getText().equals("")) return; //title.setText(WriterPanel.convertString(title.getText())); String text=title.getText(); Insets insets=title.getInsets(); int width=title.getWidth()-insets.left-insets.right; int height=title.getHeight()-insets.top-insets.bottom; Font root=title.getFont().deriveFont((float)height); FontMetrics m=title.getFontMetrics(root); if(m.stringWidth(text)<width) { title.setFont(title.getFont().deriveFont((float)height)); return; } float delta=-100; while(Math.abs(delta)>.1f) { m=title.getFontMetrics(root); int w=m.stringWidth(text); if(w==width) break; if(Math.signum(w-width)==Math.signum(delta)||root.getSize2D()+delta<0) { delta/=-10; continue; } root=root.deriveFont(root.getSize2D()+delta); } title.setFont(root); } private void fixAnswers() { //System.out.println(answers); while(answers.get(answers.size()-1).getText().equals("")&&answers.size()>1&&answers.get(answers.size()-2).getText().equals("")) removeAnswer(answers.size()-1); if(!answers.get(answers.size()-1).getText().equals("")) { answers.add(new JTextField()); answerPanel.add(answers.get(answers.size()-1)); answers.get(answers.size()-2).removeKeyListener(this); answerPanel.revalidate(); } answers.get(answers.size()-1).addKeyListener(this); } private void removeAnswer(int i) { answers.remove(i); answerPanel.remove(i); answerPanel.revalidate(); } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub fixAnswers(); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } } Thank you in advance for any help.

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >