Friday, May 6, 2011

Banner Impressions Tracking - Database Design

Hi Folks

Looking for some good advice on db design for tracking multiple banner impressions.

IE I have 5 Banners over x Domains

I would like to build data on each banner on how many impressions per day per banner etc. So also be able to do lookups for other date ranges.

Would it be best to have a date per day per row or just track each impression per row.

Hope you can advise.

And thanks in Advance

From stackoverflow
  • I'd recommend to create the most flexible design that would allow you to create new reports as requirements extend in the future. You suggest that the customer wants reports on "impressions per day". What if they come in later and say "what time of the day are impressions shown most at"? How about "when are they clicked on most"?

    So the most flexible way to do this is to have 1 record for each impression, where each record is just banner_id timestamp

    Later on, you can create a stored procedure that aggregates historical data and thus purges HUGE amounts of data that you have accumulated - thus, creating reports on the level of granularity that you care about. I can imagine storing hourly data for a month, and daily data for a year. The stored procs would just write to an archive table:

    • Banner ID
    • Time interval identifier (of the month/year for monthly data, or day/month/year for daily data, etc)
    • Number of impressions
  • Why reinvent the wheel? There are plenty of free ad servers. The most notable one I've heard of is OpenX (used to be phpAdsNew). If nothing else, you can install it and see how they set up their DB.

Like to store all command-line arguments to a bash script into a single variable

Let's say I have a bash script called foo.sh.

I'd like to call it like this

foo.sh Here is a bunch of stuff on the command-line

and I'd like it to store all of that text into a single variable and print it out.

So my output would be:

Here is a bunch of stuff on the command-line

How would I do this?

From stackoverflow
  • echo "$*"
    

    would do what you want, namely printing out the entire command-line arguments, separated by a space (or, technically, whatever the value of $IFS is). If you wanted to store it into a variable, you could do

    thevar="$*"
    

    If that doesn't answer your question well enough, I'm not sure what else to say...

    Mark Biek : Easier than I thought. Thanks!
  • Have a look at the $* variable. It combines all command line arguments into one.

    echo "$*"
    

    This should do what you want.

    More info here.

  • The command echo will take all arguments and print them out:

    echo Here is a bunch of stuff on the command-line
    

    You should quote the arguments if you have special characters.

  • If you want to avoid having $IFS involved, use $@ (or don't enclose $* in quotes)

    $ cat atsplat
    IFS="_"
    echo "     at: $@"
    echo "  splat: $*"
    echo "noquote: "$*
    
    $ ./atsplat this is a test
         at: this is a test
      splat: this_is_a_test
    noquote: this is a test
    

    The IFS behavior follows variable assignments, too.

    $ cat atsplat2
    IFS="_"
    atvar=$@
    splatvar=$*
    echo "     at: $atvar"
    echo "  splat: $splatvar"
    echo "noquote: "$splatvar
    
    $ ./atsplat2 this is a test
         at: this is a test
      splat: this_is_a_test
    noquote: this is a test
    

    Note that if the assignment to $IFS were made after the assignment of $splatvar, then all the outputs would be the same ($IFS would have no effect in the "atsplat2" example).

Gravatar for Iphone? How do I generate a hexadecimal MD5 hash?

I'd like to use gravatar in my iPhone application. Is there anyway to generate a hexadecimal MD5 hash in Objective-C for iPhone? Using openssl on iPhone is a no-go.

From stackoverflow
  • This is how I did it before I removed it from my app:

    #import <CommonCrypto/CommonDigest.h>
    
    NSString* md5( NSString *str ) {
      const char *cStr = [str UTF8String];
      unsigned char result[CC_MD5_DIGEST_LENGTH];
    
      CC_MD5( cStr, strlen(cStr), result );
    
      return [[NSString
          stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
          result[0], result[1],
          result[2], result[3],
          result[4], result[5],
          result[6], result[7],
          result[8], result[9],
          result[10], result[11],
          result[12], result[13],
          result[14], result[15]
          ] lowercaseString];
    }
    

    It's only fair to add that I didn't write this myself. I found it somewhere on the internet but I didn't record where.

  • The code I used for generating the necessary MD5 hash is up on my github repository, in the CommonCrypto subfolder. There are a bunch of similar routines in there which will either show you how to use CommonCrypto or how to format strings of hex byte values, base-64, etc.

    A potentially better way of generating the string would be:

    NSMutableString * str = [[NSMutableString alloc] initWithCapacity: 33];
    int i;
    for ( i = 0; i < 16; i++ )
    {
      [str appendFormat: @"%02x", result[i]];
    }
    NSString * output = [str copy];
    [str release];
    return ( [output autorelease] );
    

    If you're going to use the code in the answer above, however, I'd personally suggest changing the %02X's to %02x and forgoing the -lowercaseString call completely-- might as well generate the hex values lowercase to start with.

How can I duplicate a website's settings in IIS7?

I'm going mad trying to get an ASP.NET application running on IIS7 (Server2008).

I have one web site set up in IIS7 which works fine. I'm trying to create another one now but I only get 404s for all .aspx files. The Handling Mappers are all different from the working site's. Is there any way I can duplicate the working site's settings so I don't have to go through 50 mappings manually.

Or is there a better way to get the correct settings?

From stackoverflow
  • For IIS 5 (and 6?), Microsoft had a free download called MetaEdit. It was used for just this - backing up and restoring an IIS configuration from machine to machine. Check MS's web site to see if there is an updated version for IIS 7.

  • If you are merely trying to re-install the default ASP.NET mappings, the best way to do that is use

    aspnet_regiis.exe
    

    which is in the %windir%\Microsoft.NET\Framework\v___ folders (depends on which version you're trying to set -- looks like 3.5?)

    Use the documentation at http://msdn.microsoft.com/en-us/library/k6h9cz8h.aspx to see whether you want to use the -i, -r, or -s option.

    Mr. Flibble : This didn't seem to make any changes. Everything is already setup as per aspnet_regiis.exe.
  • IIS7's default configurations are held in c:\windows\system32\inetsrv\config\applicationHost.config

    Any changes you make on a per site/application basis are stored in the web.config for that site/application.

    You should be able to simply copy the files onto the second server.

    Mr. Flibble : Copying the section from a working site to the new one made it work. Cheers.

Working with a hashtable of unknown but similar objects (C#)

I have a hash table which can contain any number of objects. All of these objects implement some similar methods / properties and some of their own.

For example all objects in the hashtable may have a method called PrintText taking a single parameter of type string. All the objects are however instantiated from different classes.

Is it possible for me to pull out a particular object from the hashtable by its key without knowing its type before runtime, and access all its own methods and properties (not just the common ones)?

Normally I would do something like,

MyClass TheObject = MyHashTable[Key];

But the object being pulled out could be derived from any class so I cannot do that in this instance.

From stackoverflow
  • You could define an interface containing the common methods and properties, and implement this interface in all your classes. Then you can easily access these methods and properties.

    But to access the specific methods of an object (not contained in the interface), you will need to know the type of the object.

    Update:

    It's not clear from your question, but when you write about a hashtable, I assume you mean the Hashtable class. In that case, you should have a look at the generic Dictionary class (available since .NET 2.0). This class will make your code typesafe and saves you from a lot of type-casting, e.g:

    IMyInterface a = new MyObject();
    
    // with Hashtable
    Hashtable ht = new Hashtable();
    ht.Add("key", a);
    IMyInterface b = (IMyInterface)ht["key"];
    
    // with Dictionary
    var dic = new Dictionary<string, IMyInterface>();
    dic.Add("key", a);
     // no cast required, value objects are of type IMyInterface :
    IMyInterface c = dic["key"];
    
    Craig Bovis : Exactly what I needed, thanks Martin. I didn't realise Interfaces could be used in this way!
  • To solve problems with common methods and properties you can solve by making your classes to implement the same interface. However, I don't see how you can access non-common members. You can try to use Reflection.

  • dynamic in C# 4. Reflection in earlier versions.

    EDIT: In some cases, defining a common interface can be both an efficient and clear way of achieving something of the nature you describe. ('inspired' by the accepted answer and/or others mentioning it - can't remember the timeline)

    Marc Gravell : While duck-typing will work, an interface (as per the accepted answer) would be vastly preferable. Dynamic should be seen as a last resort in most cases (with the exception of COM/DLR where it is much more useful). But +1 for mentioning it.
    Ruben Bartelink : Yep, agree. (Also I nabbed the reference to interfaces from other responses, but didnt declare it by putting an EDIT: in front of the text (though I was open in the description of the edit!))
  • You can say:

    object theObject = MyHashTable[Key];
    

    Then you can say:

    theObject.GetType()
      .GetMethod("PrintText")
      .Invoke(theObject, new object[] {"paramvalue"});
    

UIView animations interacting badly

Hi--

I'm seeing what appears to be interaction between separate animations, and I'd really appreciate any suggestions to eliminate this effect.

Basically: I've got an iPhone app which includes a button 'a' on the root view. Tapping 'a' pushes a view on a navigation view controller stack, with a flip animation. The pushed view has a button to pop the view back to the root.

The underlying code:

- (IBAction)pushOneView{
TheAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight 
                    forView:delegate.navigationController.view cache:NO];
[delegate.navigationController 
            pushViewController:oneViewController animated:NO];
[UIView commitAnimations];

}

This seems to work fine, and the animation is quite smooth.

The root view also includes a subview ('panelView'), and another button, 'b'. panelView can display either of two other subviews--tapping 'b' swaps between those subviews, with a spin animation. The code:

-(IBAction)swapPanels{
UIViewController *coming;
UIViewController *going;
float rotation;

if (self.aPanel.view.superview == nil) {
    coming = aPanel;
    going = bPanel;
    rotation = 3.14;
}
else {
    coming = bPanel;
    going = aPanel;
    rotation = -3.14;
}

// First half of spin
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.25];
CGAffineTransform swirlTransform = CGAffineTransformMakeRotation(rotation);
panelView.transform = swirlTransform;
[panelView setAlpha:0.1];
[UIView commitAnimations];

// Finish spin
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.25];
CGAffineTransform secondTransform = 
                        CGAffineTransformRotate(swirlTransform, rotation);
panelView.transform = secondTransform;
[panelView setAlpha:1];
[UIView commitAnimations];

// Swap the panels
[going.view removeFromSuperview];
[panelView insertSubview:coming.view atIndex:0];

}

This also seems to work fine. Each of the swappable panels contains a picker and some labels.

However, I notice that the 'a' transition becomes slow and jerky if the 'b' transition has been executed before it. In other words, if I start the app, run 'a' back and forth several times, it runs smoothly. Then exercise 'b' back and forth a few times. Then try 'a' again...'a' is now jerky, and will remain so until an app restart.

This is 100% repeatable. It is subtle using the simulator, but quite obvious on a device. I have tested for leaks--none are shown by leaks tool. If the animation is removed from the 'b' operation (just comment-out the animation steps), the effect on 'a' is not observed after the 'b' subview swap is exercised. If the pickers are removed from the swappable panel nibs, the effect is similarly eliminated. If the 'a' animation transition is set to cache, then after 'b' it does not stutter in the middle, but seems to ignore animating, simply swapping the view (this may be a matter of perception).

In case I'm not clear: I am NOT triggering these separate operations at the same time. Animation 'a', after 'b' has been executed--and completed--is not the same as if 'b' had never been executed. Is there clean-up I should be doing after an animation? Is my subview-swapping code flawed? Or...?

Thanks in advance for any suggestions.

From stackoverflow
  • You do have two overlapping animations in your 'b' section. When you create an animation using a begin / commit block, it gets handed off to a background thread to perform. In your 'b' section, the two animations that should be sequential are actually being fired off at nearly the same time. This can cause bizarre behavior, possibly like what you are seeing.

    I'd recommend adding a callback in your first animation to a delegate method using code like the following:

    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(rotationAnimationFinished:finished:context:)];
    

    within your first animation block in 'b' (the "First half of spin" part). Then you need to define the callback method within your class, in this case

    - (void)rotationAnimationFinished:(NSString *)animationID finished:(BOOL)finished context:(void *)context;
    

    Within that delegate method, which will be called when the first part of the spin animation has finished, place the remaining code from your 'b' method (everything after your "Finish spin" comment).

    By separating apart these animations, that might prevent the weirdness you're seeing.

    jpb : Thanks much for the suggestion, Brad, but I don't think we're there yet. While I understand your point, one test of it is to eliminate the second half of the 'b' animation entirely...and doing so makes no difference in the behavior of the 'a' animation.
  • Brad's answer does seem to have lead me to a solution: the symptoms continued to suggest that something about running those 'b' animations left the system in a different state than when it started. Finally, it occurred to me that the transform property of the panelView was left set after the 'b' animations...and perhaps that impacted further animations of a superview containing panelView.

    So I set up method as Brad suggested, to execute once the 'b' animations were complete--but all that method does is set the panelView transform back to the default: CGAffineTransformIdentity:

    • (void)spinFinished:(NSString *)animationID finished:(BOOL)finished context:(void *)context { panelView.transform = CGAffineTransformIdentity; }

    With this in place, post-'b' executions of the 'a' animation appear to be back to normal. So thanks again, Brad, for your help here. It is much appreciated.

