Wednesday, February 9, 2011

How to extract a file extension in PHP ?

This is a question you can read everywhere on the web with various answers :

$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];

etc.

However, there is always "the best way" and it should be on stackoverflow.

  • pathinfo - http://uk.php.net/manual/en/function.pathinfo.php

    An example...

    $path_info = pathinfo('/foo/bar/baz.bill');
    
    echo $path_info['extension']; // "bill"
    
    vaske : This one is "the best way"
  • People from other scripting languages always think theirs is better because they have a built in function to do that and not PHP (I am looking at pythonistas right now :-)).

    In fact, it does exist, but few people know it. Meet pathinfo :

    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    

    This is fast, efficient, reliable and built in. Pathinfo can give you others info, such as canonical path, regarding to the constant you pass to it.

    Enjoy

    J-P : Why didn't you just put the answer in the question!?
    e-satis : Because it's written is the overflow FAQ do it this way.
    Mark Biek : I wish I could vote this up twice. I can't tell you how much code I've been able to replace using pathinfo
    e-satis : So do I. That's why I put it here !
    From e-satis
  • E-satis response is the correct way to determine the file extension.

    Alternatively, instead of relying on a files extension, you could use the fileinfo (http://us2.php.net/fileinfo) to determine the files MIME type.

    Here's a simplified example of processing an image uploaded by a user:

    // Code assumes necessary extensions are installed and a successful file upload has already occurred
    
    // Create a FileInfo object
    $finfo = new FileInfo(null, '/path/to/magic/file');
    
    // Determine the MIME type of the uploaded file
    switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME) {
        case 'image/jpg':
            $im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
        break;
    
        case 'image/png':
            $im = imagecreatefrompng($_FILES['image']['tmp_name']);
        break;
    
        case 'image/gif':
            $im = imagecreatefromgif($_FILES['image']['tmp_name']);
        break;
    }
    
    From Toxygene

How do I resize my panels when resizing the main form in a winforms application?

If the user of my winforms application resizes the main form, I want the 2 panels to stretch out also, along with the child controls.

How can I achieve this?

  • Play around with the Dock and Anchor properties of your panels.

  • You can use the TableLayoutPanel and set column width at x% each this way you will have the screen split in 2. The TableLayoutPanel must be Dock to fill all the form or Anchor.

    The TableLayoutPanel can contain other panel. OR you can use simply your panel and use Anchor (click the panel and go in the Properties panel of VS).

    From Daok
  • If the user of my winforms application resizes the main form, I want the 2 panels to stretch out also, along with the child controls.

    You're the ideal use case for TableLayoutPanel (MSDN). If you were only scaling the panels, Dock and Anchor would be appropriate. But since you want your controls to scale well, you're pretty much in an AutoLayout world, and likely the TableLayoutPanel. (I'm a huge fan of this, by the way, although overuse can have a negative performance impact on laying out your controls.)

    Some helpful links on using it to configure your layout to scale:

    MusiGenesis : Argh. I write software for Windows Mobile devices, and once again I just had the experience of learning about a cool .NET feature that isn't in the Compact Framework.
    John Rudy : For future visitors of this answer: I just noticed a link to my blog in this answer, and have now removed it, as I shut the blog down many months ago. I apologize for the inconvenience.
    From John Rudy
  • See following:
    http://urenjoy.blogspot.com/2008/11/make-resolution-independent-windows-app.html

    From Brij

Why is getenv('REMOTE_ADDR') giving me a blank IP address?

This PHP code...

207    if (getenv(HTTP_X_FORWARDED_FOR)) {
208        $ip   = getenv('HTTP_X_FORWARD_FOR');
209        $host = gethostbyaddr($ip);
210    } else {
211        $ip   = getenv('REMOTE_ADDR');
212        $host = gethostbyaddr($ip);
213    }

Throws this warning...

Warning: gethostbyaddr() [function.gethostbyaddr]: Address is not in a.b.c.d form in C:\inetpub...\filename.php on line 212

It seems that $ip is blank.

  • Why don't you use

    $_SERVER['REMOTE_ADDR']
    

    and

    $_SERVER['HTTP_X_FORWARDED_FOR']
    
  • on php.net it says the follwing:

    The function 'getenv' does not work if your Server API is ASAPI (IIS). So, try to don't use getenv('REMOTE_ADDR'), but $_SERVER["REMOTE_ADDR"].

    Did you maybe try to do it with $_SERVER?

    From fly.floh
  • First of all, getenv() takes a string as parameter. On line 207, you should use:

    getenv('HTTP_X_FORWARDED_FOR')
    

    ...instead of:

    getenv(HTTP_X_FORWARDED_FOR)
    

    Secondly, accessing these variables through $_SERVER is a more reliable solution, as getenv() tends to display different behaviour on different platforms.

    Also, these variables will probably not work if you are running this script through CLI.

    Try a var_dump($ip); and see what the variable contains.

  • A better solution has already been given. But still:

    getenv('HTTP_X_FORWARD_FOR');
    

    should be

    getenv('HTTP_X_FORWARDED_FOR');
    

    Yeah... sometimes computers want to have strings they understand ;-)

    From easyDaMan

what is the best xhtml-css editor with emmbeded browser (under GPL) in your opinion?

what is the best xhtml-css editor with emmbeded browser (under GPL) in your opinion? note: must be work under linux os.

  • Quanta Plus.

  • Eclipse (with the web tools project) should be able to handle this, although it may be more heavy weight than you need. As far as I know the browser included is based on Mozilla.

    Peter Boughton : Eclipse is EPL, which is not GPL-compatible. Although it might be the questioner just wants any Free Software / Open Source license, rather than specifically GPL.
    From slashnick
  • I was pleasantly surprised by Netbeans and after trying a bunch of others. Web browser and web server baked in just the way you like :)

    Mark Tomlin : I agree with everything you just said. However, Netbeans also feels some what heavy. I don't know if it's just me, but it does not feel as snappy as notepad. And, at the end of the day, ever text editor should be as fast as notepad or it's just not doing it's job well enough.
  • Aptana ... well, some people really like it, other people really dislike it.

    It's certainly capable of doing what you want though, so only way to be sure which category you'll fit into is to give it a try.

  • Aptana Studio is the best in my opinion, it's based on Eclipse and subsequently Java, so it will run on pretty much anything and has "Design" views supporting Firefox, Opera and Safari on OS X and Windows, I assume it does other browsers as well if they are installed.

    It does CSS, XHTML, JavaScript + AJAX, PHP etc. It's very comprehensive and has some very useful predictive functions. It may be a little bulky if you like a minimalist development interface. In saying that though, I like a minimalist development interface and I love Aptana Studio!

    From Matt
  • Free Komodo edit is best for this http://www.activestate.com/komodo_edit/features/

    It shows preview using Firefox engine.

    alt text

Complex profiles in maven

I've been looking at profiles in maven for selecting different sets of dependencies. This is fine when you want to build say a debug build differently from a release build. My problem is that I want to do a fair bit more than this. For my application (Mobile Java app where J2ME is just one target among many) there may be a large number of possible combinations of variations on a build.

Using some made-up command line syntax to illustrate what I'd like to see, I'd imagine typing in something like

mvn -Pmidp,debug,local-resources

What Maven does in this case is to build three different builds. What I want to do is use those three (Or more, or less) switches to affect just one build. So I'd get a MIDP-targetting debug build with 'local resources' (Whatever that might mean to me - I'm sure you can imagine better examples).

The only way I can think of doing this would be to have lots and lots of profiles which becomes quite problematic. In my example, I'd have

-Pmidp-debug-localresources
-Pmidp-release-localresources
-Pmidp-debug-remoteresources
-Pmidp-release-remoteresources
...

Each with its own frustratingly similar set of dependencies and build tag.

I'm not sure I've explained my problem well enough, but I can re-write the question to clarify it if comments are left.

UPDATE:

The question isn't actually valid since I'd made a false assumption about the way maven works.

-Pmidp,debug,local-resources

does not do 3 builds. It in fact enables those 3 profiles on one build, which was ironically what I was looking for in the first place.

  • The Maven way is to create a lot of artifacts with less complexity. I'd say your best bet is to abstract the common parts of each build into a separate artifact, then create a project for each build that defines the build specific parts. This will leave you with a lot of projects, but each will be much simpler.

    izb : I have that, but it's the selection of a specific part within a superpart that has me stumped, particularly when I want to choose between a large set of possible small parts, each doing some small thing, and each possibly a variant of another.

Cookies and Objects

I'm having trouble figuring out how to access a cookie from a compiled object. I'm trying to make a compiled (DLL) object that will check the users cookie and then compare that to a database to confirm they have the correct access.

I can pass in the cookie info fine and the component will work, but I'm trying to have the component check the users cookie as well. I'm not even sure what object to use. I've been searching all weekend and I've seen references to httprequest, httpcookie, cookie, and cookiecollection.

I can look up cookie values on the page itself using Request.Cookies("inet")("user_id") but this doesn't work in the component.

  • Objects (App_Code/ compiled dlls) can only access Request via the static HttpContext.Current object

    HttpCookie cookie = HttpContext.Current.Request.Cookies["CookieName"];
    

    (If it's not called from a web app, HttpContext.Current is null, so you may want to check for that when running in unit testing) (If this isn't App_Code, you'll need to reference System.Web)

    From martin
  • If the component is a separate DLL from your web app you'd need to pass in a reference to the Request object.

    That said why not just read/check the cookie value in your ASP.NET code before calling into your DLL. It's not such a good idea to have your business logic coupled to your web tier like this.

    From Kev

How do I use the new SVN merge-tracking?

In my existing (Pre-SVN 1.5) merge strategy, we create a copy of the Trunk (called BasePoint) at the moment of branch-creation for referencing later during the merge.

When we need to merge a branch back into the trunk, we perform 2 operations.

  1. Merge from BasePoint to LatestTrunk (Trunk has likely moved on since the original branch) into Working copy of Branch and then commit.

    At this point we typically check that the merge into the branch has not damaged anything

  2. Merge from LatestTrunk to LatestBranch back into Working copy of trunk and then commit.

Documentation suggests that I use the new reintegrate merge on the Trunk and Merge from the Branch.

Do I need to merge from the trunk into the dev branch first or is this included in the new reintegrate option?

To put it another way, does the new merge --reintegrate functionality represent 'each of my previous merges' or 'the whole operation' ?

(FWIW I am using TortoiseSVN 1.5.1)

  • I believe reintegrate does not actually do the two operations, but instead is used to merge back into trunk from an updated branch. You will still need to do the first set of merge/commit operations to update the branch first.

    Here is a link to the Subversion Book. It is possible to get this book in dead tree format.

    From the link, it sounds like using --reintegrate handles some weird cases, probably like merge usually does compared to just using straight patches (read the section "Why Not Use Patches Instead?").

  • The short answer is, You still have to do both steps.

    The SVN book explains the process for merging as:

    1. svn merge http://trunk/path while in a branch working copy
    2. svn merge --reintegrate http://branch/path while in a trunk working copy

    Notice the lack of revision numbers. This probably doesn't feel like a huge win. The new coolness is the ability to re-run the merge as you are coding in your branch, allowing you to keep the branch up to date with changes in trunk (without recording revision numbers by hand!). SVN keeps track of what needs to be merged in from trunk and what changes are unique to the branch. When you are done with the branch, --reintegrate uses that data to automatically merge only the branch changes back to trunk.

    From Nate Green
  • A good blog post about merging problems in svn (and what reintegrate does) is here.

    From teki

Modern equivalent of javadeps?

I am looking for a replacement for javadeps, which I used to use to generate sections of a Makefile to specify which classes depended on which source files.

Unfortunately javadeps itself has not been updated in a while, and cannot parse generic types or static imports.

The closest thing I've found so far is Dependency Finder. It almost does what I need but does not match non-public classes to their source files (as the source filename does not match the class name.) My current project has an interface whose only client is an inner class of a package-private class, so this is a significant problem.

Alternatively if you are not aware of a tool that does this, how do you do incremental compilation in large Java projects using command-line tools? Do you compile a whole package at a time instead?

Notes:

  1. javadeps is not to be confused with jdepend, which is for a very different purpose.
  2. This question is a rewrite of "Tool to infer dependencies for a java project" which seemed to be misunderstood by 2 out of 3 responders.
  • I use the <depend> task in ant, which is ok, but not 100% trustworthy. Supposedly JavaMake can do this dependency analysis, but it seems to be rarely updated and the download page is only sometimes available.

    finnw : Thanks. Although JavaMake doesn't parse Java source it's probably the best match right now.

How can I check if at least one of two subexpressions in a regular expression match?

I am trying to match floating-point decimal numbers with a regular expression. There may or may not be a number before the decimal, and the decimal may or may not be present, and if it is present it may or may not have digits after it. (For this application, a leading +/- or a trailing "E123" is not allowed). I have written this regex:

/^([\d]*)(\.([\d]*))?$/

Which correctly matches the following:

1
1.
1.23
.23

However, this also matches empty string or a string of just a decimal point, which I do not want.

Currently I am checking after running the regex that $1 or $3 has length greater than 0. If not, it is not valid. Is there a way I can do this directly in the regex?

  • I think this will do what you want. It either starts with a digit, in which case the decimal point and digits after it are optional, or it starts with a decimal point, in which case at least one digit is mandatory after it.

    /^\d+(\.\d*)?|\.\d+$/
    
    Patrick McElhaney : What sorry regex engine doesn't support +? I took the liberty of changing the code to what you would have had if you knew for sure + was supported.
    Glomek : I was thinking of some versions of grep, sed, and ed, but the original poster is probably using something more recent. It's one of those habits that you'll see in people who started with Unix systems that didn't use GNU tools. I also use zcat instead of the -z option to tar.
    From Glomek
  • Create a regular expression for each case and OR them. Then you only need test if the expression matches.

    /^(\d+(\.\d*)?)|(\d*\.\d+)$/
    
    From tvanfosson

What Could Cause Intermittent Issues with Images Loading in Internet Explorer 6?

I am having issues with a website that I am working on in which images and background-images fail to load in Internet Explorer 6.

Here is an example of a page on which you might experience this issue:

Example Page

So far I have looked at the following possible issues and pretty much ruled them out:

  • XML/Extraneous data in the image files (google photoshop 7 internet explorer)
  • Corrupt image files

I have not ruled out invalid markup.

I have noticed that there are validation errors in most of the pages where this problem has been reported and I am working on getting those fixed where appropriate.

The behavior I see is that the page will load and all elements other than the background image render. There are no javascript errors thrown. When using Fiddler, no request for the image is made. If the browser is pointed directly to the background-image, the cache is cleared and then the browser is pointed back at the HTML page, the background-image will load inside the HTML page.

Does anyone have any additional suggestions for ways to attack this issue?

  • is it only ie6 and not ie7 too? IE is pretty strict with html sometimes, versus firefox lets you get away with more. Not sure if this helps, but I just debugged weird IE6/7 bugs by slowly taking away content. But if it's only intermittent, as in happens with the same code on and off, that's a really weird one.

    J5 : Yes, only IE6, not IE7 (not reported or seen by me, anyway).
  • Twice now I've had people have problems with photos not showing up, and it was because they were in an incorrect colorspace, using CMYK instead of RGB.

    J5 : That is something that I had not thought to check specifically. I will do so now with a few of the images that have failed to load.
    J5 : Looks like RGB at least on this page and some other images I had saved locally from another page that had problems.
  • this is a weird issue with IE6. I just right click on the image and select "Show Picture" then the image loads properly.

    J5 : That's sometimes correct (I am not sure that the context menu gives the option for background-images) but that doesn't solve the problem from a programming perspective, only from a user perspective.
    cruizer : I think it's an IE6 bug, and something that web programming cannot address.
    From cruizer
  • The problem is the "IE6" part ;-)

    From webmat
  • I'm looking at this in IE6 and trying to replicate the problem, but I can't seem to get it to happen - it always seems to load.

    Some thoughts on things to try though as there appears to be another two classes that the background is over-riding is to try adding !important after the background assignment, so:

    div.gBodyContainer {
    background-image:url(/etc/medialib/europe/about_infiniti/environment.Par.7366.Image.964.992.direct.jpg); !important
    }
    

    Another thing to try is getting rid of all the . in the filename and cut down the length of it, shouldn't matter, but it may be causing some problems, doesn't hurt to try it anyway.

    The other thing you could try is making gBodyContainer an ID instead of a class, or give it an ID as well as a class and assign the background to the ID. Again, it shouldn't matter, but it doesn't hurt to try and see if it works, IE6 does a lot of funny things.

    J5 : Thanks for taking the time to get into the code to that degreee, Matt. The filename is generated by a CMS so I can't really get into it. I think the background-image overriding is something to look into, though.
    From Matt
  • i think in some cases you could solve this issue by loading the full size image before the request and hide it with style "display: none;" so IE6 will load the image from cache

    From Sorin

Using VS 2005 to design abstract forms

There's a famous bug in Visual Studio that prevents you from using the form designer on a subclass of an abstract form.

This problem has already been elucidated and solved most elegantly by Urban Potato; that's not the part I'm having trouble with. The trouble is, I have duplicated the technique described by Urban Potato, and included it in my project (which happens to be pretty big), and now every time I try to open the designer of my derived form, I get that Microsoft "frightfully sorry, old chap, but I'm going to have to kill you now" message (reminiscent of Otto in A Fish Called Wanda) that says "Microsoft Visual Studio 2005 has encountered a problem and needs to close. We are sorry for the inconvenience."

But here's the real kicker: if you just ignore that message, and stuff it away beyond the bottom right corner of the screen, you can carry on working, perfectly normally! Just don't click the "Send Error Report" or "Don't Send" buttons, coz then VS does close.

Still, this phenomenon is highly annoying, and I'd very much like to be able to work without the feeling that my IDE is just looking for some really nasty way to get back at me for pooh-poohing its sage advice to quit now - or else.

Further useful info: this same behavior can be duplicated on all other computers in my office; it's nothing specific to my machine. Obviously something in the project/code is upsetting the IDE, but at least I know the design pattern works, coz after I ignore the crash message, the designer works perfectly well. I just don't know where to start looking for the thing that is causing this problem.

Any ideas?

Thanks!

  • The reason your are getting this problem might be that your base form is an abstracted class. The reason why the IDE will crashes is because the IDE tries to create an instance of the the abstract class which it cannot do.

    It might be that you accidentally marked the internal class as abstract too.

    Regards,

    JvR

    Shaul : I implemented the Urban Potato solution exactly. Your answer doesn't explain why the IDE crashes, nor why it continues to function if you just ignore the crash message...
  • If it were me, I'd try attaching a debugger (maybe another instance of Visual Studio) to the instance that throws the error dialog, and see if the stack trace gives you any insights into what's causing the error.

    From Charlie

Where can I find a good collection of public domain owl ontologies for various domains?

I am building an ontology-processing tool and need lots of examples of various owl ontologies, as people are building and using them in the real world. I'm not talking about foundational ontologies such as Cyc, I'm talking about smaller, domain-specific ones.

How can I re-use an existing database connection in phpBB3?

