Search Results

Search found 118921 results on 4757 pages for 'code first'.

Page 13/4757 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • Augmenting functionality of subclasses without code duplication in C++

    - by Rob W
    I have to add common functionality to some classes that share the same superclass, preferably without bloating the superclass. The simplified inheritance chain looks like this: Element -> HTMLElement -> HTMLAnchorElement Element -> SVGElement -> SVGAlement The default doSomething() method on Element is no-op by default, but there are some subclasses that need an actual implementation that requires some extra overridden methods and instance members. I cannot put a full implementation of doSomething() in Element because 1) it is only relevant for some of the subclasses, 2) its implementation has a performance impact and 3) it depends on a method that could be overridden by a class in the inheritance chain between the superclass and a subclass, e.g. SVGElement in my example. Especially because of the third point, I wanted to solve the problem using a template class, as follows (it is a kind of decorator for classes): struct Element { virtual void doSomething() {} }; // T should be an instance of Element template<class T> struct AugmentedElement : public T { // doSomething is expensive and uses T virtual void doSomething() override {} // Used by doSomething virtual bool shouldDoSomething() = 0; }; class SVGElement : public Element { /* ... */ }; class SVGAElement : public AugmentedElement<SVGElement> { // some non-trivial check bool shouldDoSomething() { /* ... */ return true; } }; // Similarly for HTMLAElement and others I looked around (in the existing (huge) codebase and on the internet), but didn't find any similar code snippets, let alone an evaluation of the effectiveness and pitfalls of this approach. Is my design the right way to go, or is there a better way to add common functionality to some subclasses of a given superclass?

    Read the article

  • :first-child fails when an element of a different class is dynamically inserted above

    - by koko
    So, I've encountered a situation where inserting an element of a different class/id breaks all css-rules on that :first-child. <div id="nav"> <div class="nSub">abcdef</div> <div class="nSub">abcdef</div> <div class="nSub">abcdef</div> <div class="nSub">abcdef</div> <div class="nSub">abcdef</div> </div> .nSub:first-child { margin-top:15px; -moz-border-radius-topleft:5px; /* ... */ } .nSub { background:#666; /* ... */ } .nSub:last-child { -moz-border-radius-bottomleft:5px; /* ... */ } As soon as I insert an element of another class/id above, like this: $('nav').insert({top:'<div id="newWF"></div>'}); all declarations for .nSub:first-child are being ignored in both FF 3.6 and Safari 4.

    Read the article

  • Executing logic before save or validation with EF Code-First Models

    - by Ryan Norbauer
    I'm still getting accustomed to EF Code First, having spent years working with the Ruby ORM, ActiveRecord. ActiveRecord used to have all sorts of callbacks like before_validation and before_save, where it was possible to modify the object before it would be sent off to the data layer. I am wondering if there is an equivalent technique in EF Code First object modeling. I know how to set object members at the time of instantiation, of course, (to set default values and so forth) but sometimes you need to intervene at different moments in the object lifecycle. To use a slightly contrived example, say I have a join table linking Authors and Plays, represented with a corresponding Authoring object: public class Authoring { public int ID { get; set; } [Required] public int Position { get; set; } [Required] public virtual Play Play { get; set; } [Required] public virtual Author Author { get; set; } } where Position represents a zero-indexed ordering of the Authors associated to a given Play. (You might have a single "South Pacific" Play with two authors: a "Rodgers" author with a Position 0 and a "Hammerstein" author with a Position 1.) Let's say I wanted to create a method that, before saving away an Authoring record, it checked to see if there were any existing authors for the Play to which it was associated. If no, it set the Position to 0. If yes, it would find set the Position of the highest value associated with that Play and increment by one. Where would I implement such logic within an EF code first model layer? And, in other cases, what if I wanted to massage data in code before it is checked for validation errors? Basically, I'm looking for an equivalent to the Rails lifecycle hooks mentioned above, or some way to fake it at least. :)

    Read the article

  • WSDL first for existing service layer

    - by Jurgen H
    I am working on an existing Java project with a typical services - dao setup for which only a webapplication was available. My job is to add webservices on top of the services layer, but the webservices have their own functional analysis and datamodel. The functional analyses ofcource focuses on what is possible in the different service methods. As good practice demands, we used the WSDL first strategy and generated JAXB bound Java classes and a SEI for the webservices. After having implemented the webservices partially, we noticed a 70% match between the datamodel. This resulted in writing converters which take the webservice JAXB classes and map them with the service layer classes. Customer customer = new Customer(); customer.setName(wsCustomer.getName()); customer.setFirstName(wsCustomer.getFirstName(); .. This is a very obvious example, some other mappings where little more complicated. Can anyone give his best practices, experiences, solutions to this kind of situations? Are any of these frameworks usefull? http://transmorph.sourceforge.net/wiki/index.php/Main_Page http://ezmorph.sourceforge.net/ Please don't start a discussion about WSDL first vs code first.

    Read the article

  • What is this code?

    - by Aerovistae
    This is from the Evolution of a Programmer "joke", at the "Master Programmer" level. It seems to be C++, but I don't know what all this bloated extra stuff is, nor did any Google searches turn up anything except the joke I took it from. Can anyone tell me more about what I'm reading here? [ uuid(2573F8F4-CFEE-101A-9A9F-00AA00342820) ] library LHello { // bring in the master library importlib("actimp.tlb"); importlib("actexp.tlb"); // bring in my interfaces #include "pshlo.idl" [ uuid(2573F8F5-CFEE-101A-9A9F-00AA00342820) ] cotype THello { interface IHello; interface IPersistFile; }; }; [ exe, uuid(2573F890-CFEE-101A-9A9F-00AA00342820) ] module CHelloLib { // some code related header files importheader(<windows.h>); importheader(<ole2.h>); importheader(<except.hxx>); importheader("pshlo.h"); importheader("shlo.hxx"); importheader("mycls.hxx"); // needed typelibs importlib("actimp.tlb"); importlib("actexp.tlb"); importlib("thlo.tlb"); [ uuid(2573F891-CFEE-101A-9A9F-00AA00342820), aggregatable ] coclass CHello { cotype THello; }; }; #include "ipfix.hxx" extern HANDLE hEvent; class CHello : public CHelloBase { public: IPFIX(CLSID_CHello); CHello(IUnknown *pUnk); ~CHello(); HRESULT __stdcall PrintSz(LPWSTR pwszString); private: static int cObjRef; }; #include <windows.h> #include <ole2.h> #include <stdio.h> #include <stdlib.h> #include "thlo.h" #include "pshlo.h" #include "shlo.hxx" #include "mycls.hxx" int CHello:cObjRef = 0; CHello::CHello(IUnknown *pUnk) : CHelloBase(pUnk) { cObjRef++; return; } HRESULT __stdcall CHello::PrintSz(LPWSTR pwszString) { printf("%ws\n", pwszString); return(ResultFromScode(S_OK)); } CHello::~CHello(void) { // when the object count goes to zero, stop the server cObjRef--; if( cObjRef == 0 ) PulseEvent(hEvent); return; } #include <windows.h> #include <ole2.h> #include "pshlo.h" #include "shlo.hxx" #include "mycls.hxx" HANDLE hEvent; int _cdecl main( int argc, char * argv[] ) { ULONG ulRef; DWORD dwRegistration; CHelloCF *pCF = new CHelloCF(); hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); // Initialize the OLE libraries CoInitiali, NULL); // Initialize the OLE libraries CoInitializeEx(NULL, COINIT_MULTITHREADED); CoRegisterClassObject(CLSID_CHello, pCF, CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &dwRegistration); // wait on an event to stop WaitForSingleObject(hEvent, INFINITE); // revoke and release the class object CoRevokeClassObject(dwRegistration); ulRef = pCF->Release(); // Tell OLE we are going away. CoUninitialize(); return(0); } extern CLSID CLSID_CHello; extern UUID LIBID_CHelloLib; CLSID CLSID_CHello = { /* 2573F891-CFEE-101A-9A9F-00AA00342820 */ 0x2573F891, 0xCFEE, 0x101A, { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 } }; UUID LIBID_CHelloLib = { /* 2573F890-CFEE-101A-9A9F-00AA00342820 */ 0x2573F890, 0xCFEE, 0x101A, { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 } }; #include <windows.h> #include <ole2.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "pshlo.h" #include "shlo.hxx" #include "clsid.h" int _cdecl main( int argc, char * argv[] ) { HRESULT hRslt; IHello *pHello; ULONG ulCnt; IMoniker * pmk; WCHAR wcsT[_MAX_PATH]; WCHAR wcsPath[2 * _MAX_PATH]; // get object path wcsPath[0] = '\0'; wcsT[0] = '\0'; if( argc > 1) { mbstowcs(wcsPath, argv[1], strlen(argv[1]) + 1); wcsupr(wcsPath); } else { fprintf(stderr, "Object path must be specified\n"); return(1); } // get print string if(argc > 2) mbstowcs(wcsT, argv[2], strlen(argv[2]) + 1); else wcscpy(wcsT, L"Hello World"); printf("Linking to object %ws\n", wcsPath); printf("Text String %ws\n", wcsT); // Initialize the OLE libraries hRslt = CoInitializeEx(NULL, COINIT_MULTITHREADED); if(SUCCEEDED(hRslt)) { hRslt = CreateFileMoniker(wcsPath, &pmk); if(SUCCEEDED(hRslt)) hRslt = BindMoniker(pmk, 0, IID_IHello, (void **)&pHello); if(SUCCEEDED(hRslt)) { // print a string out pHello->PrintSz(wcsT); Sleep(2000); ulCnt = pHello->Release(); } else printf("Failure to connect, status: %lx", hRslt); // Tell OLE we are going away. CoUninitialize(); } return(0); }

    Read the article

  • Exclude first child with XSL-T

    - by zneak
    Hello, What I'm trying to do is fairly simple, but I can't find the way to. I just want to iterate over the children of a node excluding the first child. For instance, in this XML snippet, I would want all the <bar> elements, except the first one: <foo> <Bar>Example</Bar> <Bar>This is an example</Bar> <Bar>Another example</Bar> <Bar>Bar</Bar> </foo> There is no common attribute by which I can filter (like an id tag or something similar). Any suggestions?

    Read the article

  • Data not displayed first time in android after copying the file from assets to data folder

    - by Thinkcomplete
    Description I have used the code tip from http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ to copy a pre-filled data file to the target and handled this in a asynch task Problem : On starting the application it gives error and shuts down first time, starting again without any change it works perfectly fine. So first time after the file is copied, the error comes but after that no issues. Please help Code attached:.. private class CopyDatabase extends AsyncTask<String, Void, Boolean> { private final ProgressDialog dialog = new ProgressDialog(BabyNames.this); protected void onPreExecute() { this.dialog.setMessage("Loading..."); this.dialog.show(); } @Override protected Boolean doInBackground(String... params) { // TODO Auto-generated method stub try { namesDBSQLHelper.createDatabase(); return null; } catch(IOException ioe){ ioe.printStackTrace(); } return null; } protected void onPostExecute(final Boolean success){ if (this.dialog.isShowing()){ this.dialog.dismiss(); } } }

    Read the article

  • touchesEnded:withEvent: from UIScrollView First Responder

    - by Matthew Mitchell
    I've made a UIScrollView the first responder. I need to maintain touch events to a touchesEnded:withEvent: method on a view behind it. I've tried using the nextResponder method and that failed. I've tried forwarding touchesEnded:withEvent to the view behind it and that fails. How do I get this to work? The UIScrollView wont work unless it is the first responder or gets events some other way. Thank you for any help. Shame Apple's documentation and APIs are terrible in areas.

    Read the article

  • Question on refactoring and code design

    - by Software Engeneering Learner
    Suppose, I have a class with a constant static final field. Then I want in certain situations that field to be different. It still can be final, because it should be initialized in constructor. My question is, what strategy I should use: add this field value into the constructor create 2 subclasses, replace original field usage with some protected method and override it in subclasses Or create some composite class that will held instance of my class inside and somehow change that value? Which approach should I use and why?

    Read the article

  • How to convince my boss that quality is a good thing to have in code?

    - by Kristof Claes
    My boss came to me today to ask me if we could implement a certain feature in 1.5 days. I had a look at it and told him that 2 to 3 days would be more realistic. He then asked me: "And what if we do it quick and dirty?" I asked him to explain what he meant with "quick and dirty". It turns out, he wants us to write code as quickly as humanly possible by (for example) copying bits and pieces from other projects, putting all code in the code-behind of the WebForms pages, stop caring about DRY and SOLID and assuming that the code and functionalities will never ever have to be modified or changed. What's even worse, he doesn't want us do it for just this one feature, but for all the code we write. We can make more profit when we do things quick and dirty. Clients don't want to pay for you taking into account that something might change in the future. The profits for us are in delivering code as quick as possible. As long as the application does what it needs to do, the quality of the code doesn't matter. They never see the code. I have tried to convince him that this is a bad way to think as the manager of a software company, but he just wouldn't listen to my arguments: Developer motivation: I explained that it is hard to keep developers motivated when they are constantly under pressure of unrealistic deadlines and budget to write sloppy code very quickly. Readability: When a project gets passed on to another developer, cleaner and better structured code will be easier to read and understand. Maintainability: It is easier, safer and less time consuming to adapt, extend or change well written code. Testability: It is usually easier to test and find bugs in clean code. My co-workers are as baffled as I am by my boss' standpoint, but we can't seem to get to him. He keeps on saying that by making things more quickly, we can sell more projects, ask a lower price for them while still making a bigger profit. And in the end these projects pay the developer's salaries. What more can I say to make him see he is wrong? I want to buy him copies of Peopleware and The Mythical Man-Month, but I have a feeling they won't change his mind either. A lot of you will probably say something like "Run! Get out of there now!" or "I'd quit!", but that's not really an option since .NET web development jobs are rather rare in the region where I live...

    Read the article

  • How to price code reviews to encourage good behavior?

    - by Chris Clark
    I work for a company that has a hosted .net internet application with many clients. Those clients often want to write customizations for our application. We have APIs to hook into the app, but the customizations themselves are written in .net. This is a shared, secure hosting environment and we have to code review these customizations before we can deploy them in our datacenter to ensure that they don't degrade performance, crash our servers, or open any security vulnerabilities. We charge for these code reviews. The current pricing model is simply a function of the number of lines of code. I think this is a bad idea for a variety of reasons, but primarily because, if we are interested in verifying that the code works as expected, we should be incentivizing good, readable code, not compaction. I would like to propose a pricing model that incorporates some, or all of the following as inputs: Lines of code Cyclomatic complexity Avg function length # of functions Are there any other metrics I should incorporate, or other ideas for how we can reasonably create pricing for code reviews that encourages safe and understandable code?

    Read the article

  • unable to save files from Code Blocks ONLY

    - by ths
    i have an NTFS drive mounted in a folder /Tejas i have created a new project using it in a folder in this drive but i am unable to save the changes, i get the following error message Couldn't save project /Tejas/Project/codeblock/ciphers/ciphers.cbp (Maybe the file is write-protected?) i get similar message even when i try to save the c source file i am able to edit and save files using gedit editor... why am i getting this problem?

    Read the article

  • Can AfferoGPLv3 code be used in GPLv3 code?

    - by Karel Bílek
    Can software with AGPLv3 license be used with GPLv3 project? Can the resulting project be GPLv3, or must it have the special requirements of AGPLv3? I am not very smart from clause 13 of GLPv3 that mentions AGPLv3. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. Must the resulting, combined work be AGPLv3 or not?

    Read the article

  • Layout of mathematical views (iOS)

    - by William Jockusch
    I am trying to figure out the right way to encapsulate graphical information about mathematical objects. It is not simple. For example, a matrix can include square brackets around its entries, or not. Some things carry down to sub-objects -- for example, a matrix might track the font size to be used by its entries. Similarly, the font color and the background color would carry down to the entries. Other things do not carry down. For example, the entries of the matrix do not need to know whether or not the matrix has those square brackets. Based on all of the above, I need to calculate sizes for everything, then frames. All of this can depend on the properties stored above. The size of a matrix depends on the sizes of its entries, and also on whether or not it has those brackets. What I am having a hard time with is not the individual ways to calculate sensible frames for this or that. It is the overall organizational structure of the whole thing. How can I keep track of it all without going crazy. One particular obstacle is worth mentioning -- for reasons I don't want to go into here, I need to calculate the sizes and frames for everything before I instantiate any actual views. So, for example, if I have a Matrix object, I need to calculate its size before I make a MatrixView. If I have an equation, I need to calculate the size of the view for the equation before I create the actual view. So I clearly need separate objects for those calculations. But I can't figure out a sensible class structure for those objects. If I put them all into a single class, I get some advantages because copying then becomes easy. But I also end up with a bloated class that contains info that is irrelevant for some objects -- such as whether or not to include those brackets around the matrix. But if I use a lot of different classes, copying properties becomes a real pain. If it matters, this is all in Objective C, for an iOS environment. Any pointers would be greatly appreciated.

    Read the article

  • Trouble with Code First DatabaseGenerated Composite Primary Key

    - by Nick Fleetwood
    This is a tad complicated, and please, I know all the arguments against natural PK's, so we don't need to have that discussion. using VS2012/MVC4/C#/CodeFirst So, the PK is based on the date and a corresponding digit together. So, a few rows created today would be like this: 20131019 1 20131019 2 And one created tomorrow: 20131020 1 This has to be automatically generated using C# or as a trigger or whatever. The user wouldn't input this. I did come up with a solution, but I'm having problems with it, and I'm a little stuck, hence the question. So, I have a model: public class MainOne { //[Key] //public int ID { get; set; } [Key][Column(Order=1)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string DocketDate { get; set; } [Key][Column(Order=2)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string DocketNumber { get; set; } [StringLength(3, ErrorMessage = "Corp Code must be three letters")] public string CorpCode { get; set; } [StringLength(4, ErrorMessage = "Corp Code must be four letters")] public string DocketStatus { get; set; } } After I finish the model, I create a new controller and views using VS2012 scaffolding. Then, what I'm doing is debugging to create the database, then adding the following instead of trigger after Code First creates the DB [I don't know if this is correct procedure]: CREATE TRIGGER AutoIncrement_Trigger ON [dbo].[MainOnes] instead OF INSERT AS BEGIN DECLARE @number INT SELECT @number=COUNT(*) FROM [dbo].[MainOnes] WHERE [DocketDate] = CONVERT(DATE, GETDATE()) INSERT INTO [dbo].[MainOnes] (DocketDate,DocketNumber,CorpCode,DocketStatus) SELECT (CONVERT(DATE, GETDATE ())),(@number+1),inserted.CorpCode,inserted.DocketStatus FROM inserted END And when I try to create a record, this is the error I'm getting: The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: The object state cannot be changed. This exception may result from one or more of the primary key properties being set to null. Non-Added objects cannot have null primary key values. See inner exception for details. Now, what's interesting to me, is that after I stop debugging and I start again, everything is perfect. The trigger fired perfectly, so the composite PK is unique and perfect, and the data in other columns is intact. My guess is that EF is confused by the fact that there is seemingly no value for the PK until AFTER an insert command is given. Also, appearing to back this theory, is that when I try to edit on of the rows, in debug, I get the following error: The number of primary key values passed must match number of primary key values defined on the entity. Same error occurs if I try to pull the 'Details' or 'Delete' function. Any solution or ideas on how to pull this off? I'm pretty open to anything, even creating a hidden int PK. But it would seem redundant. EDIT 21OCT13 [HttpPost] public ActionResult Create(MainOne mainone) { if (ModelState.IsValid) { var countId = db.MainOnes.Count(d => d.DocketDate == mainone.DocketNumber); //assuming that the date field already has a value mainone.DocketNumber = countId + 1; //Cannot implicitly convert type int to string db.MainOnes.Add(mainone); db.SaveChanges(); return RedirectToAction("Index"); } return View(mainone); } EDIT 21OCT2013 FINAL CODE SOLUTION For anyone like me, who is constantly searching for clear and complete solutions. if (ModelState.IsValid) { String udate = DateTime.UtcNow.ToString("yyyy-MM-dd"); mainone.DocketDate = udate; var ddate = db.MainOnes.Count(d => d.DocketDate == mainone.DocketDate); //assuming that the date field already has a value mainone.DocketNumber = ddate + 1; db.MainOnes.Add(mainone); db.SaveChanges(); return RedirectToAction("Index"); }

    Read the article

  • EF4 Code First - Many to many relationship issue

    - by Yngve B. Nilsen
    Hi! I'm having some trouble with my EF Code First model when saving a relation to a many to many relationship. My Models: public class Event { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Tag> Tags { get; set; } } public class Tag { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Event> Events { get; set; } } In my controller, I map one or many TagViewModels into type of Tag, and send it down to my servicelayer for persistence. At this time by inspecting the entities the Tag has both Id and Name (The Id is a hidden field, and the name is a textbox in my view) The problem occurs when I now try to add the Tag to the Event. Let's take the following scenario: The Event is already in my database, and let's say it already has the related tags C#, ASP.NET If I now send the following list of tags to the servicelayer: ID Name 1 C# 2 ASP.NET 3 EF4 and add them by first fetching the Event from the DB, so that I have an actual Event from my DbContext, then I simply do myEvent.Tags.Add to add the tags.. Problem is that after SaveChanges() my DB now contains this set of tags: ID Name 1 C# 2 ASP.NET 3 EF4 4 C# 5 ASP.NET This, even though my Tags that I save has it's ID set when I save it (although I didn't fetch it from the DB)

    Read the article

  • difference between :first and :first-child not clear

    - by sushil bharwani
    i am having a ul li list <ul> <li>Parent <ul> <li> child1 </li> <li> child2 </li> </ul> </li> </ul> and i am trying to use a selector jQuery('ul li:first') and jQuery('ul li:first-child') both giving the same result this makes me confused about the difference between the two is there a example which clarifies the difference between two selectors

    Read the article

  • difference be :first and :first-child not clear

    - by sushil bharwani
    i am having a ul li list < ul > < li > Parent < ul > < li > child1 < /li > < li > child2 < /li > < /ul > < /li > < /ul > and i am trying to use a selector jQuery('ul li:first') and jQuery('ul li:first-child') both giving the same result this makes me confused about the difference between the two is there a example which clarifies the difference between two selectors

    Read the article

  • vb.net A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in ms

    - by prasoon99
    I just installed Visual Basic 2010 Express. I created a simple console application: Module Module1 Sub Main() Dim i As Integer i = 0 End Sub End Module I'm getting the following error SIX times before I get to line "i = 0": A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll Can anyone help? Why is this happening? Is there something wrong with my configuration? -Prasoon

    Read the article

  • first Occurrence Of Non Blank Cell vba

    - by Madhu Kiran
    Hi, I am trying to write VBA code which works on my Excel sheet. Range("A65536").End(xlUp).Row gives me the row number of the last non blank cell. similarly i am trying to get the row number of the first non blank cell in that particular column. Thanks in advance. madhu

    Read the article

  • “It’s only test code…”

    - by Chris George
    “Let me hack this in, it’s only test code”, “Don’t worry about getting it reviewed, it’s only test code”, “It doesn’t have to be elegant or efficient, it’s only test code”… do these phrases sound familiar? Chances are if you’ve working with test automation, at one point or other you will have heard these phrases, you have probably even used them yourself! What is certain is that code written under this “it’s only test code” mantra will come back and bite you in the arse! I’ve recently encountered a case where a test was giving a false positive, therefore hiding a real product bug because that test code was very badly written. Firstly it was very difficult to understand what the test was actually trying to achieve let alone how it was doing it, and this complexity masked a simple logic error. These issues are real and they do happen. Let’s take a step back from this and look at what we are trying to do. We are writing test code that tests product code, and we do this to create a suite of tests that will help protect our software against regressions. This test code is making sure that the product behaves as it should by employing some sort of expected result verification. The simple cases of these are generally not a problem. However, automation allows us to explore more complex scenarios in many more permutations. As this complexity increases then so does the complexity of the test code. It is at this point that code which has not been architected properly will cause problems.   Keep your friends close… So, how do we make sure we are doing it right? The development teams I have worked on have always had Test Engineers working very closely with their Software Engineers. This is something that I have always tried to take full advantage of. They are coding experts! So run your ideas past them, ask for advice on how to structure your code, help you design your data structures. This may require a shift in your teams viewpoint, as contrary to this section title and folklore, Software Engineers are not actually the mortal enemy of Test Engineers. As time progresses, and test automation becomes more and more ingrained in what we do, the two roles are converging more than ever. Over the 16 years I have spent as a Test Engineer, I have seen the grey area between the two roles grow significantly larger. This serves to strengthen the relationship and common bond between the two roles which helps to make test code activities so much easier!   Pair for the win Possibly the best thing you could do to write good test code is to pair program on the task. This will serve a few purposes. you will get the benefit of the Software Engineers knowledge and experience the Software Engineer will gain knowledge on the testing process. Sharing the love is a wonderful thing! two pairs of eyes are always better than one… And so are two brains. Between the two of you, I will guarantee you will derive more useful test cases than if it was just one of you.   Code reviews Another policy which certainly pays dividends is the practice of code reviews. By having one of your peers review your code before you commit it serves two purposes. Firstly, it forces you to explain your code. Just the act of doing this will often pick up errors in your code. Secondly, it gets yet another pair of eyes on your code! I cannot stress enough how important code reviews are. The benefits they offer apply as much to product code as test code. In short, Software and Test Engineers should all be doing them! It can be extended even further by getting test code reviewed by a Software Engineer and a Test Engineer, and likewise product code. This serves to keep both functions in the loop with changes going on within your code base.   Learn from your devs I briefly touched on this earlier but I’d like to go into more detail here. Pairing with your Software Engineers when writing your test code is such an amazing opportunity to improve your coding skills. As I sit here writing this article waiting to be called into court for jury service, it reminds me that it takes a lot of patience to be a Test Engineer, almost as much as it takes to be a juror! However tempting it is to go rushing in and start writing your automated tests, resist that urge. Discuss what you want to achieve then talk through the approach you’re going to take. Then code it up together. I find it really enlightening to ask questions like ‘is there a better way to do this?’ Or ‘is this how you would code it?’ The latter question, especially, is where I learn the most. I’ve found that most Software Engineers will be reluctant to show you the ‘right way’ to code something when writing tests because they perceive the ‘right way’ to be too complicated for the Test Engineer (e.g. not mentioning LINQ and instead doing something verbose). So by asking how THEY would code it, it unleashes their true dev-ness and advanced code usually ensues! I would like to point out, however, that you don’t have to accept their method as the final answer. On numerous occasions I have opted for the more simple/verbose solution because I found the code written by the Software Engineer too advanced and therefore I would find it unreadable when I return to the code in a months’ time! Always keep the target audience in mind when writing clever code, and in my case that is mostly Test Engineers.  

    Read the article

  • .NET RegEx - First N chars of First M lines

    - by George
    Hello! I want 4 general RegEx expressions for the following 4 basic cases: Up to A chars starting after B chars from start of line on up to C lines starting after D lines from start of file Up to A chars starting after B chars from start of line on up to C lines occurring before D lines from end of file Up to A chars starting before B chars from end of line on up to C lines starting after D lines from start of file Up to A chars starting before B chars from end of line on up to C lines starting before D lines from end of file These would allow to select arbitrary text blocks anywhere in the file. So far I have managed to come up with cases that only work for lines and chars separately: (?<=(?m:^[^\r]{N}))[^\r]{1,M} = UP TO M chars OF EVERY LINE, AFTER FIRST N chars [^\r]{1,M}(?=(?m:.{N}\r$)) = UP TO M chars OF EVERY LINE, BEFORE LAST N chars The above 2 expressions are for chars, and they return MANY matches (one for each line). (?<=(\A([^\r]*\r\n){N}))(?m:\n*[^\r]*\r$){1,M} = UP TO M lines AFTER FIRST N lines (((?=\r?)\n[^\r]*\r)|((?=\r?)\n[^\r]+\r?)){1,M}(?=((\n[^\r]*\r)|(\n[^\r]+\r?)){N}\Z) = UP TO M lines BEFORE LAST N lines from end These 2 expressions are equivalents for the lines, but they always return just ONE match. The task is to combine these expressions to allow for scenarios 1-4. Anyone can help? Note that the case in the title of the question, is just a subclass of scenario #1, where both B = 0 and D = 0. EXAMPLE: SOURCE: line1 blah 1 line2 blah 2 line3 blah 3 line4 blah 4 line5 blah 5 line6 blah 6 DESIRED RESULT: Characters 3-6 of lines 3-5: A total of 3 matches: <match>ne3 </match> <match>ne4 </match> <match>ne5 </match>

    Read the article

  • When is someone else's code I use from the internet "mine"?

    - by robault
    I'm building a library from methods that I've found on the internet. Some are free to use or modify with no requirements, others say that if I leave a comment in the code it's okay to use, others say when I use the code I have to attribute the use of someone's code in my application (in the credits for my app I guess). What I've been doing is reorganizing classes, renaming methods, adding descriptions (code comments), renaming the parameters and names inside the methods to something meaningful, optimizing loops if applicable, changing return types, adding try/catch/throw blocks, adding parameter checks and cleaning up resources in the methods. For example; I didn't come up with the algorithm for blurring a Bitmap but I've taken the basic example of iterating through the pixels and turned it into a decent library method (applying the aforementioned modifications). I understand how to go about building it now myself but I didn't actually hit the keystrokes to make it and I couldn't have come up with it before learning from their example. What about code people get in answers on Stackoverflow or examples from Codeproject? At what point can I drop their requirements because at n% their code became mine? FWIW I intend on using the libraries to create products that I will sell.

    Read the article

  • Operating on rows and then on columns of a matrix produces code duplication

    - by Chetan
    I have the following (Python) code to check if there are any rows or columns that contain the same value: # Test rows -> # Check each row for a win for i in range(self.height): # For each row ... firstValue = None # Initialize first value placeholder for j in range(self.width): # For each value in the row if (j == 0): # If it's the first value ... firstValue = b[i][j] # Remember it else: # Otherwise ... if b[i][j] != firstValue: # If this is not the same as the first value ... firstValue = None # Reset first value break # Stop checking this row, there's no win here if (firstValue != None): # If first value has been set # First value placeholder now holds the winning player's code return firstValue # Return it # Test columns -> # Check each column for a win for i in range(self.width): # For each column ... firstValue = None # Initialize first value placeholder for j in range(self.height): # For each value in the column if (j == 0): # If it's the first value ... firstValue = b[j][i] # Remember it else: # Otherwise ... if b[j][i] != firstValue: # If this is not the same as the first value ... firstValue = None # Reset first value break # Stop checking this column, there's no win here if (firstValue != None): # If first value has been set # First value placeholder now holds the winning player's code return firstValue # Return it Clearly, there is a lot of code duplication here. How do I refactor this code? Thanks!

    Read the article

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