nonatomic property in an NSOperation object (threaded environment), when to use it?

I'm still getting the hang of working in a threaded environment using NSOperation, and I'm interested in understand if using the 'nonatomic' property is even worthwhile if you're subclassing NSOperation?

If your defaultQueue is set to 1, is the additional overhead of nonatomic worth it? Might it be needed if you're executing more than 1 thread per operation queue?

Thanks for providing a solution on understanding this property in a threaded environment better.

From stackoverflow
  • If you have an object (or a property of that object) that you can guarantee it not accessed from multiple threads at the same time, then you can avoid potential overhead of atomic access to that property by using nonatomic. In the simplest case of creating an operation and enqueuing it on an NSOperationQueue, each NSOperation instance will either be getting set up in the invoking thread or running in a single background thread; so at any one time, only a single thread should be accessing it.

    The more general question of when nonatomic is useful depends in part on whether you are running with garbage collection enabled. According to the Objective-C release notes:

    Access to properties is atomic by default. This is trivial under GC for almost everything and also trivial under non-GC for everything but objects and structures. In particular atomic access to retained objects under non-GC conditions can be expensive. As such, a nonatomic property attribute is available.

Need help appending one wchar_t to another! C++

I have tried wcscat() but i get a runtime access violation.

wchar_t* a = L"aaa";
wchar_t* b = L"bbb";
wchar_t* c;
c = wcscat(a, b);

Can somebody tell me what is wrong here? Or another way to solve my problem? Thanks

