Daily Archives

Articles indexed Sunday June 6 2010

Page 8/76 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Ruby &&= edge case

    - by Alan O'Donnell
    Bit of an edge case, but any idea why &&= would behave this way? I'm using 1.9.2. obj = Object.new obj.instance_eval {@bar &&= @bar} # => nil, expected obj.instance_variables # => [], so obj has no @bar instance variable obj.instance_eval {@bar = @bar && @bar} # ostensibly the same as @bar &&= @bar obj.instance_variables # => [:@bar] # why would this version initialize @bar? For comparison, ||= initializes the instance variable to nil, as I'd expect: obj = Object.new obj.instance_eval {@foo ||= @foo} obj.instance_variables # => [:@foo], where @foo is set to nil Thanks!

    Read the article

  • Why am I getting a segmentation fault with this code?

    - by gooswa
    Trying to make a simple rectangle/bin packer in C. Takes a given area and finds placement for any given size rectangle. About after 4 recursions is when I get the segmentation fault. #include <stdio.h> #include <stdlib.h> typedef struct node_type PackNode; struct node_type { int x , y; int width , height; int used; struct node_type *left; struct node_type *right; }; typedef struct point_type PackPoint; struct point_type { int x,y; }; PackNode _clone(PackNode *node) { PackNode clone; clone.used = 0; clone.x = node->x; clone.y = node->y; clone.width = node->width; clone.height= node->height; clone.left = NULL; clone.right= NULL; return clone; } PackNode root; int rcount; PackPoint* recursiveFind(PackNode *node, int w, int h) { PackPoint rp; PackPoint *p = NULL; rcount++; printf ("rcount = %u\n", rcount); //left is not null go to left, if left didn't work try right. if (node->left!=NULL) { //move down to left branch p = recursiveFind(node->left, w, h); if (p!=NULL) { return p; } else { p = recursiveFind(node->right, w, h); return p; } } else { //If used just return null and possible go to the right branch; if (node->used==1 || w > node->width || h > node->height) { return p; } //if current node is exact size and hasn't been used it return the x,y of the mid-point of the rectangle if (w==node->width && h == node->height) { node->used=1; rp.x = node->x+(w/2); rp.y = node->y+(h/2); p = &rp; return p; } //If rectangle wasn't exact fit, create branches from cloning it's parent. PackNode l_clone = _clone(node); PackNode r_clone = _clone(node); node->left = &l_clone; node->right = &r_clone; //adjust branches accordingly, split up the current unused areas if ( (node->width - w) > (node->height - h) ) { node->left->width = w; node->right->x = node->x + w; node->right->width = node->width - w; } else { node->left->height = h; node->right->y = node->y + h; node->right->height = node->height - h; } p = recursiveFind(node->left, w, h); return p; } return p; } int main(void) { root = malloc( root.x=0; root.y=0; root.used=0; root.width=1000; root.height=1000; root.left=NULL; root.right=NULL; int i; PackPoint *pnt; int rw; int rh; for (i=0;i<10;i++) { rw = random()%20+1; rh = random()%20+1; pnt = recursiveFind(&root, rw, rh); printf("pnt.x,y: %d,%d\n",pnt->x,pnt->y); } return 0; }

    Read the article

  • How do I change variables from different classes?

    - by Dan T
    Before I delve into it, I'm very new to Android and I have just started learning Java last month. I've hit bumps while trying to develop my first simple app. Most of these hurdles were jumped thanks to random tutorials online. MY CODE IS VERY MESSY. Any tips are appreciated. The question above is quite broad, but this is what I want to do: It's a essentially a blood alcohol content calculator / drink keeper-tracker. Basic layout: http://i.imgur.com/JGuh7.jpg The buttons along the bottom are just regular buttons, not ImageButtons (had problems with that) Here's some example code of one: <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_marginRight="5dp" android:background="@drawable/addbeer"/> The buttons and TextView are all in main.xml. I have variables defined in a class called Global.java: package com.dantoth.drinkingbuddy; import android.app.Activity; public class Global extends Activity{ public static double StandardDrinks = 0; public static double BeerOunces = 12; public static double BeerPercentAlcohol = .05; public static double BeerDrink = BeerOunces * BeerPercentAlcohol; public static double BeerDrinkFinal = BeerDrink * 1.6666666; public static double ShotOunces = 1.5; public static double ShotPercentAlcohol = .4; public static double ShotDrink = ShotOunces * ShotPercentAlcohol; public static double ShotDrinkFinal = ShotDrink * 1.6666666; public static double WineOunces = 5; public static double WinePercentAlcohol = .12; public static double WineDrink = WineOunces * WinePercentAlcohol; public static double WineDrinkFinal = WineDrink * 1.6666666; public static double OtherOunces; public static double OtherPercentAlcohol; public static double OtherDrink = OtherOunces * (OtherPercentAlcohol * .01); public static double OtherDrinkFinal = OtherDrink * 1.6666666; public static double GenderConstant = 7.5; //9 for female public static double Weight = 180; public static double TimeDrinking = 60; public static double Hours = TimeDrinking / 60; public static double Bac = ((StandardDrinks / 2) * (GenderConstant / Weight)) - (0.017 * Hours); } The last variable is the important part. It calculates your BAC based on the factors involved. When I press the add beer button (Button01) I make it add 1 to StandardDrinks, simulating drinking one beer. The other variables in the Bac formula have values assigned to them in Global.java. The code that makes the beer button do stuff is in my regular class, drinkingbuddy.java: public class DrinkingBuddy extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.Button01); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Global.StandardDrinks = Global.StandardDrinks + Global.BeerDrinkFinal; Toast.makeText(DrinkingBuddy.this, "Mmmm... Beer", Toast.LENGTH_SHORT).show(); } }); By my perception, StandardDrinks should now have a value of 1. However, when I click the Calculate BAC button (Button05) it merely outputs the variable Bac as if StandardDrinks was still set to 0. Here is the code for the Calculate BAC button (Button05): Button button4 = (Button) findViewById(R.id.Button05); button4.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { TextView texty; texty = (TextView) findViewById(R.id.texty1); texty.setText("Your BAC is " + Global.Bac ); } }); It outputs the following to the text view: "Your BAC is -0.017". This is the Bac value for if StandardDrinks was still 0, so obviously there is some problem communicating between the classes. Can anyone help me?? The other elements of the formula (weight, time spent drinking, and the alcohol %'s and such) are variables because I will ultimately allow the user to change those values in the settings. I've heard around the water cooler that global variables are not good programming style, but this is the closest I've come to getting it to work. Any other ways of doing it are very much welcomed!

    Read the article

  • Scribus - disable escaping of text field

    - by ityndall
    Scribus 1.3.3.13 - Ubuntu 64bit I have a scribus document that I'm creating with text fields. I'm using the text fields for code samples, as that appeared to be the only way to have a scrolling text frame. Upon conversion of the document, these text fields get populated with escape characters. Is there any way to disable the escape sequences that are getting populating into these text fields?

    Read the article

  • How to have onSearchRequested not open a web browser.

    - by pcm2a
    I have a button in my app. When it is pressed I call the onSearchRequested() method. When this is called the stock search box comes up so the user can type some junk in there. When they press "Go" I need the results returned back to my application but instead the stock browser is opened and a google search is performed. How can I tell it to return the results to my application instead. I've tried these items in my manifest.xml file: <meta-data android:name="android.app.default_searchable" android:value=".MainActivity" /> <activity android:name=".MainActivity" android:launchMode="singleTop" <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> I've also tried to capture the result in my onCreate with this: Intent intent = getIntent(); if (Intent.ACTION_SEARCH.equals(intent.getAction()))

    Read the article

  • Copy call signature to decorator

    - by Morgoth
    If I do the following def mydecorator(f): def wrapper(*args, **kwargs): f(*args, **kwargs) wrapper.__doc__ = f.__doc__ wrapper.__name__ = f.__name__ return wrapper @mydecorator def myfunction(a,b,c): '''My docstring''' pass And then type help myfunction, I get: Help on function myfunction in module __main__: myfunction(*args, **kwargs) My docstring So the name and docstring are correctly copied over. Is there a way to also copy over the actual call signature, in this case (a, b, c)?

    Read the article

  • Elegantly determine if more than one boolean is "true"

    - by Ola Tuvesson
    I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would allow me to check this condition in a single if() statement? Target language is C# but I'm interested in solutions in other languages as well (as long as we're not talking about specific built-in functions). One interesting option is to store the booleans in a byte, do a right shift and compare with the original byte. Something like if(myByte && (myByte 1)) But this would require converting the separate booleans to a byte (via a bitArray?) and that seems a bit (pun intended) clumsy... [edit]Sorry, that should have been if(myByte & (myByte - 1)) [/edit] Note: This is of course very close to the classical "population count", "sideways addition" or "Hamming weight" programming problem - but not quite the same. I don't need to know how many of the bits are set, only if it is more than one. My hope is that there is a much simpler way to accomplish this.

    Read the article

  • Email an image via custom url scheme

    - by Amaresh
    I am using custom url schemes. I can send string messages as parameters to my custom url and emailing this to any person. When any person opens this email attachment in device in it open my app installed in device with the passed parameters in my custom url. Similarly how to email an image via custom url and when any person opens this attachment the image is passed to my app in device. I tried to encode the image in base64 format and tried to append to my url,but not working. Any ideas?? Thanks in advance

    Read the article

  • Sitecore not resolving rich text editor URLS in page renders

    - by adam
    Hi We're having issues inserting links into rich text in Sitecore 6.1.0. When a link to a sitecore item is inserted, it is outputted as: http://domain/~/link.aspx?_id=8A035DC067A64E2CBBE2662F6DB53BC5&_z=z Rather than the actual resolved url: http://domain/path/to/page.aspx This article confirms that this should be resolved in the render pipeline: in Sitecore 6 it inserts a specially formatted link that contains the Guid of the item you want to link to, then when the item is rendered the special link is replaced with the actual link to the item The pipeline has the method ShortenLinks added in web.config <convertToRuntimeHtml> <processor type="Sitecore.Pipelines.ConvertToRuntimeHtml.PrepareHtml, Sitecore.Kernel"/> <processor type="Sitecore.Pipelines.ConvertToRuntimeHtml.ShortenLinks, Sitecore.Kernel"/> <processor type="Sitecore.Pipelines.ConvertToRuntimeHtml.SetImageSizes, Sitecore.Kernel"/> <processor type="Sitecore.Pipelines.ConvertToRuntimeHtml.ConvertWebControls, Sitecore.Kernel"/> <processor type="Sitecore.Pipelines.ConvertToRuntimeHtml.FixBullets, Sitecore.Kernel"/> <processor type="Sitecore.Pipelines.ConvertToRuntimeHtml.FinalizeHtml, Sitecore.Kernel"/> </convertToRuntimeHtml> So I really can't see why links are still rendering in ID format rather than as full SEO-tastic urls. Anyone got any clues? Thanks, Adam

    Read the article

  • LLVM: Passing a pointer to a struct, which holds a pointer to a function, to a JIT function

    - by Rusky
    I have an LLVM (version 2.7) module with a function that takes a pointer to a struct. That struct contains a function pointer to a C++ function. The module function is going to be JIT-compiled, and I need to build that struct in C++ using the LLVM API. I can't seem get the pointer to the function as an LLVM value, let alone pass a pointer to the ConstantStruct that I can't build. I'm not sure if I'm even on the track, but this is what I have so far: void print(char*); vector<Constant*> functions; functions.push_back(ConstantExpr::getIntToPtr( ConstantInt::get(Type::getInt32Ty(context), (int)print), /* function pointer type here, FunctionType::get(...) doesn't seem to work */ )); ConstantStruct* struct = cast<ConstantStruct>(ConstantStruct::get( cast<StructType>(m->getTypeByName("printer")), functions )); Function* main = m->getFunction("main"); vector<GenericValue> args; args[0].PointerVal = /* not sure what goes here */ ee->runFunction(main, args);

    Read the article

  • mysql does not utilize my cpu and ram enough?

    - by vick
    Hello Everyone! I am importing a 2.5gb csv file to a mysql table. My storage engine is innodb. Here is the script: use xxx; DROP TABLE IF EXISTS `xxx`.`xxx`; CREATE TABLE `xxx`.`xxx` ( `xxx_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(128) NOT NULL, `yy` varchar(128) NOT NULL, `yyy` varchar(64) NOT NULL, `yyyy` varchar(2) NOT NULL, `yyyyy` varchar(10) NOT NULL, `url` varchar(64) NOT NULL, `p` varchar(10) NOT NULL, `pp` varchar(10) NOT NULL, `category` varchar(256) NOT NULL, `flag` varchar(4) NOT NULL, PRIMARY KEY (`xxx_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; set autocommit = 0; load data local infile '/home/xxx/raw.csv' into table company fields terminated by ',' optionally enclosed by '"' lines terminated by '\r\n' ( name, yy, yyy, yyyy, yyyyy, url, p, pp, category, flag ); commit; Why does my PC (core i7 920 with 6gb ram) only consume 9% cpu power and 60% ram when running these queries?

    Read the article

  • How do I refer to a view controller in a subclass?

    - by thekevinscott
    Hey all, I'm currently teaching myself Objective C and I'm kind of stuck. I'm building a backgammon game and I have a subclass, "Piece", which is being initialized, repeatedly, in BackGammonViewController. In BackGammonViewController, if I do this: UIImage *myImage = [ UIImage imageNamed: @"white-piece.png" ]; UIImageView *myImageView = [ [ UIImageView alloc ] initWithImage: myImage ]; [self.view addSubview:myImageView]; [myImageView release]; The image appears. However, I want to do this within my "piece" class. How do I refer to the "self.view" from within the piece class? Do I need to pass a reference to the view, into the "piece class" ? Or is there a global reference I can call from within the "piece class" ? Thanks for your help.

    Read the article

  • How do I process a nested list?

    - by ddbeck
    Suppose I have a bulleted list like this: * list item 1 * list item 2 (a parent) ** list item 3 (a child of list item 2) ** list item 4 (a child of list item 2 as well) *** list item 5 (a child of list item 4 and a grand-child of list item 2) * list item 6 I'd like to parse that into a nested list or some other data structure which makes the parent-child relationship between elements explicit (rather than depending on their contents and relative position). For example, here's a list of tuples containing an item and a list of its children (and so forth): [('list item 1',), ('list item 2', [('list item 3',), [('list item 4', [('list item 5'),]] ('list item 6',)] I've attempted to do this with plain Python and some experimentation with Pyparsing, but I'm not making progress. I'm left with two major questions: What's the strategy I need to employ to make this work? I know recursion is part of the solution, but I'm having a hard time making the connection between this and, say, a Fibonacci sequence. I'm certain I'm not the first person to have done this, but I don't know the terminology of the problem to make fruitful searches for more information on this topic. What problems are related to this so that I can learn more about solving these kinds of problems in general?

    Read the article

  • Algorithm for multiple word matching in a text, count the number of every matched word

    - by 66
    I have noticed that it has solutions for matching multiple words in a given text, such as below: http://stackoverflow.com/questions/1099985/algorithm-for-multiple-word-matching-in-text If I want to know exactly the number of appearances of each matched word in the text, my solution is like this: step 1: using ac-algorithm to obtain the maching words; step 2: count the number of each word obtained in step 1 is there a faster way? Thx~

    Read the article

  • Writing annotataion schemas for Callisto

    - by Ken Bloom
    Does anybody know where I can find documentation on how to write annotation schemas for Callisto? I'm looking to write something a little more complicated than I can generate from a DTD -- that only gives me the ability to tag different kinds of text mentions. I'm looking to create a schema that represents a single type of relationship between five or six different kinds of textual mentions (and some of these types of mentions have attributes that I need to assign values to), and possibly having a second type of relationship between the first two instances of the first type of relationship. (Alternatively, does anybody know of any software that would be better for this kind of schema? I've been looking at WordFreak, but it's a little clumsy, and it doesn't support attributes on its textual mentions.)

    Read the article

  • Software Engineering Practices &ndash; Different Projects should have different maturity levels

    - by Dylan Smith
    I’ve had a lot of discussions at the office lately about the drastically different sets of software engineering practices used on our various projects, if what we are doing is appropriate, and what factors should you be considering when determining what practices are most appropriate in a given context. I wanted to write up my thoughts in a little more detail on this subject, so here we go: If you compare any two software projects (specifically comparing their codebases) you’ll often see very different levels of maturity in the software engineering practices employed. By software engineering practices, I’m specifically referring to the quality of the code and the amount of technical debt present in the project. Things such as Test Driven Development, Domain Driven Design, Behavior Driven Development, proper adherence to the SOLID principles, etc. are all practices that you would expect at the mature end of the spectrum. At the other end of the spectrum would be the quick-and-dirty solutions that are done using something like an Access Database, Excel Spreadsheet, or maybe some quick “drag-and-drop coding”. For this blog post I’m going to refer to this as the Software Engineering Maturity Spectrum (SEMS). I believe there is a time and a place for projects at every part of that SEMS. The risks and costs associated with under-engineering solutions have been written about a million times over so I won’t bother going into them again here, but there are also (unnecessary) costs with over-engineering a solution. Sometimes putting multiple layers, and IoC containers, and abstracting out the persistence, etc is complete overkill if a one-time use Access database could solve the problem perfectly well. A lot of software developers I talk to seem to automatically jump to the very right-hand side of this SEMS in everything they do. A common rationalization I hear is that it may seem like a small trivial application today, but these things always grow and stick around for many years, then you’re stuck maintaining a big ball of mud. I think this is a cop-out. Sure you can’t always anticipate how an application will be used or grow over its lifetime (can you ever??), but that doesn’t mean you can’t manage it and evolve the underlying software architecture as necessary (even if that means having to toss the code out and re-write it at some point…maybe even multiple times). My thoughts are that we should be making a conscious decision around the start of each project approximately where on the SEMS we want the project to exist. I believe this decision should be based on 3 factors: 1. Importance - How important to the business is this application? What is the impact if the application were to suddenly stop working? 2. Complexity - How complex is the application functionality? 3. Life-Expectancy - How long is this application expected to be in use? Is this a one-time use application, does it fill a short-term need, or is it more strategic and is expected to be in-use for many years to come? Of course this isn’t an exact science. You can’t say that Project X should be at the 73% mark on the SEMS and expect that to be helpful. My point is not that you need to precisely figure out what point on the SEMS the project should be at then translate that into some prescriptive set of practices and techniques you should be using. Rather my point is that we need to be aware that there is a spectrum, and that not everything is going to be (or should be) at the edges of that spectrum, indeed a large number of projects should probably fall somewhere within the middle; and different projects should adopt a different level of software engineering practices and maturity levels based on the needs of that project. To give an example of this way of thinking from my day job: Every couple of years my company plans and hosts a large event where ~400 of our customers all fly in to one location for a multi-day event with various activities. We have some staff whose job it is to organize the logistics of this event, which includes tracking which flights everybody is booked on, arranging for transportation to/from airports, arranging for hotel rooms, name tags, etc The last time we arranged this event all these various pieces of data were tracked in separate spreadsheets and reconciliation and cross-referencing of all the data was literally done by hand using printed copies of the spreadsheets and several people sitting around a table going down each list row by row. Obviously there is some room for improvement in how we are using software to manage the event’s logistics. The next time this event occurs we plan to provide the event planning staff with a more intelligent tool (either an Excel spreadsheet or probably an Access database) that can track all the information in one location and make sure that the various pieces of data are properly linked together (so for example if a person cancels you only need to delete them from one place, and not a dozen separate lists). This solution would fall at or near the very left end of the SEMS meaning that we will just quickly create something with very little attention paid to using mature software engineering practices. If we examine this project against the 3 criteria I listed above for determining it’s place within the SEMS we can see why: Importance – If this application were to stop working the business doesn’t grind to a halt, revenue doesn’t stop, and in fact our customers wouldn’t even notice since it isn’t a customer facing application. The impact would simply be more work for our event planning staff as they revert back to the previous way of doing things (assuming we don’t have any data loss). Complexity – The use cases for this project are pretty straightforward. It simply needs to manage several lists of data, and link them together appropriately. Precisely the task that access (and/or Excel) can do with minimal custom development required. Life-Expectancy – For this specific project we’re only planning to create something to be used for the one event (we only hold these events every 2 years). If it works well this may change (see below). Let’s assume we hack something out quickly and it works great when we plan the next event. We may decide that we want to make some tweaks to the tool and adopt it for planning all future events of this nature. In that case we should examine where the current application is on the SEMS, and make a conscious decision whether something needs to be done to move it further to the right based on the new objectives and goals for this application. This may mean scrapping the access database and re-writing it as an actual web or windows application. In this case, the life-expectancy changed, but let’s assume the importance and complexity didn’t change all that much. We can still probably get away with not adopting a lot of the so-called “best practices”. For example, we can probably still use some of the RAD tooling available and might have an Autonomous View style design that connects directly to the database and binds to typed datasets (we might even choose to simply leave it as an access database and continue using it; this is a decision that needs to be made on a case-by-case basis). At Anvil Digital we have aspirations to become a primarily product-based company. So let’s say we use this tool to plan a handful of events internally, and everybody loves it. Maybe a couple years down the road we decide we want to package the tool up and sell it as a product to some of our customers. In this case the project objectives/goals change quite drastically. Now the tool becomes a source of revenue, and the impact of it suddenly stopping working is significantly less acceptable. Also as we hold focus groups, and gather feedback from customers and potential customers there’s a pretty good chance the feature-set and complexity will have to grow considerably from when we were using it only internally for planning a small handful of events for one company. In this fictional scenario I would expect the target on the SEMS to jump to the far right. Depending on how we implemented the previous release we may be able to refactor and evolve the existing codebase to introduce a more layered architecture, a robust set of automated tests, introduce a proper ORM and IoC container, etc. More likely in this example the jump along the SEMS would be so large we’d probably end up scrapping the current code and re-writing. Although, if it was a slow phased roll-out to only a handful of customers, where we collected feedback, made some tweaks, and then rolled out to a couple more customers, we may be able to slowly refactor and evolve the code over time rather than tossing it out and starting from scratch. The key point I’m trying to get across is not that you should be throwing out your code and starting from scratch all the time. But rather that you should be aware of when and how the context and objectives around a project changes and periodically re-assess where the project currently falls on the SEMS and whether that needs to be adjusted based on changing needs. Note: There is also the idea of “spectrum decay”. Since our industry is rapidly evolving, what we currently accept as mature software engineering practices (the right end of the SEMS) probably won’t be the same 3 years from now. If you have a project that you were to assess at somewhere around the 80% mark on the SEMS today, but don’t touch the code for 3 years and come back and re-assess its position, it will almost certainly have changed since the right end of the SEMS will have moved farther out (maybe the project is now only around 60% due to decay). Developer Skills Another important aspect to this whole discussion is around the skill sets of your architects and lead developers. When talking about the progression of a developers skills from junior->intermediate->senior->… they generally start by only being able to write code that belongs on the left side of the SEMS and as they gain more knowledge and skill they become capable of working at a higher and higher level along the SEMS. We all realize that the learning never stops, but eventually you’ll get to the point where you can comfortably develop at the right-end of the SEMS (the exact practices and techniques that translates to is constantly changing, but that’s not the point here). A critical skill that I’d love to see more evidence of in our industry is the most senior guys not only being able to work at the right-end of the SEMS, but more importantly be able to consciously work at any point along the SEMS as project needs dictate. An even more valuable skill would be if you could make the conscious decision to move a projects code further right on the SEMS (based on changing needs) and do so in an incremental manner without having to start from scratch. An exercise that I’m planning to go through with all of our projects here at Anvil in the near future is to map out where I believe each project currently falls within this SEMS, where I believe the project *should* be on the SEMS based on the business needs, and for those that don’t match up (i.e. most of them) come up with a plan to improve the situation.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >