Saturday, April 30, 2011

Tips for successful, long distance development?

My small business is just about to start a program of work. The 2 of us have been in the same industry for many years and believe we have come up with a simple solution to a VERY common problem. We will know we have succeeded when it becomes a no-brainer to use our software and we can continue to solve the various problems encountered by organizations operating in this field.

The problems we have I am sure are faced by many businesses starting out - not enough funds, no IT experience etc. however we have done fairly well to date with our Excel prototypes (don't laugh) and are ready to commercialize.

Because of the costs of developing at home (Australia), we are trying to find a few developers internationally that we can have work on various pieces, potentially with one IT guy back here co-ordinating/bring the pieces together. We aren't necessarily looking for the cheapest work, but none of the quotes we have had here to date make sense.

Does looking abroad sound like a viable approach? What are some things we should look out for doing it this way? Has it worked/failed for anyone else before?

From stackoverflow
  • I am not able to give you any answer to your problem but this: for development strategy, Agile methods are a no-go on your respect. The reason is that Agile methodologies assumes a very easy communication in front of a whiteboard, pair programming and so on. Although technology exist to supply for this, it is not the same as being in the same room.

    So, check how other delocalized teams work (in particular, check KDE, MySQL and Mozilla) to choose a proper development strategy.

  • Choose one team and a backup. Don't just dive in with a newly hired team. Start with a small pilot project (yeah, spare some money) -- see how they fare and then go on. If you are not happy -- just get it done yourselves (it's much less hassle).

  • Write everything down!

    It is very tempting to do meetings via phone, but you never know what is going on at the other end. If you do phone meetings, write meeting minutes and have every participant agree to them in writing. This will eliminate a lot of misunderstanding which might bite you later on.

    Apart from this basic advice, I can think only of performing certain tests (let them do some example programs, solve a few programming puzzles relevant to your work etc.) to make sure your prospective hires abroad turn out to be right for the job.

    Good luck, it will probably not be easy, but at least you might get to know some interesting people from across the globe.

    Jared : You may want to either record phone calls or use skype to communicate and record that.
    HS : Good idea, but text in a computer is easier to search.
  • You may want to listen to this podcast episode. http://www.dotnetrocks.com/default.aspx?showNum=162

  • You cannot do without a good bug tracker w/ integration for your version control.

    (Background: I work out of my home office doing custom software development, mostly for clients in the same city: I guess you could call that "short-distance development". I end up seeing my clients in person once every couple of weeks or so, and even then I totally depend on the bug tracker to keep things on the go.)

  • I have an outsourcing company and have spent the last four+ years in Ukraine.

    My strong suggestion is that you go physically to where the programmers are and spend as much time there as you can.

    During the start of the project, you will be able to clearly explain to the programmers what you want. You will see how and where they work. They will understand the business side of what you want. They will feel how important the project is to you. You will be able to sense if there are people who are not pulling their weight (replace them immediately).

    When you return back to Australia, have daily meetings to keep things on track. Make these consistent every day. Use a camera on both sides.

    Get a hosted server that both you and the team have access to. Put source control, autobuilds, and demo sites on that machine. Ensure you have daily builds. Review the product often.

    If you are going to do this full time, consider spending months with the programmers. Your cost of living will likely not be high.

  • You mentioned getting the work done in Australia is costly, that is why you looking abroad. Can you not hire good university grads and get the work done? I have successfully worked with university grads, the key is to hire good programmers.

    Working in a distributed environment have its challenges but there are solutions as well. I have worked in this environment and we managed to do it successfully.

    Communication is most important, we used to rely on chat, mails and phone in that order. Once you have proper disciplined communication rest will be easy. We used source control, coding conventions, automatic builds, daily status meetings. All this helped to keep the control.

    anthon : Uni grads would be great and eventually we'd look to hire as the business generated cash flow. Unfortunately we just don't have the resources for that from day one. Any tips for getting Uni students on board? I presume you would need one super-student or even an experienced IT individual to mentor/lead?

Where can I find a practical/real time scenario of using `List<T>`?

Where can I find a practical/real time scenario of using List<T>?
I want to know where and how we can implement List<T>.

Any Code example, or any link will do.

From stackoverflow
  • How about the MSDN page on List<T>? There's an explanation and an example there.

  • Simply put, whenever you want a list of something (list of number, list of persons, list of whatever), you just use a List, List, List. Maybe I missed the point of your question.. you ask how to implement List? Or how to implement code using a list? I guess it's more the second choice.

    Cerebrus : +1 for anyone who recommends lmgtfy! ;-)
  • In a 'real-time' system, you'll likely want to make sure your list is created large enough to hold all the data you intend to put in it when you first create it (use the constructor where you pass a capacity).

    You'll also want to avoid the following operations (and maybe more), as they are relatively expensive (ie. they may look O(1), but aren't):

    • Insert(int, T)
    • Remove(T)
    • RemoveAt(int)

    There are other O(N) operations on a list, but most of those you'd guess by looking at what the method does.

    That said, the only way to know if it'll work for your performance requirements is to test it. Get yourself a good test harness and pound it to make sure it means your needs.

  • Sounds like you will need to model the performance needs of your service to see if List or any data structure will work. Do you need millions of items per second? Billions? Milli-seconds? Make sure you can deliver to your specifications, or re-write the specifications!

  • I have never written software for realtime-like systems, and I doubt that .NET is a good candidate for it. You never know when the garbage collector will trigger, pause your programs for an unknown amount of time before it returns the execution to your program like nothing happened.

    Could you tell us more about the type of data, and the type of operations you expect to do with the list? The slowest part with a List is probably the resize of the underlying array that occurs when you add more items that it was originally created for. You can get away with this by using the constructor that accepts an integer as the initial size, if you can calculate that information. Also, stay away from some of the methods like Insert/Remove, they aint as fast as they sound like.

    Peter Lillevold : How can you say that .Net cannot be used with realtime systems if you have no experience in building such beasts?
    Simon Svensson : @Peter, That's why I used the wording "and I _doubt_ that". It is required, to my knowledge, that a realtime system should execute before a preconfigured time. This is not something that can be guaranteed if the code can be interrupted at any time by the garbage collector, paused for any time, and resumed later without any notification.
    Peter Lillevold : True, I pull back my -1. The .Net runtime can be configured to run GC on a separate threads with multicore processors, though, which will make it more likely to work in realtime scenarios.
    Simon Svensson : There are more information at http://blogs.msdn.com/maoni/archive/2004/09/25/234273.aspx about different garbage collections. While all pause the execution in some what, some does it for shorter intervals and are optimized for high responsiveness.
    1. Identify alternatives to List<>
    2. Measure performance of List<> compared to alternatives for your specific case. General answers to your question cannot be accurate.
  • What kind of real time is real time? Because if you want to do REAL real time, neither .Net nor Windows is your friend.

    And it ain't simple: http://www.eurotech-inc.com/info/white-papers/Managed_Code_for_Real_Time.pdf

  • For performance-critical systems, I agree that List<T> might not be appropriate for the job because it's a little bloated in terms of implementation. Sure it's easy to use, but it has a lot of caveats in it.

    To really find out how it performs:

    • Create a program that does some typical operations for your application then profile it using List<T>.
    • Study the internal workings of List<T> using RedGates reflector to really, really find the bottlenecks and find alternative implementations for it. For example, one unexpected slowdown point would be accessing the Count() method, as it iterates through all the contents of the list.
    • Your finds should be basis enough to implement a "turbofied" implementation of the IList<T> interface that you can use on your system with reasonable performance improvements.
  • I think you are rather looking for some comparison of List with other data structures in C#. It would be nice if you filter down your question.

Are BDB files portable from one system architecture to another

My googlefu is lacking tonight and I can't find an answer to this.

Will databases I create on a amd64/emt64 system be usable on a x86 system?

From stackoverflow
  • According to the FAQ:

    Are Berkeley DB databases portable between architectures with different integer sizes and different byte orders?

    Yes. Specifically, databases can be moved between 32- and 64-bit machines, as well as between little- and big-endian machines. See the "Selecting a byte order" section of the Berkeley DB Reference Guide for more information.

    Zoredache : Excellent! Thanks.
    joast : I think the FAQ answer should have a caveat. The database files themselves are portable, however the data you store in a BDB database is only portable if you make it that way since BDB doesn't know the structure of the records being stored. For example, if you use integer keys, then you either need a custom comparison function or always store them in network byte order and translate to host byte order as needed.

Cocoa / Objective-C Array beyond bounds question

I am playing with a little Cocoa Apps I wrote where I add objects of a class Person to a NSMutableArray. When I try to access an object that is beyond the array limit all I get is an "beyond bounds" message on the console.

In fact I expected something worse. I expected the app to crash! But it doesn't.

I am not sure if this is a good or a bad thing but I wonder what does happen inside the apps to prevent it from crashing. I always had the idea I am accessing objects in memory who are not there. Normaly that would kill every application.

From stackoverflow
  • In your case, you're not actually being allowed to access bad memory directly since you're interfacing through the NSArray object. Instead, what's happening is that you're giving the object a bad index, and it is informing you by throwing an exception.

    By default, exceptions that happen on the main thread of an NSApplication application do not cause the application to terminate. Instead, they log the error and abort the current run loop cycle and then start the next cycle.

    For more information on how you can deal with these exceptions during your debugging phase, please take a look at this document. It describes various techniques and responses you can use when dealing with application level exceptions.

    Also, reading and writing bad memory doesn't always cause the application to crash, that's why those kinds of errors can be so hard to track down. Instead, you could simply be corrupting other objects and have no idea that you've done so until much latter in the application's cycle. The important thing to remember here is that NSApplication will squash most exceptions happening on the main thread, so you have to pay extra attention to that.

SVN Default folders - Must they be used?

I've seen repositories in SVN that did not at least create a local trunk, branches, and tags folder on the client. So is are the default folders required for use with SVN (I'm using tortoise) or what? I don't see why some people have the folders but some do not in some implementations of repositories.

From stackoverflow
  • Since the only way to tag or branch in Subversion is to make a copy in some other tree, omitting the standard trunk/tags/branches directories prevents you from ever creating a copy of your repository in a location that is "outside" your project directory. If you ever want to tag or branch without having the default directories, you'll just end up creating them and moving your project around anyway.

    CoffeeAddict : but a branch is not a copy of an entire directory, usually it's not at least.
  • Absolutely not required. Many companies consider it best practices, and having trunk/branch directories works well for many software environments, and seems more familiar to those coming from cvs, etc.

    An example where it's suboptimal is storing a website in Subversion. Several companies I've worked at have a Devel and Live directories. Work is done in the Devel directory, and merged into the Live directory when the green light goes on.

    As Greg said, though, you definitely want SOME directory under the root, but there's no requirement for a particular structure.

    CoffeeAddict : what do you mean by "some directory", can you put this into context then if I do not have those folders initially? I am not a build guy so I do not know.
    dj_segfault : As Greg (Love the hair!) said 04/21, if you put all your stuff in the root of the repository, it's very difficult to change your mind later by creating a directory and moving all the existing stuff into it. However, if you have everything in a directory, you can always create parallel directories and subdirectories, etc.
  • As others have said, it is not required to have the trunk/branches/tags. These folders have no special meaning to subversion, it's just a best practice that you may use if it fits your needs.

    But since you mentioned TortoiseSVN, there is one small detail: Tortoise will warn you when you try to commit to a sub-folder of /tags. It enforces that a tag is not modified once it is created (another best-practice).


    Update (in response of your comment):

    The best practices say that you should have "trunk", "branches" and "tags" folders in your repository. One way (probably the most common one) to use these folders is this:

    • trunk is where the main development takes place.
    • tags contains snapshots (copies) of important revisions/version of your source code (e.g. releases such as 1.0, 1.1, 2.0).
    • branches are used for maintenance of older versions, e.g. your product is on version 2, then you have the need to fix a bug in version 1.0 (you can then copy your 1.0 tag to a new branch and make modifications there).

    Now to subversion, all folders (trunk, tags, branches) are "normal" folders. They have now special meaning and subversion does not treat them any different (which means you could modify what you have in "/tags/1.0" for example).

    TortoiseSVN tries to enforce best-practices by warning you when you try to commit to a tag (since usually you want to keep tags as they were to be able to rebuild an older version of your product at any time).

    CoffeeAddict : what do you mean by tags
    M4N : Updated my answer. Hope this helps. See also this page of the tortoiseSVN documentation: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-repository.html#tsvn-repository-layout
    CoffeeAddict : I am pretty sure we had those folders on the server-side but not client-side. When we as developers checked out code for the first time from a repository, we only saw the .svn folder and nothing more
    Vincent Robert : No. You should not checkout those folders on the client, they should be used to help you choose which branch you're working on. Checkout ".../trunk/" to work on the trunk. Then "switch" to ".../branches/new-feature/" to work on the new feature.
    Vincent Robert : And keep in mind that using the recommended trunk/branches/tags folders will greatly help any migration to another version control software in the future.
  • This doesn't answer your question, (the others have already) but if you only want the trunk, just specify that when you do the initial get/checkout.

What is the best way to search the Long datatype within an Oracle database?

I am working with an Oracle database that stores HTML as a Long datatype. I would like to query the database to search for a specific string within the HTML data stored in the Long.

I tried, "select * from TABLE where COLUMN like '%form%'". This causes the following Oracle error because "like" is not supported for Long datatypes.

ORA-00932: inconsistent datatypes: expected NUMBER got LONG

From stackoverflow
  • You can't search LONGs directly. LONGs can't appear in the WHERE clause. They can appear in the SELECT list though so you can use that to narrow down the number of rows you'd have to examine.

    Oracle has recommended converting LONGs to CLOBs for at least the past 2 releases. There are fewer restrictions on CLOBs.

  • Don't use LONGs, use CLOB instead. You can index and search CLOBs like VARCHAR2.

    Additionally, querying with a leading wildcard(%) will ALWAYS result in a full-table-scan. Look into http://download.oracle.com/docs/cd/B19306_01/text.102/b14218/toc.htm>Oracle Text indexes instead.

  • Example:

    create table longtable(id number,text long);
    
    insert into longtable values(1,'hello world');
    insert into longtable values(2,'say hello!');
    
    commit;
    
    create or replace function search_long(r rowid) return varchar2 is
    temporary_varchar varchar2(4000);
    begin
    select text into temporary_varchar from longtable where rowid=r;
    return temporary_varchar;
    end;
    /
    
    
    SQL> select text from longtable where search_long(rowid) like '%hello%';                                                                              
    
    TEXT
    --------------------------------------------------------------------------------
    hello world
    say hello!
    

    But be careful. A PL/SQL function will only search the first 32K of LONG.

    Sam : If you want to delete the matching rows, see this answer: http://stackoverflow.com/questions/2381203/oracle-delete-where-long-like/2381600#2381600

importing gaeutilities or any other module by dev_appserver

I'm developing a gae application on a windows machine. to have session handling I downloaded gaeutilities and added its path (C:\Python25\Lib\site-packages\gaeutilities-1.2.1) to the registry ("PythonPath" item under python25).

in my code this is how I import the gaeutilities Session class:

from appengine_utilities.sessions import Session

when gae engine (dev_appserver.py) tries to import it, an exception is raised, stating an importerror and "no module named appengine_utilities.sessions"

on the other hand, pyscripter can find the module (autocomplete becomes available for the Session class), and I can import the module within the python interpreter (the same one that dev_appserver uses, python 2.5.4).

for a remedy, I created a PYTHONPATH environmental variable and also added the path to it. nothing changes.

I'm lost. what am I doing wrong?

important edit: I have found myself to be totally unable to import any 3rd party gae modules. PYTHONPATH is correct, sys.path is correct, registry is correct, still dev_appserver complains of importerror.

From stackoverflow
  • Strange.

    I would start troubleshooting by making 100% sure that the sys.path that dev_appserver.py uses does include C:\Python25\Lib\site-packages\gaeutilities-1.2.1.

    I suggest you display sys.path in a HTML view served by dev_appserver.py.

    Check permissions on gaeutilities-1.2.1 directory and subdirectories. Perhaps the python interpreter is unable to create *.pyc files or something like that.

    Another suggestion:

    Put the appengines_utilities folder in your application directory (the directory that contains your app.yaml file). I guess you need all third-party stuff there anyway if you want to upload the code to google's servers.

    shanyu : Thank you, I followed your suggestions to see that sys.path includes the folder and no permission restrictions on the folders. Any other suggestions? :)
    codeape : I updated my answer with another suggestion.
    shanyu : That does it, thanks.

How do I call dll inside Java?

How do I call a DLL inside Java program ?

From stackoverflow
  • System.load("C:\\Windows\\System32\\yourdllname.dll");
    

    if thats your path to your dll

  • The canonical answer is JNI. However, this is somewhat painful. Other options:

    CDR : If you also add which one is the latest and best that would have been helpful too. Like initialy it was JNI. Then someone wrote a better solution Swig. Then finding Swig's limitation some wrote JNA which is double faster than Swig etc
    Jon Skeet : Unfortunately I don't know that history.

Manipulating a thread from a different thread

In a program in c# I have 2 threads apart from the main thread. When the user closes the form I want to terminate one of the threads from the main thread. How do I go about doing so?. Please provide me with the code if possible.

From stackoverflow
  • If you want to kill off a thread you have started yourself I would suggest holding a reference to it, such as a private field. When the application (or thread) is finishing off you can simply call Thread.Abort() on that thread.

    For example:

    private Thread _myWorker;
    
    void doSomething()
    {
        _myWorker = new Thread(...);
        _myWorker.Start();
    }
    
    void killWorker()
    {
        _myWorker.Abort()
    }
    

    You should note that then you call Abort() on the thread it will raise a ThreadAbortException which you should catch within your worker code and handle to cleanup etc. For more details see Thread.Abort

    Additionally when your application shuts down its main thread (the message loop, aka Application.Run) the child threads will also be shut down.

    Jon Skeet : Child threads will only be shut down automatically if they're background threads. Foreground threads can live on after the main thread has shut down.
  • Please don't use Thread.Abort as recommended by the other answers so far, unless you want your program to be in an unknown state (see articles by Ian Griffiths and Chris Sells for more info). If closing the form should actually be killing the app, you're probably okay - but in that case I'd recommend just using background threads anyway, which will automatically die when all foreground threads have terminated.

    From Joe Duffy's "Concurrent Programming in Windows":

    There are two situations in which thread aborts are always safe:

    • The main purpose of thread aborts is to tear down threads during CLR AppDomain unloads. [...]
    • Synchronous thread aborts are safe, provided that callers expect an exception to be thrown from the method. [...]

    All other uses of thread aborts are questionable at best. [...] While thread aborts are theoretically safer than other thread termination mechanisms, they can still occur at inopportune times, leading to instability and corruption if used without care.

    (Synchronous thread aborts are when the thread aborts itself, rather than being aborted by another thread.)

    For graceful shutdown (without risking getting into odd states) use a flag which is set periodically from the form and checked from the other threads - taking the memory model into account (e.g. either making the flag volatile or using a lock each time you test or set it). See my article on the topic for an example.

    Avik : To close the form I have the corresponding event. I have named the thread that I wish to terminate as SecondThread. However I am unable to call SecondThread.Is there something I am missing here. Moreover if there is anyway by which a thread can abort itself that would simplify things because i prefer using the concept of flags as you have pointed out.
    Jon Skeet : You just make sure that it has access to a shared piece of data, and that it polls it regularly to see whether or not it should shut down. Of course, you can only do this if you control what the thread's doing yourself.
    Matthew Savage : This is quite subjective - if your threads are for a single unit of work then calling Thread.Abort() shouldn't leave it in a dirty state (provided you handle the abort properly). If you have a thread which is then calling out to lot of other methods then it gets messier. Its really a case of looking at what you are doing and determining the best approach.
    Jon Skeet : "Provided you handle the abort properly" is the difficult bit - and likely to be harder than just making the thread shut down gracefully in the first place. While it's *somewhat* subjective, I think it's worth listening to the advice of true experts like Joe Duffy. Why take chances with something as tricky as asynchronous aborts?
  • Killing threads from other threads is almost always a bad idea. The correct way to do it is to signal the thread to terminate and then wait for it.

    That's because threads should be totally responsible for their own resources as much as practicable, and that includes their lifetime.

    It doesn't need to be complicated, a simple variable which can be set by any thread and is read by another thread periodically will do (this isn't really in any language but you should get the idea if you know C):

    int exitThread1 = false;
    static void Thread1 (void) {
        while (!exitThread1) {
            // do stuff
        }
    }
    static void mummyProc (void) {
        int tid1 = startThread (Thread1);
        // dum de dum de dum ...
        exitThread1 = true;
        joinThread (tid1);
    }
    

Changing System.in in eclipse to read from a file

This seems like kind of a silly question but is there a way to change the standard in in eclipse. If I was doing this from the windows console it would look like "java myprogram < stdin.txt"

From stackoverflow
  • The way you do this in VS is to set the command line arguments when debugging to "< stdin.txt". Maybe the same will work in Eclipse? I'd check but I don't have it on this machine.

  • Here is a (fairly ugly) solution, as pointed out in this comment

  • I am using Eclipse 3.4 and I see a place to enter a file for stdin/stdout on the Common tab of a Java Application Run configuration. I am not exactly sure if it will work for stdin, but it is worth a try.

How to use cumstomized configuration xml file?

I am going to use StructureMap as a way to do DI. I'll use xml as my DI configuration. I have two questions.

The first one is how to use a customaized xml file name instead of StructureMap.Config? For example, in my console application, if I want to use myDIStructure.config file, what class and method should I use in the main():

private static void main(string[] args) {
    //? OjbectFactory.UserConfigurationFile = "myDIStructure.config";
    Program program = ObjectFactory.GetInstance<Program>();
    ...
}

The second question is how I define generic interface with a class type in my configuration file. For example, I have the following interface and class:

public interface ProcessData<T> {
   void ReadData(T data);
   void ProcessData(T data);
   void SaveData(T data);
}
...
public class Data1 {....}  // this class will be used for ProcessData<T>
....
public class MyProcessData : ProcessData<Data1> {....} // implementation class

Then in my console application, I would like to use PlugInFamily for ProcessData interface type, and Plugin for MyProcessData. Not sure if this is possible in StructionMap and how?

From stackoverflow
  • First - I'm increasingly of the opinion that the xml configuration option is now mainly left for backwards compatibility. The main StructureMap code now uses the code-based registry approach.

    Re using custom files; I haven't tried it, but StructureMapConfiguration.IncludeConfigurationFromFile(...) looks promising.

    Re generics... indeed, that is one of the complexities of xml ;-p

    Edit: based on this post in the user group, it looks like maybe the back-tick notation will work:

    <DefaultInstance 
      PluginType="MyDemo.IRepository`1, MyDemo" 
      PluggedType="MyDemo.UserRepository , MyDemo" />
    

How to Store Video in a Video Web Application

What is the best way to store lots of video in a web application? Hardware, Database, etc. If you were building a YouTube clone, how would you do it?

From stackoverflow
  • I believe the way youtube handles it is storing the file location in a table in the DB, so when the request is made the file is located from the hard drive and then loads the file from there.

    Take a look at: http://highscalability.com/youtube-architecture for more info.

What should I do to modify my fork() in C to run well?

I dont understand why my code does not work.

This is my code. I don't know why I'm get an error segment. Could somebody explain the reason to me?

#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>

int id_process;

void manager_signal () {
    kill (id_process, SIGKILL);
    kill (getppid(),SIGKILL);
}

int main () {
    id_process = fork ();
    if (id_process==-1) {
        perror("ERROR to create the fork");
    } else {
        if ( id_process != 0 ) {
            printf("Father´s ID is %d \n", getpid());   
            alarm(5);
            (void) signal (SIGALRM, manager_signal);
            sleep (20);
            printf ("Running to where the father can be\n");
            alarm (0);    
        } else {
            printf ("CHildren´s ID is %d \n", getpid ());
            for (;;) {
                printf ( "Children RUN FOREVER ^^");
                sleep (2);
            }
        }
    }
    return 0;
}
From stackoverflow
  • Your question is a little difficult to understand since you don't really explain what the error is, but I do have one question which I'm sure will be pertinent.

    Why is the "father" process killing its child and its parent? Shouldn't it kill its child and itself (id_process and getpid() rather than getppid() which is the parent PID)?

    That appears to be the problem. When I run that under Cygwin, it kills off my shell (darned annoying). If I change it to kill (getpid(),SIGKILL);, it terminates okay after five seconds with the following output:

    $ vi qq.cpp ; g++ -o qq qq.cpp ; ./qq.exe
    Fathers ID is 6016
    Childrens ID is 4512
    Children RUN FOREVER ^^
    Children RUN FOREVER ^^
    Children RUN FOREVER ^^
    Children RUN FOREVER ^^
    Children RUN FOREVER ^^
    Killed
    

    This is with the program modified as follows:

    #include <iostream>
    #include <string>
    #include <sys/types.h>
    #include <unistd.h>
    
    int id_process;
    
    void manager_signal (int x) {
        kill (id_process, SIGKILL);
        kill (getpid(),SIGKILL);
    }
    
    int main () {
        id_process = fork ();
        if (id_process==-1) {
            perror("ERROR to create the fork");
        } else {
            if ( id_process != 0 ) {
                printf("Fathers ID is %d\n", getpid());
                alarm(5);
                (void) signal (SIGALRM, manager_signal);
                sleep (20);
                printf ("Running to where the father can be\n");
                alarm (0);
            } else {
                printf ("Childrens ID is %d\n", getpid ());
                for (;;) {
                    printf ( "Children RUN FOREVER ^^\n");
                    sleep (1);
                }
            }
        }
        return 0;
    }
    
    Jonathan Leffler : Run the faulty program as: sh -c "./testprog"; then your main shell isn't killed. Good spotting on the incorrect definition for manager_signal(); can you still do: void manager_signal(int) to indicate that the function takes an int (the signal number) but ignores it? It was a nice feature in C++ as I recall it, one that C would do well to adopt too.
  • I don't think

        kill (id_process, SIGKILL);
    

    is required either. You're killing the same process in the next instruction.

How to move controls to the middle of an MFC form?

How to move controls to the middle of the form in a VC++ 6.0 MFC project?

Say I added an EditBox(m_editcontrol), how to move this control to the middle of the form?