From stackoverflow
  • Use c++'s built in wstring:

    #include <string>
    using std::wstring;
    
    int main()
    {
        wstring a = L"aaa";
        wstring b = L"bbb";
        wstring c = a + b;
    }
    

    wcscat is for c-style strings, not c++ style strings. The c way to do this is

    wchar_t* a = L"aaa";
    wchar_t* b = L"bbb";
    wchar_t c[7];
    wcscpy(c, a);
    wcscat(c, b);
    

    EDIT: Wow, now that I edited it, it makes it look like I copied one of the answers below.

    Greg Hewgill : It must have been the correct solution then! :)
  • The wcscat function appends the second argument onto the string buffer in the first argument. It looks as though this might be your first experience using strings in C. You could make your example work by doing the following:

    wchar_t* a = L"aaa";
    wchar_t* b = L"bbb";
    wchar_t c[7];
    wcscpy(c, a);
    wcscat(c, b);
    

    When using C string manipulation functions, you must ensure that you allocate enough buffer space for the string operation begin performed (the C runtime won't do it for you). In this case, it means the c buffer must contain enough space to hold the result string. I have precalculated that the result is 6 characters long plus the trailing null, which means I need to allocate 7 characters.

  • wcscat doesn't create a new string - it simply appends b to a. So, if you want to make sure you don't cause a runtime access violation, you need to make sure there's space for b at the end of a. In the case above:

    wchar_t a[7] = L"aaa";
    wchar_t b[]  = L"bbb";
    wchar_t* c;
    c = wcscat(a, b);
    

    You can still get a return value from the function, but it will simply return a.

  • Why not use std::wstring? Here's a great answer explaining it.

    Here is your code with wstring:

    #include <string>
    
    int main(void)
    {
        std::wstring a(L"aaa");
        std::wstring b(L"bbb");
    
        std::wstring c = a + b;
    
        return 0;
    }
    

    To answer your actual question though, you are using wcscat incorrectly. Try like this:

    #include <string>
    
    int main(void)
    {
        // constant wchar_t
        const wchar_t *a = L"aaa";
        const wchar_t  *b = L"bbb";
    
        // buffer for concatenation, could change to a call to new
        wchar_t c[50] = {0};
    
        // add a to c, then b to c (ending up with a + b)
        wcscat(c, a);
        wcscat(c, b);
    
        // would free memory here if you used new
        return 0;
    }
    

What does the error message "No provisioned iPhone OS device is connected." mean?

Yesterday I testet a lot on my device. Suddenly I get this error message when I hit Build & Go in Xcode. First, it asks me if it's ok to sign with my key. I click yes, and then that error message appears. My iPod is connected as usual, iTunes starts automatically and I close that to prevent interruptions.

I tried restarting Xcode. Doesn't help. My Apple Dev Enrollment is brand new. Any idea what the problem might be?

Edit: In Window > Organizer I can see this message:

Your mobile device has encountered an unexpected error (0xE8000001) Try disconnecting and powering off the device; then power the device on and reconnect it.

I restarted it with power-off, but I still get that message.

From stackoverflow
  • I've had this happen before as well. I'm not sure what caused it either, but in most instances powering the phone off and back on again solved the problem.

  • So, the final solution to that problem:

    • Check if the provisioning profile is still in ~/Library/MobileDevice/Provisioning Profiles
    • If not, go download it from the iPhone Developer Program website

    • Device power off (really off...you do that by holding that big standby button pressed for a few seconds)

    • Quit Xcode (quit really: Check in Dock that it's not running)

    • Activate device (power on), wait until it's bootet completely

    • Plugin to your mac

    • Wait until that harrying iTunes starts automatically, wait until it has synched your iPhone / iPod touch, and then switch iTunes off (really off).

    • Start Xcode

    • Build & Go

    • Pray & have fun (hopefully)

  • I was going to mention that dev certs eventually expire, until I saw you mention "My Apple Dev Enrollment is brand new."

    Posting anyway in case it helps others... If your setup stops working out of the blue, you may have to download fresh certificates.

    JOM : That's it, cert expired! Thanx!
  • Thanks. It worked for me after restarting the iPod

  • if the ipod is brand new u have to check the (use for development) option in organiser

Pdflib Java api

Hello,

Does somebody knows a high level Java API that wraps the pdflib (horrible) Java API that is actually easy to use.

To clarify, I have to use pdflib (my company uses it), so I need a wrapping API, not other alternatives.

Thanks

Tal

From stackoverflow
  • I don't know anything about pdflib but for a nice Java PDF API have a look at iText.

  • There are a few PDF libraries for Java that I know of.

    If you have a specific example of what you are trying to do it that would help.

Any big sites using Client Side XSLT?

Lately, I've been pondering the somewhat non-mainstream architecture of building raw XML on the server side, and then using an XSLT stylesheet on the client to transform the XML into the full UI. Of course, a fallback mechanism would have to exist if the client was not capable of client side XSLT, in which case we'd just transform it for them on the server side.

I'm already intimately familiar with XSLT, and this approach seems to be a clean separation of presentation and content, completely forcing the data into XML, and using XSLT for presentation.

I'm also aware that this does add an extra layer of complexity to the application, which is just another moving part that can fail.

My question is: are there any big name or big traffic sites using this approach, and if so: what limitations/lessons learned did you take away from it?

Thanks Internet, Zach

From stackoverflow
  • I couldn't tell you in detail how it's implemented, but World of Warcraft is pretty big and high traffic, and their web site is implemented as you describe.

    nickf : you can see the implementation detail for yourself: http://www.worldofwarcraft.com/new-hp/layout/layout.xsl
    zachleat : Try going to the page in Safari, then view the source. It doesn't use the top level node, instead has . The stylesheet prolog is still there, is Safari showing the output of the transformation?
    Ben Blank : @zachleat: The WoW site uses UA switching to determine whether to serve XML with stylesheet instructions or pre-transformed HTML. IIRC, only IE6+ and FF2+ are served XML.
    EricLaw -MSFT- : Indeed, Blizzard's sites do this. Unfortunately, it works poorly in IE6, 7, and 8 because MSXML has the tendency to hang and deadlock when applying XSLTs. That problem has only been fixed in Win7 thus far.
  • I don't know any big public Websites that use client-side XSLT transform (well, except World of Warcraft mentioned by Joel :-). So I cannot answer your question directly.

    However, from time to time I was pondering the same question myself, and I have a hypothesis that the number of such sites on Internet must be very close to zero. :-)

    The short version of my theory behind this hypothesis is this: with the exception of some pretty exotic cases, provision of client-side XSLT option is simply not worth the trouble. :-)

  • The company I worked at back in 2001 released a server product that implemented exactly the architecture you describe. We had very good success offloading the processing onto the clients. Furthermore, doing client detection using the HTTP user agent we were able to use the server side XSL processing to cater to very specific clients like Japanese cell phones. I think the sites/services/products that use this technique do it quite transparently to the clients. However, I think the trend lately is to do the processing server-side so that you do not have to rely nor test on the particular implementations of XSL for a variety of clients and you get support for some XSL extensions that you would not be able to use when supporting the vast majority of browsers.

    I know I'm not directly answering your question of naming some big name sites, but I hope I'm offering something of value to the problem. So, basically my point is that unless the performance saving of doing your template processing is more valuable than having to QA, support and development for three or four browsers without extensions, then you should stick with server-side processing.

  • I agree with Elijah's answer. I think that using client side XSLT is a difficult job. You have to do a lot of QA for it. But whereas with server side, you don't that QA. You have to take care of all type of clients and possibilities while using client side. There may be a possibility that your code may break while using client side XSLT.

  • I may be biased when I say this, but working on a web based app that does this, I hate it. The only reason it is even viable is because the clients are only IE6+. Even then, there are issues with it. I find XSLT to be very difficult and would suggest if you are going to do this to get a good tool for debugging and editing XSLT. Why not use JSON and jquery? Must more standard and less client side variability.

  • Like other people have mentioned, Blizzard has many sites that are client side xsl. I would recommend avoiding client side xsl. It is a really cool idea, but there are many unusual bugs that you need to work around.

    In Firefox, any javascript that uses document.write will destroy the DOM. Also, the noscript plug-in for firefox stops client side xsl. In both cases, the user will see nothing. There doesn't seem to be a way to detect this kind of error, so a fall back will not work.

    In IE, if you have anything that does a 30x redirect to something of a different origin (going from http to https or crossing sub domains), you will get an error for violating the same origin policy. You did not really violate the same origin policy, but IE acts like you did. For example, if you go to http://foo.example.com/login and that does a 302 redirect to https://bar.example.com/login.xml, IE will treat the xsl as if it came from bar.example.com and it will treat the xml as if it came from foo.example.com. So you will need to revert to something like a meta refresh for your redirects.

    These are the things that I came up with off the top of my head. It is a neat idea, but be aware of these issues.

    Chad Scira : interesting, had no idea about that one. These are rare cases though. I feel client-side XSLT is the future. Handing the template to the browser and having them fill it up with data is how the internet should work. I love that blizzard uses it on most of their sites :). But like anything clientside... there's browser compatibility issues (css, js...)
    harpo : +1 for the IE tip.
  • I am currently running a few minor pages with client side XSLT, all in swedish though (lillemanfestivalen.se, resihop.nu and beta projects). My biggest concern were that google did not index my pages content, just the XML without the transformation. However, since I launched resihop.nu a week ago, it shows up on google with transformation! :D

    Now my other concern is facebook and other social sites, that do not understand how to handle it. I still, however, think the up sides are greater than the down sides. The fabulous speed and separation I get is awsome. And with resihop.nu, I dont even develop a separate API, I just point developers to the site itself. (More work will be needed there to make it good though)

