Search Results

Search found 6094 results on 244 pages for 'double gras'.

Page 80/244 | < Previous Page | 76 77 78 79 80 81 82 83 84 85 86 87  | Next Page >

  • MySQL - how long to create an index?

    - by user293594
    Can anyone tell me how adding a key scales in MySQL? I have 500,000,000 rows in a database, trans, with columns i (INT UNSIGNED), j (INT UNSIGNED), nu (DOUBLE), A (DOUBLE). I try to index a column, e.g. ALTER TABLE trans ADD KEY idx_A (A); and I wait. For a table of 14,000,000 rows it took about 2 minutes to execute on my MacBook Pro, but for the whole half a billion, it's taking 15hrs and counting. Am I doing something wrong, or am I just being naive about how indexing a database scales with the number of rows?

    Read the article

  • Help with complex sql query

    - by eugeneK
    To make story short, i'm building self-learning banner management system. Users will be able to insert these banners to their site when banners will be shown based on sales/impressions ratio. I have 4 tables Banners bannerID int bannerImage varchar.... SmartBanners smartBannerID int smartBannerArrayID int bannerID int impressionsCount int visibility tinyint (percents) SmartBannerArrays smartBannerArrayID int userID int Statistics bannerID int saleAmountPerDay decimal... Each night i need to generate new "visibility" for each SmartBanner based on whole SmartBannerArray that same user has. So i need to get sum of impressions and sales for each bannerID in SmartBannerArray. All comes to my mind is to use double cursor, one will loop thought SmartBannerArrays get needed values for sum of impressions and sales and then inner loop which will access each SmartBanner and change it's "visibility" percentage based on (sales/impressions)/(sumOfSales/sumOfImpressions)*100 Hope you get the picture... Is there any other way to design better tables or not to use double cursor to avoid server overload ?

    Read the article

  • How do you implement position-sensitive zooming inside a JScrollPane?

    - by tucuxi
    I am trying to implement position-sensitive zooming inside a JScrollPane. The JScrollPane contains a component with a customized 'paint' that will draw itself inside whatever space it is allocated - so zooming is as easy as using a MouseWheelListener that resizes the inner component as required. But I also want zooming into (or out of) a point to keep that point as central as possible within the resulting zoomed-in (or -out) view (this is what I refer to as 'position-sensitive' zooming), similar to how zooming works in google maps. I am sure this has been done many times before - does anybody know the "right" way to do it under Java Swing?. Would it be better to play with Graphic2D's transformations instead of using JScrollPanes? Sample code follows: package test; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; public class FPanel extends javax.swing.JPanel { private Dimension preferredSize = new Dimension(400, 400); private Rectangle2D[] rects = new Rectangle2D[50]; public static void main(String[] args) { JFrame jf = new JFrame("test"); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(400, 400); jf.add(new JScrollPane(new FPanel())); jf.setVisible(true); } public FPanel() { // generate rectangles with pseudo-random coords for (int i=0; i<rects.length; i++) { rects[i] = new Rectangle2D.Double( Math.random()*.8, Math.random()*.8, Math.random()*.2, Math.random()*.2); } // mouse listener to detect scrollwheel events addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { updatePreferredSize(e.getWheelRotation(), e.getPoint()); } }); } private void updatePreferredSize(int n, Point p) { double d = (double) n * 1.08; d = (n > 0) ? 1 / d : -d; int w = (int) (getWidth() * d); int h = (int) (getHeight() * d); preferredSize.setSize(w, h); getParent().doLayout(); // Question: how do I keep 'p' centered in the resulting view? } public Dimension getPreferredSize() { return preferredSize; } private Rectangle2D r = new Rectangle2D.Float(); public void paint(Graphics g) { super.paint(g); g.setColor(Color.red); int w = getWidth(); int h = getHeight(); for (Rectangle2D rect : rects) { r.setRect(rect.getX() * w, rect.getY() * h, rect.getWidth() * w, rect.getHeight() * h); ((Graphics2D)g).draw(r); } } }

    Read the article

  • How to combine template partial specialization and template argument deduction

    - by KKKoo0
    My understanding is that template argument deduction is only for function templates, but function templates does not allow partial specialization. Is there a way to achieve both? I basically want to achieve a function-like object (can be a functor) with the signature template<class InputIterator1, class InputIterator2, class OutputIterator, int distribution> void GetQuantity(InputIterator1 frist1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, double supply, double limit); Depending on the value of distribution, I want to have a couple of specializations of this template. And when I call this function,I basically do not want to specify all the type parameters, because they are many of them (and thus I need argument deduction)!

    Read the article

  • Any way to get TStringList.CommaText to not escape commas with quotes?

    - by Mason Wheeler
    I'm doing some work with code generation, and one of the things I need to do is create a function call where one of the parameters is a function call, like so: result := Func1(x, y, Func2(a, b, c)); TStringList.CommaText is very useful for generating the parameter lists, but when I traverse the tree to build the outer function call, what I end up with looks like this: result := Func1(x, y, "Func2(a, b, c)"); It's quoting the third argument because it contains commas, and that produced invalid code. But I can't do something simplistic like StringReplace all double quotes with empty strings, because it's quite possible that a function argument could be a string with double quotes inside. Is there any way to make it just not escape the lines that contain commas?

    Read the article

  • nhibernate fatal error

    - by Afif Lamloumi
    i have an error ( System.InvalidCastException: Unable to cast object of type 'AccountProxy' to type 'System.String'.) when i did this code i mapped the tables( Account,AccountString,EventData,...) of the the database opengts ( open source) i have this error when i called a function from EventData.cs IQuery query = session.CreateQuery("FROM Eventdata"); IList pets = query.List(); return pets; the Stack Trace: [InvalidCastException: Impossible d'effectuer un cast d'un objet de type 'AccountProxy' en type 'System.String'.] (Object , Object[] , SetterCallback ) +431 NHibernate.Bytecode.Lightweight.AccessOptimizer.SetPropertyValues(Object target, Object[] values) +20 NHibernate.Tuple.Component.PocoComponentTuplizer.SetPropertyValues(Object component, Object[] values) +49 NHibernate.Type.ComponentType.SetPropertyValues(Object component, Object[] values, EntityMode entityMode) +34 NHibernate.Type.ComponentType.ResolveIdentifier(Object value, ISessionImplementor session, Object owner) +150 NHibernate.Type.ComponentType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner) +42 NHibernate.Loader.Loader.GetKeyFromResultSet(Int32 i, IEntityPersister persister, Object id, IDataReader rs, ISessionImplementor session) +93 NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies) +92 NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +675 NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +129 NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +116 [GenericADOException: could not execute query [ select eventdata0_.deviceID as deviceID5_, eventdata0_.timestamp as timestamp5_, eventdata0_.statusCode as statusCode5_, eventdata0_.accountID as accountID5_, eventdata0_.latitude as latitude5_, eventdata0_.longitude as longitude5_, eventdata0_.gpsAge as gpsAge5_, eventdata0_.speedKPH as speedKPH5_, eventdata0_.heading as heading5_, eventdata0_.altitude as altitude5_, eventdata0_.transportID as transpo11_5_, eventdata0_.inputMask as inputMask5_, eventdata0_.outputMask as outputMask5_, eventdata0_.address as address5_, eventdata0_.DataSource as DataSource5_, eventdata0_.rawdata as rawdata5_, eventdata0_.distanceKM as distanceKM5_, eventdata0_.odometerKM as odometerKM5_, eventdata0_.geozoneIndex as geozone19_5_, eventdata0_.geozoneID as geozoneID5_, eventdata0_.creationTime as creatio21_5_ from eventdata eventdata0_ ] [SQL: select eventdata0_.deviceID as deviceID5_, eventdata0_.timestamp as timestamp5_, eventdata0_.statusCode as statusCode5_, eventdata0_.accountID as accountID5_, eventdata0_.latitude as latitude5_, eventdata0_.longitude as longitude5_, eventdata0_.gpsAge as gpsAge5_, eventdata0_.speedKPH as speedKPH5_, eventdata0_.heading as heading5_, eventdata0_.altitude as altitude5_, eventdata0_.transportID as transpo11_5_, eventdata0_.inputMask as inputMask5_, eventdata0_.outputMask as outputMask5_, eventdata0_.address as address5_, eventdata0_.DataSource as DataSource5_, eventdata0_.rawdata as rawdata5_, eventdata0_.distanceKM as distanceKM5_, eventdata0_.odometerKM as odometerKM5_, eventdata0_.geozoneIndex as geozone19_5_, eventdata0_.geozoneID as geozoneID5_, eventdata0_.creationTime as creatio21_5_ from eventdata eventdata0_]] NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +213 NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18 NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +79 NHibernate.Hql.Ast.ANTLR.Loader.QueryLoader.List(ISessionImplementor session, QueryParameters queryParameters) +51 NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters) +231 NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results) +369 NHibernate.Impl.SessionImpl.List(String query, QueryParameters queryParameters, IList results) +317 NHibernate.Impl.SessionImpl.List(String query, QueryParameters parameters) +282 NHibernate.Impl.QueryImpl.List() +163 DATA1.EventdataExtensions.GetEventdata() in C:\Users\HP\Desktop\our_project\DATA1\Queries\Eventdata.cs:33 MvcApplication7.Controllers.HistoriqueController.Index() in C:\Users\HP\Desktop\our_project\MvcApplication7\Controllers\HistoriqueController.cs:17 lambda_method(Closure , ControllerBase , Object[] ) +62 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27 System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263 System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343 System.Web.Mvc.Controller.ExecuteCore() +116 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 Any suggestions? how can correct this error Data entity class (outtake from comment): public class MyClass { public virtual string DeviceID { get; set; } public virtual int Timestamp { get; set; } public virtual string Account { get; set; } public virtual int StatusCode { get; set; } public virtual double Latitude { get; set; } public virtual double Longitude { get; set; } public virtual int GpsAge { get; set; } public virtual double SpeedKPH { get; set; } public virtual double Heading { get; set; } public override bool Equals(object obj) { return true; } public override int GetHashCode() { return 0; } }

    Read the article

  • Declarative JDOQL vs Single-String JDOQL : performance

    - by DrDro
    When querying with JDOQL is there a performance difference between using the declarative version and the Single-String version: Example from the JDOQL doc: //Declarative JDOQL : Query q = pm.newQuery(org.jpox.Person.class, "lastName == \"Jones\" && age < age_limit"); q.declareParameters("double age_limit"); List results = (List)q.execute(20.0); //Single-String JDOQL : Query q = pm.newQuery("SELECT FROM org.jpox.Person WHERE lastName == \"Jones\"" + " && age < :age_limit PARAMETERS double age_limit"); List results = (List)q.execute(20.0); Other then performance, are there any reasons for which one is better to use then the other or is it just about the one with which we feel more comfortable.

    Read the article

  • Java Regex for matching quoted string with escaped quotes

    - by kayahr
    I know there are already many questions like mine but I found no answer which works in Java. So I write a new question. I have text files with content like this: key1 = "This is a \"test\" text with escapes using '\\' characters"; key2 = 'It must work with \'single\' quotes and "double" quotes'; I need a regular expression which matches the values in the double-quotes (or single-quotes). This regular expression must support the escaped quotes and escaped backslashes. The regular expression must work with Java standard Pattern/Matcher classes.

    Read the article

  • quantity of measurable units design pattern

    - by Berryl
    Hello I am thinking through a nice pattern to be useful across domains of measurable units (ie, Length, Time) and came up with the following use case and initial classes, and of course, questions! 1) Does a Composite pattern help or complicate? 2) Should the Convert method(s) in the ComposityNode be a separate converter class? All comments appreciated. Cheers, Berryl Example Use Case: var inch = new ConvertableUnit("inch", 1) var foot = new ConvertableUnit("foot", 12) var imperialUnits = new CompositeConvertableUnit("imperial units", .024) imperialUnits.AddChild(inch) imperialUnits.AddChild(foot) var meter = new ConvertableUnit("meter", 1) var millimeter = new ConvertableUnit("millimeter ", .001) var imperialUnits = new CompositeConvertableUnit("metric units", 1) imperialUnits.AddChild(meter) imperialUnits.AddChild(millimeter) var oneInch = new Quantity(1, inch); var oneFoot = new Quantity(1, foot); oneFoot.ToBase() // "12 inches" var oneMeter = new Quantity(1, meter); oneInch.ToBase() // .024 meters Possible Solution ConvertableUnit : Node double Rate string Name Quantity ConvertableUnit Unit double Amount CompositeConvertableUnit : Node ISet<ConvertableUnit> _children ConvertableUnit BaseUnit {get{ return _children.Where(c=>c.Rate == 1).First() } } Quantity ConvertTo(Quantity from, Quantity to) Quantity ToBase(Quantity from);

    Read the article

  • What can be done to speed up synchronous WCF calls?

    - by Dimitri C.
    My performance measurements of synchronous WCF calls from within a Silverlight application showed I can make 7 calls/s on a localhost connection, which is very slow. Can this be speeded up, or is this normal? This is my test code: const UInt32 nrCalls = 100; ICalculator calculator = new CalculatorClient(); // took over from the MSDN calculator example for (double i = 0; i < nrCalls; ++i) { var call = calculator.BeginSubtract(i + 1, 1, null, null); call.AsyncWaitHandle.WaitOne(); double result = calculator.EndSubtract(call); } Remarks: CPU load is almost 0%. Apparently, the WCF module is waiting for something. I tested this both on Firefox 3.6 and Internet Explorer 7. I'm using Silverlight v3.0

    Read the article

  • Argument passing regarding ivars

    - by StoneBreaker
    I am passing an iVar into a function. The iVar is a double. The value of the iVar inside the function is correct, but the value of the iVar outside the function is not changed. This must have something to do with the way that I am receiving the iVar into the function. How do I pass a double iVar in so that its value is changed in the object and not only in the function? I do the same thing with pointers and the results are as expected, so I think I am not understanding scalar argument passing in c/objective-c.

    Read the article

  • Is there any reason to throw a DivideByZeroException?

    - by Atomiton
    Are there any cases when it's a good idea to throw errors that can be avoided? I'm thinking specifically of the DivideByZeroException and NullReferenceException For example: double numerator = 10; double denominator = getDenominatorFromUser(); if( denominator == 0 ){ throw new DivideByZeroException("You can't divide by Zero!"); } Are there any reasons for throwing an error like this? NOTE: I'm not talking about catching these errors, but specifically in knowing if there are ever good reasons for throwing them.

    Read the article

  • MPI and C structs

    - by hanno
    I have to admit, I was quite shocked to see how many lines of code are required to transfer one C struct with MPI. Under what circumstances will it work to simply transmit a struct using the predefined dataype MPI_CHAR? Consider the following example: struct particle { double x; double y; long i; }; struct particle p; MPI_Isend(&p, sizeof(particle), MPI_CHAR, tag, MPI_COMM_WORLD, &sendr); In my case, all processes run on the same architecture. Is padding the only issue?

    Read the article

  • Arraylist is null; I cannot access books in the arraylist

    - by user3701380
    I am a beginner-intermediate java programmer and I am getting a null pointer exception from my arraylist. I am writing a bookstore program for APCS and when i add the book, it is supposed to add to the arraylist in the inventory class. But when i call a method to search for a book (e.g. by title), it shows that there isn't anything in the arraylist. //Here is my inventory class -- it has all methods for adding the book or searching for one The searching methods are in getBookByTitle, getBookByAuthor, and getBookByISBN and the method for adding a book is addBook package webbazonab; //Inventory Class //Bharath Senthil //Ansh Sikka import java.util.ArrayList; public class Inventory{ private ArrayList<Book> allBooks = new ArrayList<Book>(); private String bookTitles; private String bookAuthors; private String bookPrices; private String bookCopies; private String ISBNs; public Inventory() { } //@param double price, int copies, String bookTitle, String Author, String isbnNumber public void addBooks(Book addedBook){ allBooks.add(addedBook); } public boolean isAvailable(){ for(Book myBook : allBooks){ if(myBook.copiesLeft() == 0) return false; } return true; } public String populateTitle(){ for (Book titleBooks : allBooks){ bookTitles = titleBooks.getTitle() + "\n"; return bookTitles; } return bookTitles; } public String populateAuthor(){ for(Book authorBooks : allBooks){ bookAuthors = authorBooks.getAuthor() + "\n"; return bookAuthors; } return bookAuthors; } public String populatePrice(){ for (Book pricedBooks : allBooks){ bookPrices = String.valueOf(pricedBooks.getPrice()) + "\n"; } return "$" + bookPrices; } /** * * @return */ public String populateCopies(){ for (Book amtBooks : allBooks){ bookCopies = String.valueOf(amtBooks.copiesLeft()) + "\n"; return bookCopies; } return bookCopies; } public String populateISBN(){ for (Book isbnNums : allBooks){ ISBNs = isbnNums.getIsbn() + "\n"; return ISBNs; } return ISBNs; } @SuppressWarnings("empty-statement") public Book getBookByTitle(String titleSearch) { for(Book titleBook : allBooks) { if (titleBook.getTitle().equals(titleSearch)) { return titleBook; } } return null; } public Book getBookByISBN(String isbnSearch){ for(Book isbnBookSearches : allBooks){ if(isbnBookSearches.getIsbn().equals(isbnSearch)){ return isbnBookSearches; } } return null; } public Book getBookByAuthor(String authorSearch){ for(Book authorBookSearches : allBooks){ if(authorBookSearches.getAuthor().equals(authorSearch)){ return authorBookSearches; } } return null; } public void sort(){ for(int i = 0; i < allBooks.size(); i++) { for(int k = 0; k < allBooks.size(); k++) { if(((Book) allBooks.get(i)).getIsbn().compareTo(((Book) allBooks.get(k)).getIsbn()) < 1) { Book temp = (Book) allBooks.get(k); allBooks.set(k, allBooks.get(i)); allBooks.set(i, temp); } else if(((Book) allBooks.get(i)).getIsbn().compareTo(((Book) allBooks.get(k)).getIsbn()) > 1) { Book temp = (Book) allBooks.get(i); allBooks.set(i, allBooks.get(k)); allBooks.set(k, temp); } } } } public ArrayList<Book> getBooks(){ return allBooks; } } //The exception occurs when i call the method here (in another class): Inventory lib = new Inventory(); jTextField12.setText(lib.getBookByAuthor(authorSearch).getTitle()); Here is my book class if you need it package webbazonab; //Webbazon AB //Project By: Ansh Sikka and Bharath Senthil public class Book { private double myPrice; private String myTitle; private String bookAuthor; private String isbn; private int myCopies; public Book(double price, int copies, String bookTitle, String Author, String isbnNumber) { myPrice = price; myCopies = copies; myTitle = bookTitle; bookAuthor = Author; isbn = isbnNumber; } public double getPrice() { return myPrice; } public String getIsbn() { return isbn; } public String getTitle() { return myTitle; } public String getAuthor() { return bookAuthor; } public int copiesLeft(){ return myCopies; } public String notFound(){ return "The book you searched for could not be found!"; } public String toString() { return "Title: " + getTitle() + "\nAuthor: " + getAuthor() + "\nNumber of Available Books: " + copiesLeft() + "\nPrice: $" + getPrice(); } } Thanks!

    Read the article

  • Can you use back references in the pattern part of a regular expression?

    - by Camsoft
    I there a way to back reference in the regular expression pattern? Example input string: Here is "quoted text" some quoted text. Say I want to pull out the quoted text, I could create the following expression: "([^"]+)" This regular expression would match quoted text. Say I want it to also support single quotes, I could change the expression to: ["']([^"']+)["'] But what if the input string has a mixture of quotes say Here is 'quoted text" some quoted text. I would not want the regex to match. Currently the regex in the second example would still match. What I would like to be able to do is if the first quote is a double quote then the closing quote must be a double. And if the start quote is single quote then the closing quote must be single. Can I use a back reference to achieve this?

    Read the article

  • Design advice for avoiding change in several classes

    - by Anders Svensson
    Hi, I'm trying to figure out how to design a small application more elegantly, and make it more resistant to change. Basically it is a sort of project price calculator, and the problem is that there are many parameters that can affect the pricing. I'm trying to avoid cluttering the code with a lot of if-clauses for each parameter, but still I have e.g. if-clauses in two places checking for the value of the size parameter. I have the Head First Design Patterns book, and have tried to find ideas there, but the closest I got was the decorator pattern, which has an example where starbuzz coffee sets prices depending first on condiments added, and then later in an exercise by adding a size parameter (Tall, Grande, Venti). But that didn't seem to help, because adding that parameter still seemed to add if-clause complexity in a lot of places (and this being an exercise they didn't explain that further). What I am trying to avoid is having to change several classes if a parameter were to change or a new parameter added, or at least change in as few places as possible (there's some fancy design principle word for this that I don't rememeber :-)). Here below is the code. Basically it calculates the price for a project that has the tasks "Writing" and "Analysis" with a size parameter and different pricing models. There will be other parameters coming in later too, like "How new is the product?" (New, 1-5 years old, 6-10 years old), etc. Any advice on the best design would be greatly appreciated, whether a "design pattern" or just good object oriented principles that would make it resistant to change (e.g. adding another size, or changing one of the size values, and only have to change in one place rather than in several if-clauses): public class Project { private readonly int _numberOfProducts; protected Size _size; public Task Analysis { get; set; } public Task Writing { get; set; } public Project(int numberOfProducts) { _numberOfProducts = numberOfProducts; _size = GetSize(); Analysis = new AnalysisTask(numberOfProducts, _size); Writing = new WritingTask(numberOfProducts, _size); } private Size GetSize() { if (_numberOfProducts <= 2) return Size.small; if (_numberOfProducts <= 8) return Size.medium; return Size.large; } public double GetPrice() { return Analysis.GetPrice() + Writing.GetPrice(); } } public abstract class Task { protected readonly int _numberOfProducts; protected Size _size; protected double _pricePerHour; protected Dictionary<Size, int> _hours; public abstract int TotalHours { get; } public double Price { get; set; } protected Task(int numberOfProducts, Size size) { _numberOfProducts = numberOfProducts; _size = size; } public double GetPrice() { return _pricePerHour * TotalHours; } } public class AnalysisTask : Task { public AnalysisTask(int numberOfProducts, Size size) : base(numberOfProducts, size) { _pricePerHour = 850; _hours = new Dictionary<Size, int>() { { Size.small, 56 }, { Size.medium, 104 }, { Size.large, 200 } }; } public override int TotalHours { get { return _hours[_size]; } } } public class WritingTask : Task { public WritingTask(int numberOfProducts, Size size) : base(numberOfProducts, size) { _pricePerHour = 650; _hours = new Dictionary<Size, int>() { { Size.small, 125 }, { Size.medium, 100 }, { Size.large, 60 } }; } public override int TotalHours { get { if (_size == Size.small) return _hours[_size] * _numberOfProducts; if (_size == Size.medium) return (_hours[Size.small] * 2) + (_hours[Size.medium] * (_numberOfProducts - 2)); return (_hours[Size.small] * 2) + (_hours[Size.medium] * (8 - 2)) + (_hours[Size.large] * (_numberOfProducts - 8)); } } } public enum Size { small, medium, large } public partial class Form1 : Form { public Form1() { InitializeComponent(); List<int> quantities = new List<int>(); for (int i = 0; i < 100; i++) { quantities.Add(i); } comboBoxNumberOfProducts.DataSource = quantities; } private void comboBoxNumberOfProducts_SelectedIndexChanged(object sender, EventArgs e) { Project project = new Project((int)comboBoxNumberOfProducts.SelectedItem); labelPrice.Text = project.GetPrice().ToString(); labelWriterHours.Text = project.Writing.TotalHours.ToString(); labelAnalysisHours.Text = project.Analysis.TotalHours.ToString(); } } At the end is a simple current calling code in the change event for a combobox that set size... (BTW, I don't like the fact that I have to use several dots to get to the TotalHours at the end here either, as far as I can recall, that violates the "principle of least knowledge" or "the law of demeter", so input on that would be appreciated too, but it's not the main point of the question) Regards, Anders

    Read the article

  • Pointers to Derived Class Objects Losing vfptr

    - by duckworthd
    To begin, I am trying to write a run-of-the-mill, simple Ray Tracer. In my Ray Tracer, I have multiple types of geometries in the world, all derived from a base class called "SceneObject". I've included the header for it here. /** Interface for all objects that will appear in a scene */ class SceneObject { public: mat4 M, M_inv; Color c; SceneObject(); ~SceneObject(); /** The transformation matrix to be applied to all points of this object. Identity leaves the object in world frame. */ void setMatrix(mat4 M); void setMatrix(MatrixStack mStack); void getMatrix(mat4& M); /** The color of the object */ void setColor(Color c); void getColor(Color& c); /** Alter one portion of the color, leaving the rest as they were. */ void setDiffuse(vec3 rgb); void setSpecular(vec3 rgb); void setEmission(vec3 rgb); void setAmbient(vec3 rgb); void setShininess(double s); /** Fills 'inter' with information regarding an intersection between this object and 'ray'. Ray should be in world frame. */ virtual void intersect(Intersection& inter, Ray ray) = 0; /** Returns a copy of this SceneObject */ virtual SceneObject* clone() = 0; /** Print information regarding this SceneObject for debugging */ virtual void print() = 0; }; As you can see, I've included a couple virtual functions to be implemented elsewhere. In this case, I have only two derived class -- Sphere and Triangle, both of which implement the missing member functions. Finally, I have a Parser class, which is full of static methods that do the actual "Ray Tracing" part. Here's a couple snippets for relevant portions void Parser::trace(Camera cam, Scene scene, string outputFile, int maxDepth) { int width = cam.getNumXPixels(); int height = cam.getNumYPixels(); vector<vector<vec3>> colors; colors.clear(); for (int i = 0; i< width; i++) { vector<vec3> ys; for (int j = 0; j<height; j++) { Intersection intrsct; Ray ray; cam.getRay(ray, i, j); vec3 color; printf("Obtaining color for Ray[%d,%d]\n", i,j); getColor(color, scene, ray, maxDepth); ys.push_back(color); } colors.push_back(ys); } printImage(colors, width, height, outputFile); } void Parser::getColor(vec3& color, Scene scene, Ray ray, int numBounces) { Intersection inter; scene.intersect(inter,ray); if(inter.isIntersecting()){ Color c; inter.getColor(c); c.getAmbient(color); } else { color = vec3(0,0,0); } } Right now, I've forgone the true Ray Tracing part and instead simply return the color of the first object hit, if any. As you have no doubt noticed, the only way the computer knows that a ray has intersected an object is through Scene.intersect(), which I also include. void Scene::intersect(Intersection& i, Ray r) { Intersection result; result.setDistance(numeric_limits<double>::infinity()); result.setIsIntersecting(false); double oldDist; result.getDistance(oldDist); /* Cycle through all objects, making result the closest one */ for(int ind=0; ind<objects.size(); ind++){ SceneObject* thisObj = objects[ind]; Intersection betterIntersect; thisObj->intersect(betterIntersect, r); double newDist; betterIntersect.getDistance(newDist); if (newDist < oldDist){ result = betterIntersect; oldDist = newDist; } } i = result; } Alright, now for the problem. I begin by creating a scene and filling it with objects outside of the Parser::trace() method. Now for some odd reason, I cast Ray for i=j=0 and everything works wonderfully. However, by the time the second ray is cast all of the objects stored in my Scene no longer recognize their vfptr's! I stepped through the code with a debugger and found that the information to all the vfptr's are lost somewhere between the end of getColor() and the continuation of the loop. However, if I change the arguments of getColor() to use a Scene& instead of a Scene, then no loss occurs. What crazy voodoo is this?

    Read the article

  • How to generate GIR files from the Vala compiler?

    - by celil
    I am trying to create python bindings to a vala library using pygi with gobject introspection. However, I am having trouble generating the GIR files (that I am planning to compile to typelib files subsequently). According to the documentation valac should support generating GIR files. Compiling the following helloworld.vala public struct Point { public double x; public double y; } public class Person { public int age = 32; public Person(int age) { this.age = age; } } public int main() { var p = Point() { x=0.0, y=0.1 }; stdout.printf("%f %f\n", p.x, p.y); var per = new Person(22); stdout.printf("%d\n", per.age); return 0; } with the command valac helloworld.vala --gir=Hello-1.0.gir doesn't create the Hello-1.0.gir file as one would expect. How can I generate the gir file?

    Read the article

  • Accelerometer Values from Android/iPhone device

    - by mrlinx
    I'm trying to map my movements with a android device into an OpenGL scene. I've recorded accelerometer values for a simples movement: Moving the phone (lies flat on a table) 10cm forward (+x), and then 10cm backward (-x). The problem is that this values when used to calculate velocity and position, makes only the opengl cube go forward. Seems like the negative acceleration recorded was not enough to reduce the speed and invert its movement. What can be the problem? This is my function that updates the velocity and position every time new data comes in: void updatePosition(double T2) { double T = 0.005; Vec3 old_pos = position.clone(), old_vel = velocity.clone(); velocity = old_vel.plus(acceleration.times(T)); position = old_pos.plus(old_vel.times(T).plus(acceleration.times(0.5 * Math.pow(T, 2)))); } This is the X,Y,Z accelerometer values over the entire captured time:

    Read the article

  • Regex pattern for searches with include and exclude

    - by alex-kravchenko-zmeyp
    I am working on a Regex pattern for searches that should allow optional '+' sign to include in the search and '-' sign to exclude from the search. For example: +apple orange -peach should search for apples and oranges and not for peaches. Also the pattern should allow for phrases in double quotes mixed with single words, for example: "red apple" -"black grape" +orange - you get the idea, same as most of the internet searches. So I am running 2 regular expressions, first to pick all the negatives, which is simple because '-' is required: (?<=[\-]"?)((?<=")(?<exclude>[^"]+)|(?<exclude>[^\s,\+\-"]+)) And second to pick positives, and it is a little more complex because '+' is optional: ((?<=[\+\s]")(?<include>[^\s"\+\-][^"]+))|(?<include>(?<![\-\w]"?)([\w][^,\s\-\+]+))(?<!") Positive search is where I am having a problem, it works fine when I run it in RegexBuddy but when I try in .Net the pattern picks up second word from negative criteria, for example in -"black grape" it picks up word 'grape' even though it ends with double quote. Any suggestions?

    Read the article

  • Calling 32 bit unmanaged dlls from C# randomly failing

    - by Bert
    Hi, I'm having an issue when calling 32 bit delphi dll's from c# web site. The code generally runs fine, but occasionally I get an error Unable to load DLL '': The specified module could not be found. (Exception from HRESULT: 0x8007007E). This issue persists until I recycle the app pool for the site, and then it works fine again. On the same server, there is also a web service that is calling the same set of dlls. This web service doesn't seem to have the same issue that the web site has. Both applications are using .net framework 3.5, separate app pools on IIS. Here is the code I'm using to wrap the dlls: public sealed class Mapper { static Mapper instance = null; [DllImport("kernel32.dll")] private static extern bool SetDllDirectory(string lpPathName); private Mapper() { SetDllDirectory(ConfigManager.Path); } public static Mapper Instance { get { if (instance == null) { instance = new Mapper(); } return instance; } } public int Foo(string bar, ref double val) { return Loader.Foo(bar, ref val); } } public static class Loader { [DllImport("some.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, EntryPoint = "foo")] public static extern int Foo(string bar, ref double val); } Then I call it like this: double val = 0.0; Mapper.Instance.Foo("bar", ref val); Any ideas as to why it would "randomly" Unable to load DLL '': The specified module could not be found. (Exception from HRESULT: 0x8007007E). The other problem is that I haven't been able to replicate the issue in the development environment. I thought that due to 2 applications calling the same dlls, that there could be some locks occurring. To replicate this, I created an app that spawned multiple threads and repeatedly called the 32bit dlls, and then used the web site to call these same dlls. I still couldn't replicate the issue. Some possible fixes that I can think of: Wrap the 32 bit dlls in web service (because the webservice doesn't seem to suffer from the same problem). But this may be worthless if it turns out that the web service also fails. Set up state server for the session state and periodically recycle the app pool for the site.This isn't fixing the problem, only avoiding it. Wrap the dll's in exe, and call that exe. Then I shouldn't get the same issue. But this also seems like a hacky solution. Implement the mapper class differently ? But how else should I be doing the call? The other draw back is that other applications are using this mapper, so I'd need to change there code too. Thanks

    Read the article

  • Does DataType DataAnnotation Check the Expression?

    - by Jason
    I am currently using DataAnnotations within my ASP.NET MVC website to ensure data is properly validated. One question I wanted to verify (I think I know the answer, but I can't find verification online) - does the DataType DataAnnotation perform regular expression checks to ensure that you have received a valid e-mail/phone/currency/etc? [Required(ErrorMessage = "Price required")] [DataType(DataType.Currency, ErrorMessage = "Not a valid price")] [Range(0, double.MaxValue, ErrorMessage = "Price must be greater than 0.")] public decimal Price { get; set; } I believe the answer is no (meaning I have to provide my own, custom, RegularExpressionAttribute), but I wanted to double check before I do that for various field types.

    Read the article

  • Code crashing compiler...

    - by AndrejaKo
    Hi! I'm experimenting with a piece of C code. Can anyone tell me why is VC 9.0 with SP1 crashing for me? Oh, and the code is meant to be an example used in a discussion why something like void main (void) is evil. struct foo { int i; double d; } main (double argc, struct foo argv) { struct foo a; a.d=0; a.i=0; return a.i; } If I put return a; compiler doesn't crash.

    Read the article

  • How to get the place name by latitude and longitude using openstreetmap in android

    - by Gaurav kumar
    In my app i am using osm rather than google map.I have latitude and longitude.So from here how i will query to get the city name from osm database..please help me. final String requestString = "http://nominatim.openstreetmap.org/reverse?format=json&lat=" + Double.toString(lat) + "&lon=" + Double.toString(lon) + "&zoom=18&addressdetails=1"; RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(requestString)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { if (response.getStatusCode() == 200) { String city = ""; try { JSONValue json = JSONParser.parseStrict(response); JSONObject address = json.isObject().get("address").isObject(); final String quotes = "^\"|\"$"; if (address.get("city") != null) { city = address.get("city").toString().replaceAll(quotes, ""); } else if (address.get("village") != null) { city = address.get("village").toString().replaceAll(quotes, ""); } } catch (Exception e) { } } } }); } catch (Exception e1) { }

    Read the article

  • Android: who can help me with setting up this google maps class please??

    - by Capsud
    Hi, Firstly this has turned out to be quite a long post so please bear with me as its not too difficult but you may need to clarify something with me if i haven't explained it correctly. So with some help the other day from guys on this forum, i managed to partially set up my 'mapClass' class, but i'm having trouble with it and its not running correctly so i would like some help if possible. I will post the code below so you can see. What Ive got is a 'Dundrum' class which sets up the listView for an array of items. Then ive got a 'dundrumSelector' class which I use to set up the setOnClickListener() methods on the listItems and link them to their correct views. DundrumSelector class.. public static final int BUTTON1 = R.id.anandaAddressButton; public static final int BUTTON2 = R.id.bramblesCafeAddressButton; public static final int BUTTON3 = R.id.brannigansAddressButton; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); int position = getIntent().getExtras().getInt("position"); if(position == 0){ setContentView(R.layout.ananda); }; if(position == 1){ setContentView(R.layout.bramblescafe); }; if(position == 2){ setContentView(R.layout.brannigans); Button anandabutton = (Button) findViewById(R.id.anandaAddressButton); anandabutton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(),MapClass.class); myIntent.putExtra("button", BUTTON1); startActivityForResult(myIntent,0); } }); Button bramblesbutton = (Button) findViewById(R.id.bramblesCafeAddressButton); bramblesbutton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(),MapClass.class); myIntent.putExtra("button", BUTTON2); startActivityForResult(myIntent, 0); } }); etc etc.... Then what i did was set up static ints to represent the buttons which you can see at the top of this class, the reason for this is because in my mapClass activity I just want to have one method, because the only thing that is varying is the coordinates to each location. ie. i dont want to have 100+ map classes essentially doing the same thing other than different coordinates into the method. So my map class is as follows... case DundrumSelector.BUTTON1: handleCoordinates("53.288719","-6.241179"); break; case DundrumSelector.BUTTON2: handleCoordinates("53.288719","-6.241179"); break; case DundrumSelector.BUTTON3: handleCoordinates("53.288719","-6.241179"); break; } } private void handleCoordinates(String l, String b){ mapView = (MapView) findViewById(R.id.mapView); LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom); View zoomView = mapView.getZoomControls(); zoomLayout.addView(zoomView, new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mapView.displayZoomControls(true); mc = mapView.getController(); String coordinates[] = {l, b}; double lat = Double.parseDouble(coordinates[0]); double lng = Double.parseDouble(coordinates[1]); p = new GeoPoint( (int) (lat*1E6), (int) (lng*1E6)); mc.animateTo(p); mc.setZoom(17); mapView.invalidate(); } Now this is where my problem is. The onClick() events don't even work from the listView to get into the correct views. I have to comment out the methods in 'DundrumSelector' before I can get into their views. And this is what I dont understand, firstly why wont the onClick() events work, because its not even on that next view where the map is. I know this is a very long post and it might be quite confusing so let me know if you want any clarification.. Just to recap, what i'm trying to do is just have one class that sets up the map coordinates, like what i'm trying to do in my 'mapClass'. Please can someone help or suggest another way of doing this! Thanks alot everyone for reading this.

    Read the article

< Previous Page | 76 77 78 79 80 81 82 83 84 85 86 87  | Next Page >