From stackoverflow
  • CRect rectParent;
    m_editcontrol.GetParent()->GetClientRect(rectParent);
    CRect rectControl;
    m_editcontrol.GetWindowRect(rectControl);
    m_editcontrol.MoveWindow((rectParent.Width()-rectControl.Width())/2, (rectParent.Height()-rectControl.Height())/2, rectControl.Width(), rectControl.Height());
    

    The position of a control is within the client area of the parent, so first we need to get the width and height of the parent window. Then, we get the width and height of the control. The middle of the parent window is the difference of the widths and heights, divided by 2. MoveWindow is used to move a window to the desired position.

  • In the VC6 resource editor you can select the control and do Ctrl+F9 for vertical centering and Ctrl+Shift+F9 for horizontal centering.

    Programatically you can use MoveWindow Win32 API to position the control wherever you want.

whats the best way to pass data to user components in asp.net?

its .net 2.0 here, not MVC, and im crap at asp forms :(.

So yeah, ive got a page with user controls on it. When i click on something in the page, i want to load the usercontrol based on a parameter from the page.

Problem is i cant do it.

In my page's FaultTree_Clicked, i get the value, then ive tried a variety of things:

  • I tried exposing a property on the child user control to set the value, which i set in FaultTree_Clicked, it gets forgotten.

  • I tried saving it to Session["mykey"], and loading Session["mykey"] in the control's Page_init... the value is blank.

  • I tried saving it to ViewState["mykey"], and loading ViewState["mykey"] in the control's Page_init... the value is blank.

EDIT: ok more specific info: Heres a cut down version of what the page(MyFault) looks like:

<form id="form" runat="server">
 <div id="faulttree">
   <asp:TreeView ID="FaultTree" ......>
 </div>
 <uc1:_DefectDetail ID="DefectDetail" runat="server" Visible="true" EnableViewState="true" />
</form>

And theres a method on the pages codebehind "FaultTree_SelectedNodeChanged()".

When that method is hit, I want to load/show the DefectDetail control. The DefectControl requires a faultid, which comes off the Tree, which i successfully get in the SelectedNodeChanged method. I cant get the faultid into the defect control.

From stackoverflow
  • This has to do with ASP.NET page lifecycle. By the time the click event fires, the control's init event has already happened.

    In order to better assist you, please provide a more detailed explanation of what the FaultTree control is, what is the desired result and some sample code.

    UPDATE:

    Instead of a public property, you can simply create a public method in the control that does the desired action and invoke it from the FaultTree_SelectedNodeChangeEvent.

    Example (for a public method named Refresh):

    _DefectDetail.Refresh(object data);
    
    dalyons : I updated with an example to explain what im trying to do.
    dalyons : argh! thats all i needed to do!! haha. Thanks heaps. If i set the fault property within the Refresh function, i noticed it is blank by the time i call another method on that control. So i put the faultid in a hidden field, that is updated by the Refresh. is this the way to go? I think it might be beacuse my fault object is not serializeable.
    Jose Basilio : If the hidden field works that's great.
  • Basically you have to use EventHandlers....

            1. Add a event handler to your user control (I had a search bar UscSearchCriteriaBar1)   
    
            public event EventHandler CriteriaChanged;
    
            +
    
    
            private void InternalOnCriteriaChanged()
            {
            OnCriteriaChanged();
            }
            +
            protected virtual void OnCriteriaChanged()
            {
            // If there are registered clients raise event
            if (CriteriaChanged != null)
            CriteriaChanged(this, EventArgs.Empty);
            }
            +
            Example
            public int EmployeeID
            {
            get
            {
            f (Session["EmployeeID"] != null)
            {
            ViewState["EmployeeID"] = Convert.ToInt32(Session["EmployeeID"]);
            }
            if (ViewState["EmployeeID"] == null)
            ViewState["EmployeeID"] = 0;
            return int.Parse(ViewState["EmployeeID"].ToString());
            }
            set
            {
            ctlEmployee.SelectedValue = value.ToString();
            ViewState["EmployeeID"] = value;
            Session["EmployeeID"] = value;
            }
            }
    
    
            In your page or other control
    
    
            override protected void OnInit(EventArgs e)
            {
            InitializeComponent();
            UscSearchCriteriaBar1.CriteriaChanged += new EventHandler(this.CriteriaChanged);    
            base.OnInit(e);
            }
    
            private void CriteriaChanged(object sender, EventArgs e)
            {
            try
            {
    RefreshData();
            }
            catch (Exception ex)
            {
            ExceptionManager.Publish(ex);
            }
            }
    
        You can get UscSearchCriteriaBar1.EmployeeID
    

    This code should give you some ideas...was done for 1.1 should work on 2.

Why Screen is blinking when I am moving Object ?

Hi

I need to move object on screen, but when the object is moving the Screen is blinking (and the object too).

How can I fix it ? What is the best way to move an object on screen ?

Thanks in advance

From stackoverflow

Changing the value of a const pointer

I have the following piece of code:

void TestFunc(const void * const Var1, const float Var2)
{
  *(float*)Var1 = Var2;
}

It looks like I am changing the value of the const object the const pointer points to (thanks sharptooth), which should not be allowed. Fact is, none of the compilers I tried issued a warning. How is this possible?

From stackoverflow
  • The cast is legal, but the behaviour is undefined.

    David Thornley : That seems like a confusing answer to me. Using the cast may or may not be undefined behavior, depending on what it's used on.
  • You change the object the pointer points to, not the pointer value.

    C-style cast acts like a const_cast and removes the const modifier off the pointer. The compiler now has nothing to moan about.

  • As others mentioned, the cast removes the 'constness' of the destination as far as the expression is concerned. When you use a cast the compiler treats the expression according to the cast - as long as the cast itself it valid (and C-style casts are pretty much the big hammer). This is why you don't get an error or warning. You're essentially telling the compiler, "be quiet, I know what I'm doing, this is how you should treat things". In fact, casts are probably the #1 way for programmers to get the compiler to stop issuing warnings.

    Your assignment expression may or may not be undefined behavior. It is permitted to cast away constness if the object actually pointed to is not const.

    However, if the object pointed to is const, then you have undefined behavior.

    void TestFunc(const void * const Var1, const float Var2)
    {
      *(float*)Var1 = Var2;
    }
    
    
    int
    main(void)
    {
        float x = 1.0;
        const float y = 2.0;
    
        TestFunc( &x, -1.0);    // well defined (if not particularly great style)
        TestFunc( &y, -2.0);    // undefined behavior
    
        return 0;
    }
    

    You're treading dangerous waters...

    In general (I'm sure there are exceptions), casting so that expressions treat objects as they really are is supported, well-defined behavior in C/C++.

    This particular behavior is covered in the standards mostly by statements that modifying a const object through a cast (or something) that removes the const qualifier is undefined. The inference is that doing the same for a non-const object is not undefined. An example given in the C++ standard makes this clear.

    C90 6.5.3 - Type Qualifiers (C99 6.7.3):

    If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

    C++ 7.1.5.1 The cv-qualifiers

    A pointer or reference to a cv-qualified type need not actually point or refer to a cv-qualified object, but it is treated as if it does; a const-qualified access path cannot be used to modify an object even if the object referenced is a non-const object and can be modified through some other access path. [Note: cv-qualifiers are supported by the type system so that they cannot be subverted without casting (5.2.11). ]

    Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

    ...

    [Example:

    ...

    int i = 2;            //not cv-qualified
    const int* cip;       //pointer to const int
    cip = &i;             //OK: cv-qualified access path to unqualified
    *cip = 4;             //ill-formed: attempt to modify through ptr to const
    
    int* ip;
    ip = const_cast<int*>(cip);   //cast needed to convert const int*to int*
    *ip = 4;                      //defined: *ip points to i, a non-const object
    
    const int* ciq = new const int (3);   //initialized as required
    int* iq = const_cast<int*>(ciq);      //cast required
    *iq = 4;                              //undefined: modifies a const object
    
    cschol : Thanks for the detailed explanation. Do you happen to have a reference where this is documented for the C language? All I can find is references to const_cast in C++.
    Michael Burr : I added the relevant material from the standards.
    cschol : I appreaciate it. Thanks alot!

How to Suspend a button event in C#?

In my application I want to suspend a button event for some time so that I can fire another event after which the first button event will resume. In c# I am not getting how do I perform it using threads asynchronously. Please help. Thanks in advance..

From stackoverflow
  • If you want to fire the second event and wait for it to finish before continuing, then why not just fire it synchronously from within the first event handler? That would be much simpler.

    EDIT:

    If you want one button to trigger the code that's in another button's event handler, I would suggest instead that you move it out into a separate function, and just call that. In other words, do this:

    private void button1_Click(object sender, EventArgs e)
    {
        DoButtonStuff();
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
        DoButtonStuff();
    }
    
    private void DoButtonStuff()
    {
        // code that was originally in button2_Click()
    }
    

    If the buttons do the exact same thing, you could even just assign them the exact same handler.

    But, if you really must programmatically "click" a button, then the easiest way is probably:

    button2.PerformClick();
    

    That'll raise a Click event.

    Enjoy coding : ya iam trying to do that I need some sample code for that. I need to know how to fire a button event within other event. But I dont know the parameters of the button event please provide sample code
  • This sounds like a design problem in your application and you're tackling it from the wrong end.

  • could you do something with background worker

    background worker bw = new background worker
    
    
    button1
    
    while bw.inprogress
    {
    
    //kill time
    
    }
    bw.(dosomething)
    
    
    
    button2
    {
    while bw.inprogress
    {
    //killtime
    
    }
    bw.run(dosomething)
    }
    

Excel Date Field Conversion Problem

I currently have an excel sheet with one of the columns being in the date format.

What I see when I open up the spreadsheet is something like 12/29/09 and the program sees 40176.

I figured out this is the value present when I change the column to general text.

My question is how can I read the value 12/29/09 instead of 40176 or how can I change 40176 into a valid date?

My program is in c# Must be read in in c#


Here is sample code of my connection if it helps any.

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
string myPath = @"C:\Test.xls";
excelApp.Workbooks.Open(myPath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);

 Microsoft.Office.Interop.Excel.Sheets sheets = excelApp.Worksheets;
 Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
 excelApp.Visible = true;

 if(((Microsoft.Office.Interop.Excel.Range)excelApp.Cells[r, 1]).Value2 != null)
     DateString = ((Microsoft.Office.Interop.Excel.Range)excelApp.Cells[r, 1]).Value2.ToString();
From stackoverflow
  • You can use DateTime.FromOADate() to convert the double into a DateTime value.

  • As Reed Copsey said, the DateTime.FromOADate() method will convert the value into a DateTime. If, however, you want 12/29/09 as a string, and don't want to manipulate it any further, you can use cell.Text instead.

drag and drop in winforms or wpf

i would like to create a simple winforms or wpf application where i can drag and drop virtual "cards". this below is not exactly what i want to do, but it the closest thing that i found on the web to represent the user interface.

http://www.greenpeppersoftware.com/confluence/plugins/advanced/gallery-slideshow.action?imageNumber=1&pageId=24870977&decorator=popup&galleryTitle=Task+board+and+transitions

so basically i want to have columns in the GUI where i can drag and drag from one to the other.

My questions are:

  1. would this be easier in winforms or wpf
  2. where do i start?
From stackoverflow
  • It would probably be slightly easier in WPF because of the Thumb control which provides easy to use built-in support for dragging. (If I remember correctly, in WinForms you would need to handle the mouse events yourself, whereas the WPF Thumb does this for you and translates them into drag start, delta and end events.)

    However if you are much more familiar with one framework than the other than that would probably dwarf the difference that the Thumb control would make.

    You should also have a look around for toolkits/frameworks that could handle this for you -- I think they exist for both WinForms and WPF (not sure though).

  • In both winForms and WPF dragging and dropping can be done in a similar way by working with the events on the target DragOver and Drop.

    However with WPF you have other options. You will also be able to make the application look better by having a thumbnail as you drag (this is possible in winforms but harder to achieve).

    Have a look at this WPF sample it uses a helper class and think it does exactly what you need.

  • I agree with John in that WinForms and WPF are quite close to one another w.r.t. drag'n'drop. But WPF offers more of a "common base" for ItemsControl, allowing to implement more independent of the final UI elements used (ListBox, ListView, TreeView... can be easily switched). And obviously WPF allows much more fancy effects.

    I would strongly recommend this blog post: http://www.beacosta.com/blog/?p=53 both for some drag'n'drop basics and for a clean WPF drag'n'drop approach. It shows a nice implementation of a rather generic helper for drag'n'drop from/to WPF ItemsControls, I really like that "Insertion Adorner". And I do like that the drag'n'drop code is nicely separated from the user control itself by using attached properties, which makes it much easier to use and maintain.

  • A good way for darg and drop are explained as

    Detect a drag as a combinatination of MouseMove and MouseLeftButtonDown

    Find the data you want to drag and create a DataObject that contains the format, the data and the allowed effects.

    Initiate the dragging by calling DoDragDrop()

    Set the AllowDrop property to True on the elements you want to allow dropping.

    Register a handler to the DragEnter event to detect a dragging over the drop location. Check the format and the data by calling GetDataPresent() on the event args. If the data can be dropped, set the Effect property on the event args to display the appropriate mouse cursor.

    When the user releases the mouse button the DragDrop event is called. Get the data by calling the GetData() method on the Data object provided in the event args.

    You can find the complete article here

PHP and HTTP Header Line Breaks: What character used to represent?

I'm looping through each line of a series of CURL returned http headers, trying to detect when one ends and the next begins. I know that an http header terminates with an empty line, but what character is used to represent this line break in php? I've tried with \n but it doesn't seem to work. I certainly could be doing something wrong.

What character is used to represent the line break used to terminate a header?

Here's my existing code:

$redirect = '';
$regs = '';
foreach ($curl_response as $line)
{ 
 if ($line != "\n")
 { # line is not a linebreak, so we're still processing a header block

  if (preg_match("(HTTP/[0-9]\.[0-9] [0-9]{3} .*)",$line))
  { # line is the status code
   # highlight the outputted line
   $output .= "<b style='background: yellow;'>$line</b>";
  }

  elseif (preg_match("/^Location: (.*)$/m",$line,$regs)) 
  { # the line is a location header, so grab the location being redirected to
   # highlight the outputted line
   $output .= "<b style='background: purple; color: white;'>$line</b>";
   $redirect = $regs[1];
  }

  else 
  { # some other header, record to output
   $output .= $line;
  }

 }

 else 
 { # we've reached a line break, so we're getting to a new block of redirects
  $output .= "\nreached line break\n";
  if ($redirect != '')
  { # if we recorded a redirect above, append it to output
   $output .= "\n\nRedirecting to $redirect\n\n";
   $redirect = '';
  }

 } 

}

echo $output;

Solved - Turns out that \r is what I should have been matching on. Very odd. Not sure if this changes per site, or if it's something set in curl. So far its \r on all sites I've tried.

Edit 2: Doh. I think it's because in order to get the header into an array of lines, I exploded it on \n. So perhaps any \r\n are now just \r...

$c = explode("\n",$content);
From stackoverflow
  • You need to also check for "\r\n" and "\r", as those are also valid terminating empty lines.

    When in canonical form, media subtypes of the "text" type use CRLF as the text line break. HTTP relaxes this requirement and allows the transport of text media with plain CR or LF alone representing a line break when it is done consistently for an entire entity-body. HTTP applications MUST accept CRLF, bare CR, and bare LF as being representative of a line break in text media received via HTTP.

    -- HTTP/1.1: Protocol Parameters - 3.7.1 Canonicalization and Text Defaults

  • The headers terminate with a double line break with no space in between (ie an empty line). A line break can be either "\n" or "\r\n" (or, as I have just learned, in some cases "\r", but I don't think that's common).

    Perhaps you could match it with a regular expression like

    list($headers) = preg_split('/\r?\n\r?\n|\r\r/S', $httpresponse);