File rewrite not working?

test.php

<?php
$filec = fopen('test.txt','w');

$arr = file('test.txt');

foreach ($arr as $key => $value) {
    fwrite($filec,$value);
}

fclose($filec);
?>

test.txt

asdjlaksjd
asdhfwejkyhtjkre
jfdhgdjkf'hgjldsff
sfjnkbnm,cv
sm,nxcm,b,
sdjlhfskld
jfsdfwerwlur
slfdjsdkljfklsdjf

When I run test.php, test.txt is emptied. Does anyone know why?

Echoing $value, etc seems to work.

From stackoverflow
  • When you call fopen with w, you are effectively clearing the file. When you call file, you're reading from that cleared file.

    Put the file call before the fopen one.

    a2h : Oh wow, how did I not notice that? Thanks.

In WPF, how can I animate the width of a Window?

Hello everyone,

As the title says, how should I go about animating the height or width of a Window? I can do something like:

var wdw = new Window();
var ani = new DoubleAnimation(wdw.Width + 150, TimeSpan.FromSeconds(0.2));
wdw.Show();
wdw.BeginAnimation(SomeDependencyProperty, ani)

...but Width doesn't seem to be a dependency property. Am I missing something? Is there a correct way to do this?

Thanks in advance!

From stackoverflow
  • Nevermind, my problem was that I was doing a wdw.ShowDialog() (which my example didn't have)

What are the issues to be aware of when updating Flash 8 AS2 content for Flash 10

I have a large number of Flash projects that have been written in Flash 8 (AS2). I recently acquired Flash CS4 to update this content to the new version. I have some new functionality to add and want to take advantage of some new features in Flash 10 (local file access etc). I have already encountered a number of issues when opening my files in CS4, can anyone add to this list?

  1. CS4 did not recognise Flash 8 project file format and could not open them
  2. Remoting classes I was using in Flash 8 (import mx.remoting) could not be loaded
  3. All actions on buttons or movie clips are not supported
  4. Text field variables are not supported

I am sure there will be more, what else do I need to look out for? Are there any other pitfalls that I need to be aware of?

Thanks guys

p.s. this is handy - http://www.adobe.com/devnet/actionscript/cookbook/

From stackoverflow
  • Flash CS4 retains backwards compatibility with AS2 and pretty much all functionality of Flash 8, though transitioning between the two isn't necessarily smooth. If you were to just open a Flash 8 FLA in Flash CS4 and publish it using the publish settings Flash CS4 automatically assigns (Flash Player 10 with ActionScript2), you should be OK.

    However, if you are trying to publish your Flash 8 FLAs to FP10 with AS3, you're going to encounter all of the problems you mentioned above. This is because AS3 is not merely an upgrade of AS2, but an entirely different language (OK, not as drastic as that sounds, but you get the idea). A lot of the new features in Flash CS4 (IK, new Motion, etc) won't work with AS2 and requires you to publish to AS3. This is likely the source of your problems; you're trying to combine AS2-only features (in this case, AS2 code) with AS3-only features. To do both, you have to re-write your AS2 code as AS3. Unfortunately, there's no quick fix to do this.

    My recommendation is that you go ahead and learn AS3. It may be a bit difficult to wrap your head around coming from AS2, but it is a much more complete language and will last you a long time.

LINQ2SQL: How do I declare a member variable of type var?

I have a class like this

    public class foo
    {

        private void getThread()
        {
         var AllThreads = from sc in db.ScreenCycles
                          join s in db.Screens on sc.ScreenID equals s.ScreenID
                          select s;
        }
    }

I want to make the AllThreads variable a class variable instead of a method variable. Like this...

public class foo
{
    var AllThreads;
    private void getThread()
    {
       AllThreads = from sc in db.ScreenCycles
                          join s in db.Screens on sc.ScreenID equals s.ScreenID
                          select s;
    }
}

How ever it wont let me declare a class variable of type var.

How to I achieve this?

From stackoverflow
  • You could do it like this:

    public class foo {    
      IEnumerable<string> AllThreads;    
    
      private void getThread() {
         AllThreads = (from sc in db.ScreenCycles
                          join s in db.Screens on sc.ScreenID equals s.ScreenID
                          select s.Screen1 + " " + sc.Thread);
      }
    }
    

    Updated per Joel's suggestion.

    Joel Coehoorn : Close, but it's best to avoid the .ToList().
    Joel Coehoorn : Also, I don't think he's returning Strings.
    Jimmie R. Houts : ah, he changed the question... otherwise I would have done the same as @The Lame Duck
  • The initial var is defining an anonymous class. In order to do what you what you have to define the class.

    But...you could probably just do this:

    List<string> AllThreads;
    
  • var can only be used as a local declaration. If you want to use the type returned from a LINQ expression you must have build an object.

  • To preserve your original code, try this

    public class foo
    
        IEnumerable<ScreenCycles> AllThreads;
        private void getThread()
        {
           AllThreads = from sc in db.ScreenCycles
                              join s in db.Screens on sc.ScreenID equals s.ScreenID
                              select s;
        }
    
    }
    
    Joel Coehoorn : Looks like he's selecting "Screens" rather than "ScreenCycles"
    Serapth : Is it worthwhile pointing out that the original class design is flawed, and you generally shouldnt return IEnumerable? Granted, exactly what you answered is valid to the question asked, but in the end, the advice is fundamentally flawed ( as a direct result to the question ).
    Joel Mueller : I couldn't disagree more. Generally, you SHOULD return IEnumerable, unless you have a good reason to return a less-generic type. However, storing an IEnumerable that depends on a live database connection without first calling ToArray or ToList on it is probably not such a good idea.
  • You can't use var at the class level. You need to provide an explicit type if it's not going to be initialized right away.

    Assuming "s" is of a type name "Screen":

    public class foo
    {
        IEnumerable<Screen> AllThreads;
        private void getThread()
        {
           AllThreads = from sc in db.ScreenCycles
                              join s in db.Screens on sc.ScreenID equals s.ScreenID
                              select s;
        }
    }
    
  • As many of said, you can't use var. Refactor your code to use Linq types.

    public class foo 
    {
        ScreenCycle[] allThreads;
        private void getThread() 
        { 
            allThreads = (from sc in db.ScreenCycles join s in db.Screens on sc.ScreenID 
                         equals s.ScreenID select s).ToArray(); 
        } 
    }
    
  • OK, this isn't an answer, just a relative newbie to stackoverflow question, which this thread illustrates quite well.

    The code markup tools on this site are seriously... um, unique. What I dont understand in this particular case is, why are all our comment codeblocks very very long? Is it something the OP did? I tired various edits on my earlier example, and for some reason the textbox my code was in was much longer than its contents. ( IE 8 )

  • http://blogs.msdn.com/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx

Automatically updating a file with Revision from TFS?

I'm quite new to TFS (actually I only use it because I have some projects on CodePlex and did not want to go through svnbridge), and I'm looking for something equivalent to the $Revision$ parameter in SVN.

Essentially on checkout, I want to update a file to contain the newest Revision number, to be displayed as Version number (just like at the bottom of SO).

Is there anything already built-in in msbuild of .net 3.5 SP1, or any official/standard msbuild task, or even something equivalent of just dropping $Revision$ and having the TFS client do the magic on checkout?

From stackoverflow
  • Keyword expansion is not currently supported in TFS. This often takes people by suprise. Below are a couple of blog posts on the topic, you will also find a link there to take you to the Microsoft site if you want to vote for the feature. I know that it is something that the Team get asked for from time to time - but they have yet to come across anyone that actually needs keyword expansion anymore, just a lot of folks are kinda just used to it.

    Anyway - have a read and see what you think.

    Michael Stum : Thanks. Well, I agree on the questionable usage scenario of many keywords, but Revision (or any other way to get the Changeset Number) is one that is really useful when doing regular builds.
  • Michael,

    From within a Team Build you can access the changeset number being built using the $(SourceGetVersion) variable. You could override the AfterGet or BeforeCompile extensibility targets and push the contents of this variable into whatever files you need it in.

    Regards,

    William D. Bartholomew (Team System MVP)