I am using my own db for phpbb3 forum, and I wish to insert some data from the forum into my own tables. Now, I can make my own connection and it runs my query but in trying to use the $db variable(which I think is what you're meant to use??) it gives me an error.

I would like someone to show me the bare bones which i insert my query into to be able to run it.

thanks

  • Well.. You haven't given us very much information, but there are two things you need to do to connect and query to a database.

    For phpbb, you may want to read the documentation they have presented:

    http://wiki.phpbb.com/Database_Abstraction_Layer

    Here is a general overview of how you'd execute a query:

    include($phpbb_root_path . 'includes/db/mysql.' . $phpEx);
    
    $db = new dbal_mysql();
    // we're using bertie and bertiezilla as our example user credentials. You need to fill in your own ;D
    $db->sql_connect('localhost', 'bertie', 'bertiezilla', 'phpbb', '', false, false);
    
    $sql = "INSERT INTO (rest of sql statement)";
    
    $result = $db->sql_query($sql);
    
    From Cetra
  • I presumed that phpBB already had a connection to my database. Thus I wasnt going to use a new one? Can i make a new one and call it something else and not get an error?

    And $resultid = mysql_query($sql,$db345);

    Where $db345 is the name of my database connection

    Omar Kooheji : If php is like any other database I've used then you should be able to have as many connections as the database suports. Which is usually greater than 1.
    Chris : Yeah, got it. thanks to all of you for your help!
    From Chris

Access to remote computer's MSMQ gives "Remote computer is not available"

We have a windows application that runs on a server and accesses 4 other servers (all of them are members in the domain) to get the messages in each of their private queues. We've just installed a new server, and for some reason when the application tries to access that computer, it gets a "Remote computer is not available" message.
The application accesses the other servers with a user who is an admin domain user.
Has anyone encountered such a problem, or have a clue as to what could be causing it?

  • Could it be a firewall issue?

    http://support.microsoft.com/kb/183293

  • Have you fired up a packet capture tool such as Microsoft Network Monitor or Wireshark and looked at the traffic going to and from the system that gets the error? That's often the surest way to see what is going on without alot of time consuming experimentation.

    I would set up a capture from the box getting the error, run until you get the error, and immediately stop the capture. Set a filter to look at just the traffic to and from that system. If you can't install the capture tool on the box itself, make sure you place it on the network in a way that it will still be able to see all the traffic from that box. (I.e. don't put it on an adjacent port on a switch, because the switch's job is to insulate each ports traffic from each other).

    IF you see no actual traffic being sent to the remote server in question, then you probably have a naming/directory/DNS type issue. I.e. the local server can't figure out where the other one is. Since this is a Windows domain type situation, I'd start looking in Active Directory for clues.

    IF you see traffic going out to the remote server, but you never see even one packet coming back from it before the failure, then you probably have a firewall issue either on the remote box or on the route from here to there.

    IF you see traffic going back and forth to the remote server but then it stops, you'll need to dig into those packets and see what low-level error codes might be present in the traffic. Both NETMON and Wireshark have good decodes for the Microsoft protocols so you should be able to see exactly what is happening. If you're not familiar with these protocols, you might want to first capture a correctly working connection to one of the other servers so you can compare.

    From Tim Farley
  • Probably way too late for this thread, but I found the answer to this here: http://blogs.msdn.com/johnbreakwell/archive/2008/07/10/getting-msmq-messages-out-of-windows-server-2008.aspx

  • The problem is finally solved, and it was solved accidentally: Apparently there was some confusion in the DNS server, and the cache server had difficulty accessing the correct server. Our webmaster corrected al the server names, and that also solved the MSMQ problem.

    From Lea Cohen

Comparative advantages of xdoc and apt formats

What are the relative merits of the xdoc and apt formats for writing websites of Maven projects? Is one more expressive than the other? Has one got better tool support than the other?

  • The XDOC format is definitely a richer mechanism for creating documents and is required if you want to produce documents with TOC/TOF, headers, footers or footnotes (and other document attributes), since the APT format doesn't support these.

    That being said, I tend to use the APT format for almost all internal documents as I enjoy writing in the APT format. When compared to writing XDOC (with all its XML loveliness), APT is a breeze. By the same token, when I'm writing a plugin that generates content, I tend to use the XDOC format, since it's pretty easy to write software that creates the required XML.

Techniques for dynamic (algorithmic) graphics

I'm programming an application for a 32 bit processor with limited memory (512k flash, 32k RAM).

The display on this device is 128x160 with 16 bit color, which would normally consume 40k ram if I were to buffer it on my processor. I don't have that much RAM, so I'm looking for techniques, tips, tricks, ideas for generating screen data on the fly.

Things that might help:

  • Perhaps you know of a resource for this sort of limitation
  • Maybe you've generated attractive graphics on the fly
  • Is there a generic algorithm I might use to combine elements in program memory (including alpha blending) on the fly while I scan the display
  • Simple vector rendering techniques (or free (bsd/mit/apache) source)
  • ???

I do have a multiplier, but no floating point processor. The display itself has a very simple controller and memory for the display - but reads and writes are expensive so I don't want to use that as my workspace if I can avoid it.

  • In a way, you are in pretty much the same situation game developers where at the time of the Tandys, Spectrums and early PCs. So, here's my recommendation:

    You should read Michael Abrash writings on computer graphics. They were written in a time where a floating point co-processor was an optional piece of hardware, and they describe a lot of the basic techniques (Bresenham lines, etc.) used in the old (supposedly 'bad') software-rendered days.

    You can read most of his "Black Book" here.

    Additionaly, you can probably find a lot of the old BBS files that most people used back in the day to learn graphics programming here. Just search for Graphics, Lines, and what not.

    Hope that helps!

    Update: I also recall using this in my first attempts at drawing things on the screen. Can't tell how much time I spent trying to understand the maths behind it (well, to be fair I was like 15 at the time). Very good (and simple) introduction to 3D, and a very nice premier on transformations, polygon-fillers and interpolation.

    From dguaraglia
  • What kind of data will you show on the screen?

    If it is not photographic images, you could consider using a palette. For instance: A 256 color palette using 8 bits per pixel would require 20kb, (plus 256 x 2bytes for the lookup table) which at least is better than 40kb.

    From norheim.se
  • I believe the basic technique for dealing with this kind of situation is to divide the screen into narrow horizontal stripes, and only buffer two such stripes in RAM. One stripe will be displayed, while you render the next one down. When the scanning 'beam' hits the next stripe (and fires off an interrupt for you to catch), you swap the two and start drawing the next stripe down.

    A nasty side-effect of this is that that you have hard timing limits on how long you can spend on rendering each stripe. So I guess it would be tempting to stick with something boring but with predictable performance, like sprites.

    Slightly offtopic but this is how the Nintendo DS 3D hardware works. You can see it if you try to render too many polygons around the same y-coordinate - polys will randomly flicker and drop out as the screen-refresh overtakes the rendering hardware.

    Also, I'd second the other poster's suggestion that you use palettised rendering. It's very hard to do fast maths on 16bit pixels, but faster in 8bit if you're clever about how you lay out your palette.

  • Some ideas that would combine nice graphics and low memory:

    • Store backgrounds and sprites in flash.
    • Store dynamically generated graphics in RAM using a palette to half the bytes.
    • Use the windowing feature of the LCD driver to only update the part of the screen you need to.

Is it worth converting my functional JavaScript code to an object-oriented design?

I'm currently building a small web application that includes a fair amount of JavaScript. When I was prototyping the initial idea, I just hacked together a few functions to demonstrate how the application would eventually behave intending to go forward re-writing the JavaScript in an object-oriented nature.

Now that I'm getting into the implementation phase, I'm finding that creating object-oriented JavaScript for the sake of being object-oriented seems overkill - the project isn't likely to require any major modifications in the future that would warrant and object-oriented design. Instead, I'm finding that a set of concise, cohesive functions are working well.

So, with that said and with attempting to adhere to the KISS principle, when a set of functions are providing a suitable solution to a problem, are there any other reasons worth considering to convert my code into an object-oriented design?

  • No, let it be and move forward - that is more productive in my view .

    annakata : That was a bit of a shameless bump of an edit, no? Please refrain from this, it's just artificially increasing noise on the front page.
    From mm2010
  • No, although I personally find OOP more tasty, it is a means to an end, and not an end in itself. There are many cases where procedural programming makes more sense than OOP, an converting for the sake of converting, could be, as you said, overkill.

  • If your code is well structured, well laid out, and well commented, and does the job that is required of it, then messing with it for any reason other then to add features is ill-advised.

    While it might be nice to say that the program is nicely OOP etc, if it doesn't need to be changed to work then I would definetely leave it as it is.

    If it aint broke, dont fidgit with it :)

    From
  • Treat it as legacy code from now on. When you want to change something, refactor it so the code becomes easier on the mind. If you need a bit of OOP, use it. If you don't, don't.

    OOP is a hammer, please don't treat a screw-problem as a nail.

  • If it works, and it's easy to maintain, I wouldn't bother converting it for convertings sake. There must be more interesting things to do.

    From Bart Read
  • If this code is already implemented and won't require maintenance or - better yet - upgrades, stick with it. If you are going to implement it now and it could get complex, consider the OO approach.

    Experience has shown me that it's pretty easy to write and maintain procedural code while complexity is low, but after a certain threshold it starts getting exponentially more difficult to increase complexity while using procedural programming, whereas OOP, although harder to begin, keeps complexity much more manageable.

    Bottom line: if the task is simple enough or has already been implemented, keep it simple. If it might grow more complex, consider OOP.

    From schonarth
  • Just bare in mind Objects are rather expensive to create in javascript.

    Keep construction of objects to a bare minimum.

  • I would say that it is still worth reviewing your code before making a decision. The obvious downside to "re-writing" code is that there is a testing cost to ensure that your code works the same as before. Do you have any Unit tests? If not, then your testing cost is even higher. So in general, I'm against re-writing working code unless it serves another end, which is to allow you to more easily write new functionality that is now required (i.e. refactoring common functions, etc.)

    HOWEVER, any time a person says "I hacked together", I suggest it is always worth a second look at your code. Why was it hacked together in the first place? I know plenty of people say that Object Oriented code isn't an end in and of itself, but it is a methodology that after while doesn't have to be thought about either. You just sort of naturally start doing it.

    Maybe your js is relatively simple, and therefore OO scafolding is truly extra overhead. Fine. But I still suggest that you should always code review (and especially have someone else review) any code you call "hacked". Perhaps it was a Freudian slip... but it did slip.

    Tom : @Nick, No Freudian slip - the code was 'hacked' together for prototyping and demonstrating eventual functionality. I'd never release hacked code into a production environment =). Professionally, I write OO code all day so _not_ coding in OO feels almost unnatural - that's why I wanted feedback.
    From Nick