Can someone show me a diagram of how view controllers work?

Can someone show me a diagram of how view controllers work in cocoa (obj-c).

I just want to understand because they are confusing me

Thanks!

From stackoverflow
  • I don't think a UIViewController can be summed up in a diagram.

    What specifically is it that you are having difficulty with? The navigation from one controller to another? The stacking aspect of a NavigationController? Or the structure of your look and feel inside a ViewController?

    The question is so open ended, I don't think it can be answered in a single thread on this site. I would point you toward Lecture 6 of the Stanford class on iPhone programming. Both the lecture notes and the lecture itself (with sample exercises) can be found at: http://www.stanford.edu/class/cs193p/cgi-bin/index.php

    Daniel Kindler : thanks, I'll watch that video. But I'm just having trouble understanding what is it that the view-controller does?
    danielpunkass : Agree with mmc. You should try to seek out more broad-spectrum explanations of iPhone programming in general, then return with a more specific question if you still don't understand.
  • The stanford link is a great reference.

    Generally, a view controller provides the "glue" to your application. It should get/process the data from your Model(s) and hand it off to the view. Almost all of the application logic will be in the View Controller.

    The following text is from the Cocoa Fundamentals Guide by Apple:

    Controller Objects Tie the Model to the View

    A controller object acts as the intermediary between the application's view objects and its model objects. Controllers are often in charge of making sure the views have access to the model objects they need to display and act as the conduit through which views learn about changes to the model. Controller objects can also perform set-up and coordinating tasks for an application and manage the life cycles of other objects.

    In a typical Cocoa MVC design, when users enter a value or indicate a choice through a view object, that value or choice is communicated to a controller object. The controller object might interpret the user input in some application-specific way and then either may tell a model object what to do with this input—for example, "add a new value" or "delete the current record"; or it may have the model object reflect a changed value in one of its properties. Based on this same user input, some controller objects might also tell a view object to change an aspect of its appearance or behavior, such as disabling a button. Conversely, when a model object changes—say, a new data source is accessed—the model object usually communicates that change to a controller object, which then requests one or more view objects to update themselves accordingly.

    Controller objects can be either reusable or non-reusable, depending on their general type. “Types of Cocoa Controller Objects” describes the different types of controller objects in Cocoa.

    A relevant diagram would be the relationship between the Model,View, and the Controller (again courtesy of apple):

    MVC Diagram

    Daniel Kindler : thanks man! that waas a help

Rails/Passenger/Unknown Content Type

We have the following situation:

  1. We invoke a url which runs an action in a controller. The action is fairly long running - it builds a big string of XML, generates a PDF and is supposed to redirect when done.

  2. After 60 seconds or so, the browswer gets a 200, but with content type of "application/x-unknown-content-type" no body and no Response Headers (using Tamper to look at headers)

  3. The controller action actually continues to run to completion, producing the PDF

This is happening in our prod environment, in staging the controller action runs to completion, redirecting as expected.

Any suggestions where to look?

We're running Rails 2.2.2 on Apache/Phusion Passenger.

Thanks,

From stackoverflow
  • I am not 100% sure, but probably your Apache times out the request to Rails application. Could you try to set Apache's Timeout directive higher? Something like:

    Timeout 120
    
  • I'd consider bumping this task off to a job queue and returning immediately rather than leaving the user to sit and wait. Otherwise you're heading for a world of problems when lots of people try to use this and you run out of available rails app instances to handle any new connections.

    One way to do this easily might be to use an Ajax post to trigger creating the document, drop this into Delayed Job and then run a 10 second periodic check via ajax informing the waiting user of the jobs status. Once delayed_job has finished processing your task in the background and updated something in the database to indicate it is complete, then you can redirect the user via ajax to the newly created document.

Do we really need NULL?

Is there an actual need for NULL or not? In most of the OO languages i have programmed in there has always been a way to set a variable to a NULL value which lead to all sorts of funny problems.

What are your thoughts?