Showing a loader while Spry XMLDataset loads the data

i am using Spry (SpryData.js,xpath.js)

    var ds1 = new Spry.Data.XMLDataSet("_db/db.xml", "bildiriler/bildiri",{useCache:false});
 // load the xml tree

....

<!-- use it in a loop - 
 Sometimes the page use "ds1.loadData();" to refresh the data -->
 <div spry:region="ds1" spry:repeatchildren="ds1">
 <a href="#">{author}</a></div>

So how can i show a loader animation or "Loading text" while xml data is loading (it takes long time -about 2 sec from a slow CD-. My xml file is big 100KB )

  • I am not quite good at Spry, but can't you add a css background to the div placeholder (<div spry:region="ds1" ...) which will be shown at all time (and probably can be replaced through an observer that sets the background-image of the placeholder when the rows are loaded)...

  • Yes pretty good solution. But not exactly.

    Spry loads the data (very short) an dump them to spry:region (this takes long time) So the loader image appears in the first short time. And disappears quickly.

  • Yes. I found it (strangely, not from the docs of Spry on http://labs.adobe.com/technologies/spry) I found it from this example -> http://www.infoaccelerator.net/blog/archives.cfm/date/2006/7

    i put this line into the div tag (spry:region) :

    <p spry:state ="loading"> Loading ( text or an image ) </p>
    
  • <div align="center" spry:region="dsmain" spry:state="loading" >
    <img src="../icon/Loader/1.gif" />
    <br />please wait ...
    </div>   
    
    From loali

Which database has the best support for replication

I have a fairly good feel for what MySQL replication can do. I'm wondering what other databases support replication, and how they compare to MySQL and others?

Some questions I would have are:

  1. Is replication built in, or an add-on/plugin?
  2. How does the replication work (high-level)? MySQL provides statement-based replication (and row-based replication in 5.1). I'm interested in how other databases compare. What gets shipped over the wire? How do changes get applied to the replicas?
  3. Is it easy to check consistency between master and slaves?
  4. How easy is it to get a failed replica back in sync with the master?
  5. Performance? One thing I hate about MySQL replication is that it's single-threaded, and replicas often have trouble keeping up, since the master can be running many updates in parallel, but the replicas have to run them serially. Are there any gotchas like this in other databases?
  6. Any other interesting features...
  • Another way to go is to run in a virtualized environment. I thought the data in this blog article was interesting

    http://chucksblog.typepad.com/chucks_blog/2008/09/enterprise-apps.html

    It's from an EMC executive, so obviously, it's not independent, but the experiment should be reproducible

    Here's the data specific for Oracle

    http://oraclestorageguy.typepad.com/oraclestorageguy/2008/09/to-rac-or-not-to-rac-reprise.html

    Edit: If you run virtualized, then there are ways to make anything replicate

    http://chucksblog.typepad.com/chucks_blog/2008/05/vmwares-srm-cha.html

    nathan : I'm not sure what those links have to do with replication.
    Lou Franco : They don't -- I was suggesting an alternative that is potentially cheaper and makes any database be able to replicate. See this http://chucksblog.typepad.com/chucks_blog/2008/05/vmwares-srm-cha.html
    Charles Duffy : Part of the point of database replication is being able to at least do read queries against more than one box, sharing the load. These approaches don't help with that use case.
    From Lou Franco
  • MS SQL 2005 Standard Edition and above have excellent replication capabilities and tools. Take a look at:

    http://msdn.microsoft.com/en-us/library/ms151198(SQL.90).aspx

    It's pretty capable. You can even use SQL Server Express as a readonly subscriber.

    Philippe Grondier : SQL express can be more than a read-only subscriber. It can participate to merge and transactional replications, as long as the replication is managed by the publisher (which must be a "standard" sql server)
    From Kev
  • MySQL's replication is weak inasmuch as one needs to sacrifice other functionality to get full master/master support (due to the restriction on supported backends).

    PostgreSQL's replication is weak inasmuch as only master/standby is supported built-in (using log shipping); more powerful solutions (such as Slony or Londiste) require add-on functionality. Archive log segments are shipped over the wire, which are the same records used to make sure that a standalone database is in working, consistent state on unclean startup. This is what I'm using presently, and we have resynchronization (and setup, and other functionality) fully automated. None of these approaches are fully synchronous. More complete support will be built in as of PostgreSQL 8.5. Log shipping does not allow databases to come out of synchronization, so there is no need for processes to test the synchronized status; bringing the two databases back into sync involves setting the backup flag on the master, rsyncing to the slave (with the database still runnning; this is safe), and unsetting the backup flag (and restarting the slave process) with the archive logs generated during the backup process available; my shop has this process (like all other administration tasks) automated. Performance is a nonissue, since the master has to replay the log segments internally anyhow in addition to doing other work; thus, the slaves will always be under less load than the master.

    Oracle's RAC (which isn't properly replication, as there's only one storage backend -- but you have multiple frontends sharing the load, and can build redundancy into that shared storage backend itself, so it's worthy of mention here) is a multi-master approach far more comprehensive than other solutions, but is extremely expensive. Database contents aren't "shipped over the wire"; instead, they're stored to the shared backend, which all the systems involved can access. Because there is only one backend, the systems cannot come out of sync.

    Continuent offers a third-party solution which does fully synchronous statement-level replication with support for all three of the above databases; however, the commercially supported version of their product isn't particularly cheap (though vastly less expensive. Last time I administered it, Continuent's solution required manual intervention for bringing a cluster back into sync.

    Osama ALASSIRY : Oracle RAC is not replication, you can use materialized views, streams, oracle advanced replication and standby databases to replicate your data. Each is different and has different uses.
  • All the main commercial databases have decent replication - but some are more decent than others. IBM Informix Dynamic Server (version 11 and later) is particularly good. It actually has two systems - one for high availability (HDR - high-availability data replication) and the other for distributing data (ER - enterprise replication). And the the Mach 11 features (RSS - remote standalone secondary, and SDS - shared disk secondary) are excellent too, doubly so in 11.50 where you can write to either the primary or secondary of an HDR pair.

    (Full disclosure: I work on Informix softare.)

  • A bit off-topic but you might want to check Maatkit for tools to help with MySQL replication.

    From igelkott
  • There are a lot of different things which databases CALL replication. Not all of them actually involve replication, and those which do work in vastly different ways. Some databases support several different types.

    MySQL supports asynchronous replication, which is very good for some things. However, there are weaknesses. Statement-based replication is not the same as what most (any?) other databases do, and doesn't always result in the expected behaviour. Row-based replication is only supported by a non production-ready version (but is more consistent with how other databases do it).

    Each database has its own take on replication, some involve other tools plugging in.

    From MarkR
  • I have some experience with MS-SQL 2005 (publisher) and SQLEXPRESS (subscribers) with overseas merge replication. Here are my comments:

    1 - Is replication built in, or an add-on/plugin?

    Built in

    2 - How does the replication work (high-level)?

    Different ways to replicate, from snapshot (giving static data at the subscriber level) to transactional replication (each INSERT/DELETE/UPDATE instruction is executed on all servers). Merge replication replicate only final changes (successives UPDATES on the same record will be made at once during replication).

    3 - Is it easy to check consistency between master and slaves?

    Something I have never done ...

    4 - How easy is it to get a failed replica back in sync with the master?

    The basic resynch process is just a double-click one .... But if you have 4Go of data to reinitialize over a 64 Kb connection, it will be a long process unless you customize it.

    5 - Performance?

    Well ... You will of course have a bottleneck somewhere, being your connection performance, volume of data, or finally your server performance. In my configuration, users only write to subscribers, which all replicate with the main database = publisher. This server is then never sollicited by final users, and its CPU is strictly dedicated to data replication (to multiple servers) and backup. Subscribers are dedicated to clients and one replication (to publisher), which gives a very interesting result in terms of data availability for final users. Replications between publisher and subscribers can be launched together.

    6 - Any other interesting features...

    It is possible, with some anticipation, to keep on developping the database without even stopping the replication process....tables (in an indirect way), fields and rules can be added and replicated to your subscribers.

    Configurations with a main publisher and multiple suscribers can be VERY cheap (when compared to some others...), as you can use the free SQLEXPRESS on the suscriber's side, even when running merge or transactional replications

    nathan : great information. thanks!
  • Try Sybase SQL Anywhere

    From Zote
  • Just adding to the options with SQL Server (especially SQL 2008, which has Change Tracking features now). Something to consider is the Sync Framework from Microsoft. There's a few options there, from the basic hub-and-spoke architecture which is great if you have a single central server and sometimes-connected clients, right through to peer-to-peer sync which gives you the ability to do much more advanced syncing with multiple 'master' databases.

    The reason you might want to consider this instead of traditional replication is that you have a lot more control from code, for example you can get events during the sync progress for Update/Update, Update/Delete, Delete/Update, Insert/Insert conflicts and decide how to resolve them based on business logic, and if needed store the loser of the conflict's data somewhere for manual or automatic processing. Have a look at this guide to help you decide what's possible with the different methods of replication and/or sync.

    For the keen programmers the Sync Framework is open enough that you can have the clients connect via WCF to your WCF Service which can abstract any back-end data store (I hear some people are experimenting using Oracle as the back-end).

    My team has just gone release with a large project that involves multiple SQL Express databases syncing sub-sets of data from a central SQL Server database via WAN and Internet (slow dial-up connection in some cases) with great success.

  • I haven't tried it myself, but you might also want to look into OpenBaseSQL, which seems to have some simple to use replication built-in.