From stackoverflow
  • It's possible to design a language that doesn't have a NULL but instead uninitialised values point to a singleton dummy object that doesn't actually do anything. You could compare pointers against the reference of this dummy object, and calls to methods on the object would result in no action or a runtime error.

    This technique is hard to implement for statically typed languages like C++ or Java.

    Drew Hoskins : Yeah, apparently (dynamically-typed) Objective-C does nothing when you call a method on a nil object, though it does have nil.
  • NULL is a little like God. If it didn't exist, we would wind up having to create one. Something has to represent the value of a reference that is unassigned (whether that be because it was never assigned or it was cleared at some point). The only alternative is to use an object that, effectively, substitutes for NULL. The problem with that is that if you did all that to avoid the NullPointerException, now you're going to simply replace it with UnexpectedObject exception or ClassCastException or what not.

    Charlie Martin : Definitely +1 for the Voltaire reference.
    Miky Dinescu : +1 ha ha.. that's sort of funny, but true I guess..
    Daniel Earwicker : NULL is a little like man also. For God (Anthony Hoare) created man (NULL) and then a few years later wished he hadn't.
  • In languages with garbage collection where variables are actual storage locations (as opposed to Python's labels), the NULL value is required to allow memory to be freed in a clean manner before the end of the variable's scope.

    Also, even many algorithms written in pseudo code make use of the special NULL value. It pops up literally everywhere. It is a central concept in computer science.

  • There are normally two special values. Some languages handle both, some only 1 and throw an error with the other, and some merge the two. Those two values are Null and Undefined.

    • Undefined would be trying to use a variable that flat out doesn't exist.

    • Null would be trying to use a variable that exists but has no value.

    Null can be useful because it is a guaranteed value that indicates that something is wrong, or outside of the domain/range of possible answers. Take Java for instance:

    If you did not have null, what if you did a lookup in a HashMap for something that didn't exist in the Map? What would you return? If you returned an Object then how would you know wether that Object meant nothing was there or this was what was actually in the Map. Workarounds could include creating your own "NON_EXIST" Constant Object, but thats essentially the same thing as what null already is anyways. Another workaround might be throwing an Exception. Now you're looking at major performance impacts.

    Again, its the idea of having a guaranteed allowable value that you can use. It is always available to you and its always disjoint from the set of "real values" that would normally return from an operation you're performing. Null is therefore intentionally used to mean something special.

    Like I hinted before, there are also optimizations that can be done here as well because Null is a special value. In languages like Java if you originally referenced an Object solely by a variable, then set that variable to null you're removing that reference and allowing Java's Garbage Collector to collect that now unreferenced data. If instead you let that variable sit around forever that hunk of memory that may never be used again will continue to hold resources. This is a contrived example, but it proves a point and in some resource intensive Java programs you will see these explicit assignments to null.

  • my answer to that question is NULL

Hyper-Threading programming languages

What languages can hyper-threading be implemented in? Is it only part of Object Oriented systems or can it be implemented in C?

Thanks.

From stackoverflow
  • Any language and runtime that supports threads will support hyperthreading.

    Hyper-threading is a way of multiplexing a CPU between multiple threads - there is only one real CPU but it is visible to the operating system as two CPU's, and thus two threads can be scheduled on it. Any stalls in the CPU on one thread (like waiting on memory, long FPU operations, etc.), allow the CPU to execute code from the other thread.

    More info on hyper-threading at Wikipedia.

    Drew Hoskins : It's actually finer-grained even than that. Different computational units (arithmetic, floating point) can be simultaneously computing results of instructions from different threads.
    Michael : Yeah ... a more complete answer would give this in the context of out-of-order execution and pipeline stalls but I didn't want to compress the 700 pages of Hennessy and Patterson into an answer here :)
    Michael : Actually, I'm not sure if different computational units simultaneously is possible in the case of the Atom since it is an in-order part.

Tying tables together in MySql

I have one table that includes company information (i.e. name, address, business description...) and another table that has user information (i.e. first name, last name, email and password). How do I tie the company table to the user table so that when the user logs in, the company is properly associated with the user? Would I have a userid column in the company table?

From stackoverflow
  • You are looking for joins.

    Companies would have a one-to-many relationship with the users, so you need to create a column in the user table with a name like company_id and then query it like this to get users and their company:

    SELECT * FROM users INNER JOIN companies ON users.company_id = companies.id
    
    Paolo Bergantino : :? How is this wrong? I'm rereading the question and this is what he's asking about.
    BrynJ : Agree, I'm not sure why your answer would be down-voted
    Adrien : +1 From me ... Also, see http://stackoverflow.com/questions/832322/question-about-joining-two-mysql-tables/
  • Assuming that several users might belong to a single company but only one company may be associated with a user, a companyid in the user table would make the most sense.

    To join two tables together where you expect a match between both in all cases, use an INNER JOIN:

    SELECT u.*, c.companyname FROM users u 
    INNER JOIN companies c ON u.companyid = c.companyid
    

    Obviously, the above is a simulated query and needs tailoring to match your schema / requirements.

  • No, you will probably have a one-to-many relation. So one company contains many employees. But one employee belongs to only one company (to keep things simple).

    This requires a foreign key in the user table pointing to the id of the company.

SubSonic doesn't map stored procedure in packages

Ive Used Subsonic for MSSQL and works wonderfull!!!! Does anyone know whats with oracle's SPS in Packages? Please help. need to deliver a func verry soon.

From stackoverflow
  • Oracle packages aren't supported. I'm not sure there are plans to support them any time soon.