Thursday, April 14, 2011

Virtual inheritance in C++ usages/tricks

I've never used it in the professional software even though in our shop, and others I have worked for, we design large scale systems. The only time I messed with virtual inheritance was during my interview in a company. Nonetheless, I played with it during afterhours.

Do you guys use it? Do you understand how it works in depth (how most popular compiler vendors implement it)? I would really like to know how it is used in professional software, if at all. Tricks and tips would be appreciated, too.

To me, virtual inheritance was just a solution to an infamous diamond problem. Hence, it never found its way in our software, as we don't have in our architecture MI resulting in the diamond.

Thanks.

From stackoverflow
  • The main point with virtual inheritance is to prevent derived classes from inheriting multiple copies of different superior classes. This can occur in any case where there may be multiple inheritance -- as you correctly note, the "diamond problem", which is to say where the inheritance graph is a DAG instead of a strict tree.

    The C++ FAQ goes into it in some detail. I'd also recommend the C++ FAQ Book; I used to work for the authors and they're quite good.

    Dan : +1 for the book and the site, I have the one & frequent the other :-) Smart people who can explain things well... the 2 often don't go together.
  • I don't see why you'd want to use it if your architecture doesn't use multiple inheritance.

    If you did happen to use MI I can't see why you wouldn't use virtual inheritance. There doesn't seem to be any drawback except for remembering to add the virutal keyword in the right places.

    Tom : Here's two reasons: 1) virtual inheritance requires subclasses to be aware (and if you refactor virtual bases, it impacts all of your users needlessly). 2) virtual inheritance adds runtime cost to every constructor and destructor. Why pay that cost when it's almost never necessary?
    : Can you explain how refactoring virtual bases is different than refactoring normal bases in a diamond-inheritance situation? For the constructor cost, isn't it quicker because when using a non-virtual base class it needs to make multiple copies of the base whereas with virtual it's just pointers?
    j_random_hacker : Another disadvantage of virtual inheritance is that you can no longer downcast from pointer-to-Base to pointer-to-Derived with static_cast. See this illuminating post for details: http://groups.google.com/group/comp.lang.c++.moderated/msg/631ac4837db0abbb
  • I've never used it in the professional software even though in our shop,

    Do you use iostream? We do. Look up the design of iostreams and you'll know you've been using virtual inheritance.

  • Virtual inheritance can also be used to make a class a final class, i.e. to make it so that no other classes can derive from it. I grabbed that trick once from Stroustroup (http://www.research.att.com/~bs/bs_faq2.html#no-derivation).

  • I've worked with several commercial libraries that required its use. For example, the library that Reuters supplied to access real-time financial market data used to require you to derive your listening classes from several base classes (don't know if it still does) and this needed virtual inheritance. It was no big deal, once you realised you had to use it - a fact not totally well documented.

  • for gaining further insights regarding virtual inheritance you could also check out this post: http://cpptalk.wordpress.com/2009/08/11/constructor-selection-with-virtual-inheritance/ I have in-depth knoweldge of the mechanism, so if you have a specific question - just go ahead and ask.

How to assign a String from a text file into integer array for Java?

How to assign a String from a text file into integer array for Java? I had saved the integer array into a text file, but now how can I retrieve all the integer array from the text file without any modification? I want the integer array retrieved same as before it stored into the text file. Below is part of my code:

BufferedWriter f1 = new BufferedWriter(new InputStreamReader(new FileInputStream("Input.txt")));

int a[ ] = yes(test, test.length); //go to yes method,return value to array  
for(int i = 0; i < a.length; i++)  
{  
    f1.write(a[i]);  
}  
    f1.close( );  

BufferedReader f2 = new BufferedReader(new InputStreamReader(new FileInputStream("Input.txt")));  
String src;  
while((src = f2.readLine( )) != null)  
{  
    String[ ] s = src;  
    int a[ ] = Integer.parseInt(s);//same with before it saved  
    ... ...  
}

(incompatible types found)
How to reserve the originality of the integer array(a[ ]) after saved and retrieved from the text file? Thanks!

From stackoverflow
  • You need to somehow separate the integers. The simplest solution is to write each one in a separate line. Or use a comma separated list and then use String.split(",")

    ng : Currently he is not writing integers, he is writing characters.
    kgiannakakis : That is what I've suggested. Reformat the way the data are being written.
    ng : Its got nothing to do with format, he is not even writing the valid data.
  • The way you have written the characters is totally wrong, you are writing the character representation of the int. Internally this is written as a char. You need to write your integers like so.

    for(int i = 0; i < a.length; i++)
    {
       String value = String.valueOf(a[i]);
       f1.println(value);
    }
    

    This should be compatible with how you are now reading your integers.

  • This looks like homework. Anyway, here's my test code:

    // Write integers to a file, each on a different line
    BufferedWriter f1 = new BufferedWriter( new FileWriter( new File( "Input.txt" ) ) );
    int a[] = new int[]{ 17 , 42 , 37 };
    for ( int i = 0 ; i < a.length ; i++ ) {
      f1.write( String.valueOf( a[ i ] ) + "\r\n" );
    }
    f1.close();
    
    // Read integers from a file, assume each value on a different line
    final BufferedReader bufferedReader = new BufferedReader( new FileReader( new File( "Input.txt" ) ) );
    String line;
    final List< Integer > values = new ArrayList< Integer >();
    while ( ( line = bufferedReader.readLine() ) != null ) {
      values.add( Integer.valueOf( line ) );
    }
    bufferedReader.close();
    
    // Convert List elements to array
    final int[] valueArray = new int[ values.size() ];
    int counter = 0;
    for ( int value : values ) {
      valueArray[ counter ] = value;
      counter++;
    }
    
    // Print array values
    for ( int value : valueArray ) {
      System.out.println( "value: |" + value + "|" );
    }
    

    The output is as follows

    value: |17|
    value: |42|
    value: |37|
    
    dhiller : This is a List instance holding Integer objects. Please see the collections framework in java for further information.
    dhiller : Small hint: A List implements the Iterable interface so you can use it in a new for loop.

safari problem

Hi,

I'm using Infragistics controls in my web application(ASP.net)... and I'm using Ultra web grid in that too.... my application works well in IE and Mozilla . but in safari I'm getting the following error::(which is very vague and fuzzy) ... CAN U PLZ HELP ME in this?? wat's this error ? Does it have to do with compatibility problem?? how to resolve this ?

Index was outside the bounds of the array.

Description: An unhandled exception occurred during the execution of the current web *request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.IndexOutOfRangeException: Index was outside the bounds of the array.
Source Error: 
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace: 
[IndexOutOfRangeException: Index was outside the bounds of the array.]
   Infragistics.WebUI.WebCombo.WebCombo.LoadPostData(String postDataKey, NameValueCollection values) +611
   System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +611
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2877
Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053*
From stackoverflow
  • Very likely it's a browser compatibility issue, I suggest you contact Infragistics directly and ask them if their components are supported in Safari. If they are then you should report this issue to them as a bug.

    stack_pointer is EXTINCT : ok thats fine... hey i posted in Infragistics forum.. and still couldnt get any replies... :(... It has been a day since :(
  • I'm having the same problem with the WebCombo control, and it seems to be a real compatibility issue. Infragistics response so far has been to update to the latest version of their controls, which is not an option to me right now:

    Infragistics forum's question about this issue

As a programmer,what does one need to know after university?

I've been talking to some computer science students lately who've asked me what they should know after university. They fear to have the wrong skills and knowledge to start a career in programming.

What do you consider essential skills and knowledge to get a good start into a programming career? What do companies demand?

Some other questions come to mind:

  • Is mathematics essential to programming?
  • How much theoretical computer science does one need to know?
  • Should one learn common programming languages, or does one need a foundation in other languages like Lisp or Haskell too, or what other languages?
  • To start a career, does one need a thorough understanding of computer hardware, ICs and physics or more?
  • How much ad what practical experience do you need to show a future employer?
  • How has the job market changed, because of the crisis and do you need to know more and be better to start a career?
From stackoverflow
    • Source control.
    • An OO language and a scripting language.
    • Communication skills.
    Cybis : Why the heck was this voted down? Source control and scripting are both vitally important and often missing from the university curriculum.
  • Communication skills would be right up there.

    Haven't really answered your question though. I'm no expert by far, but I'm not sure mathematics, theoretical computer science and hardware are of that much value in the real-world, unless you're doing hardcore embedded systems or some such. But for most "business" applications I would have to say just good communication skills and a quick logical mind are enough. The best thing about university to me is that it teaches you to learn; speaking for myself, when I graduated from my course I didn't actually know anything of use. It's all about how you learn after that.

    As for the effect of the economic crisis, couldn't say - we haven't been quite as hard-hit in Australia thankfully!

  • I feel that the ability to evolve your IT skills independently beyound what you have learned at university is the most important skill you need afterwards. In my opinion the study should first and foremost lay a good basement on which you can build further knowledge and skills.

    For example, there is no point in learning all programming languages out there during your studies, it is more important that you learn a few plus a structured approach to learning new languages quickly.

  • What is important depends on whether you're going to work banking systems, mobile phone games, scientific software, web apps, or whatever. In my experience:

    • Basic math is important. Advanced topics are rarely needed.
    • Basic theory (data structures etc.) is a must, but again, advanced theoretical topics are rarely needed in practice.
    • I think it's more important to know real world languages (C++, Java) and libraries than the ones that are being used at theory classes.
    • Knowledge of hardware can be quite essential. It comes up every now and then, because your code runs on hardware, after all. You don't need to exactly know the physics of how a transistor works, but things like clocks, timings, buses - the ones next to your code - are important.
    • Even a modest actual project completed is more important in my eyes, than some degrees.
    • The importance of versatility and social skills are emphasized when times are harder.
  • A few important things that leap to mind, in no particular order are:

    • The recognition that learning didn't stop after classes are over.
    • A mastery of the written word in a minimum of one living human language.
    • Enough public speaking skill to lead a technical discussion. More is better...
    • Enough math to know when to go find a mathematician.
    • Enough statistics to know when to go find a statistician.
    • Get at least some experience with real hardware: make a PIC blink an LED in morse code, or even better, recognize simple commands in morse code. It isn't critical that they like hardware, but they should at least know there are electrons being herded around by their code.
    • Read the source to at least one OS kernel. Any kernel, at any scale from RTOS to a desktop or server OS of your choice.
    • Basic knowledge of assembly language of at least one CPU, but more is better.
    • Enough knowledge of floating point to know that you don't know all the raw edges.
    • Mastery of some non-programming art or skill.

How to consume and re-expose a Win32 type library using Delphi Prism

I currently have a Win32 type library created in Delphi which I need to consume, implement and re-expose via .NET. What are the steps necessary to bring the TLB into Prism so the interface can be implemented?

From stackoverflow
  • the .NET 2.0 sdk tool TLBIMP can create an assembly from a TLB file. Something like:

    tlbimp.exe mytlb.tlb /out:MyTLB.Import.dll /namespace:MyTLBImport

    Make sure you use /publickey /keyfile or /keycontainer if you want to sign it later on.

    After the import, just reference the dll and use it as a regular library.

What tools does your team use for writing user manuals?

Basic requests are:

  • human readable / text format (for easy version control)
  • online (for collaboration)
  • easy formatting (markdown ok, html is too much)
  • strict formatting (so authors don't invent new types of titles, bullets etc.)
  • exportable to PDF, HTML
  • easy backup and deployment (so we can "deploy" to customers site as read only version)

We are thinking about using some kind of wiki engine, but it would need to use files for storage or have other means of "deployment" to customer and be easy to install/maintan. Also, it would have to be free / cheap (confluence is way too expensive)

Any suggestions?

Edit: I'm not looking for tools to document code, we have that covered using Sandcastle.

From stackoverflow
  • We use help and manual for manual and help file. There is no html export, but it provides html help, winhelp, pdf and some more formats.

    Conrad : I've been very happy with Help And Manual. Easy to use and very powerful
  • try Dikiwiki

  • We use Word. It gets put into our version control, so we have history (there's a documentation folder linked to every project). Formatting can be controlled using templates, all of which we now have set up, so making changes is easy to do within the layout standards. The files can be exported to PDF. You can publish them as read-only docs for sharing with users.

  • Although it may not answer all your requests, DokuWiki may be worth taking a look at.

    As with other wikis, it has a simple syntax, and has version control to track revisions, generates table of contents, and a full-text search feature which can come handy for a help system.

    You may want to evaluate the feature list to see if it will meet your needs.

    Also, there seems to also be a good collection of avaialble plugins. Although I haven't used DokuWiki or its plugins, there seems to be plugins available for PDF export as well.

    David Vidmar : I need to do some more testing, but this seems to be exactly what I have been looking for! Except the fact that I need to have PHP running in order to use it. :) Thanx!
  • For our API, we use Doxygen, which is great.

    Daniel Silveira : He said: "USER" manuals
    unwind : @Daniel: An API has users, too ... So it's not totally unreasonable, I'll leave the answer.
  • We're using a wiki. I recommend MoinMoin because

    • very simple to setup (even on a Laptop)
    • very simple to backup (you can even commit the wiki to a version control system to sync it between, say, laptops for offline usage).
    • nice syntax
    • easy to extend
    • Easy to search

    We're not using something like Word because:

    • Documentation rots too fast
    • Searching all documents is a pain
    • Linking between information bits is a pain
    • No diff between versions
    • Binary format which craps the hell out of any VCS
    • No deep bookmarks
    • Documents grow too big and then they become clumsy: Split (and no searching anymore) or wait ages to load.
  • LaTeX

    Omar Kooheji : I like LaTeX I wrote my dissertation in it, downvote was undeserved.
    Adam Jaskiewicz : Agreed. LaTeX is pretty useful for this kind of stuff, and meets 5/6 of the requirements (it isn't "online", but LaTeX docs in version control work pretty well for collaboration).
  • We've had great success with DocToHelp. It works great with Microsoft Word based documentation as well as other forms, and it's even got some great integration features for Visual Studio.

    The best part is once you've got a core document base imported into DocToHelp, you can choose any one of a number of export formats be it WinHelp, HTML Help, Java Help or the nice and fancy searchable Net Help.

  • You don't mention the language/framework that you are using. There are really good documentation tools out there, but some of them are specific to what you are developing in. We are a C# shop, so my answer will only apply to you if you are using .NET.

    We use Sandcastle, which is not only free, but open source. While people primarily think of it as strictly an application that generates documentation from XML Documentation, you can provide your own content in MAML. It can target both CHM and web site deployments, which meets our needs. There are some additional tools that can provide things such as marking favorites and topic ratings to my understanding, but we have not started using them as of yet.

    This provides us with both internal and external documentation. Since we also use Team Foundation Server, we use the built in Wiki on the Team Project in Sharepoint, but that is more geared towards project collaboration.

    Edit: Fixed broken link, and also wanted to mention that there are other tools in conjunction with Sandcastle, that we use. Things such as Sandcastle Help File Builder and GhostDoc are common tools. The first to edit the Sandcastle projects and MAML, and the second to improve comment quality in the code.

    David Vidmar : We are C# / .NET shop. And you missed the title of the solution. I can only see "we use ." :)
    joseph.ferris : Corrected and expanded. Sorry about that!
  • For doument the code I use Doxigen. I prefer the linux version, I had have problems with a few features in the Windows version

  • For "manuals", Docbook. It's an SGML dialect designed for technical documentation. http://www.docbook.org/ . It may not meet your "easy markup" criterion but it definitely produces nice output in LaTex (can be converted then to PDF) and good HTML output if you cook up your own CSS stylesheet for it. Text files kept in version control. All programs also use a library that combines command line argument parsing with "--help" output in a choice of formats (normal, man page, and docbook). For the API reference, doxygen of course.

  • At my current we churn out single use software so documentation often gets put ont he side line and is done in word.

    At my last job however the documentation team seemed to continuously rant and rave about mad cap software's product "Flare" it allows you to write in one format and publish to many mediums so your manual can also be your online help or a website, etc...

  • My company uses MediaWiki and TikiWiki for most documentation. We also have a guy that compiles stuff into MS Word and PDF formats for printing/sending to customers. I'd recommend you avoid TikiWiki like the plague. MediaWiki is great, both because it is really easy to use and because everyone knows how to use it -- it's the de facto standard wiki, and deservedly so, IMHO.

  • For some time we were using DocBook, but it was very hard to extend with more advanced, and necessary features (syntax highlighting, splitting into several files, multilinguality management etc.). Later, we decided to write our own system from scratch and release it as open-source: link text. It uses plain text files and Markdown as the syntax language, and now we have everything we need. The disadvantage is that currently there is probably no Markdown parser that produces something else than HTML output. For now this is enough, but we are thinking about implementing PDF support quite soon.

    Moreover, we are maintaing MediaWiki as a community-based help.

  • I can not say enough good things about Asciidoc. It has a very simple markup syntax, can generate everything from pdf to roff, portable to implement and very easily inserted into any wiki with only a few minor changes.

    Even in its markup state, its very, very easy to read. The only thing I have to fiddle with when using it are tables, but that's not too difficult.

    If you keep the text formatted files in your repository, revision tracking is quite simple.

    For code doumentation, I use Doxygen.

  • MindTouch has had an open source wiki for free download for quite some time and recently released a commercial version of that product specifically for technical documentation. It includes an Intelligent Documentation Framework, that provides guided authoring for common docs like FAQ's, Tutorials, References, Feature pages, etc.

How painless is it to upgrade Symfony applications from 1.1 to 1.2

I am currently developing a system on a server running PHP version 5.1.6 thus I am forced to use Symfony 1.1 in the current environment. I am planning to migrate the application from 1.1 to 1.2 in the somewhat near future and I was wondering if anyone has any experience with this? I have attempted to migrate a system from 1.0 to 1.1 and that was a major pain in the rear.

How has it been for anyone out there migrating from Symfony 1.1 to 1.2?

From stackoverflow
  • for me, migration to 1.2 was fairly painless. the upgrade script should do all hard work.

    the biggeest problem will be migrating to propel 1.3 if you have used 1.2 ( default with symfony 1.0.x and 1.1.x). if you were using propel 1.3 before ( with sfPropelPlugin) or Doctrine there shouldn't be any problems.

    Another one will be porting admin generated modules to new admin generator, but in 1.2 the oldones still work for now.

    those listed above are the biggest changes in 1.2.

    and i love 1.2 for it has lots of new cool stuff ( REST routing, new admin generator, some minor fixes etc.)

  • Man...my 2 cents is that it all depends on how many forms you have in your application, that was by far the most painful part. Symfony 1.2 has an entirely new form system.

    you can always do compac10 = true or whatever ...to make your old code compatible,..

    Symfony 1.2 does have many new useful widgets,..and propel 1.3 is a significant improvement, fixed some bugs that I was actually running into.

  • It should be fairly easy if you didn't use custom SQL queries with Propel (i.e. manual hydratation) as Propel 1.3 switches to PDO. I did migrate an 1.1 app to 1.2 and I had nothing to do except running the automatic upgrade script.

How to embed Windows Form in unmanaged ATL GUI?

I have a Windows form user control that is made COM visible. Now I want to embed that control into an ATL dialog GUI.

The ATL project (unmanaged C++) shall only get the progID of the winform and dynamically create and embed it at runtime.

Is this possible and if so, how do I do it?

From stackoverflow
  • I am not sure about ATL but this can be done easily in MFC using CWinFormsView and CWinFormsControl classes.

    I think there is no bulitin support to host a WinForm Control in an ATL Window but I think you can do it by simple getting the HWND of your winform control and setting your ATL control as its parent. This might be a tough road though.

    This seems to be a similar type of thing. I havent tested it myself though.

    Link

    HS : The approach described in the linked page is not applicable, because it is a winform and not an ActiveX. The latter is not really supported in .Net. When using winforms this way, unexpected things are happening.
    HS : When using CWinFormsControl I have to supply an existing winform class name, because it is a template. However, I want to create an arbitraty winform with a given progID. The actual class is not known at compile time!
  • I figured out a way to get it to work.
    The following code is using a CWnd called m_Control that is made to host a winform via a little documented version of CreateControl. Seems to work fine so far. If anyone sees any drawbacks, please comment or respond.

    AfxEnableControlContainer();
    Microsoft::VisualC::MFC::CControlCreationInfoEx i;
    i.Init(System::Type::GetTypeFromProgID(gcnew System::String(sProgID)),
           CControlCreationInfo::ReflectionType);
    i.m_clsid = CLSID_WinFormsControl;
    POINT pt;
    pt.x = pt.y = 0;
    SIZE sz;
    sz.cx = sz.cy = 100;
    m_Control.CreateControl(i, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN,
                            &pt, &sz, CWnd::FromHandle(m_hWnd), ID_CONTROL);
    
  • should sProgId is of WinFormControl? i didn't find prog id of that, please explain

    HS : You basically make your Winform COMvisible, sign it with a key file and register it via regasm. It then should have a ProgID.

Request format is unrecognized for URL unexpectedly ending in

This is not a question - posting it here for reference:

When consuming a WebService, I got the following error:

Request format is unrecognized for URL unexpectedly ending in /myMethodName

From stackoverflow
  • Found a solution on this website

    All you need is to add the following to your web.config

    <configuration>
        <system.web>
        <webServices>
            <protocols>
                <add name="HttpGet"/>
                <add name="HttpPost"/>
            </protocols>
        </webServices>
        </system.web>
    </configuration>
    

    More info from Microsoft

    Daniel Brink : would this also work on IIS7 .Net2.0 apps ?
    roman m : i THINK all you need to do is switch to
    Daniel Brink : i kept it as is and for now the error seems to have gone away. if i see the error again i'll move the webservices configs into the webserver section.

Want to restore master database ....?

Hi i want ot restore master database .

FOr that i try to start my instance in single user mode....

But give below error:

C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn>sqlservr.exe - m -s TST_01 2009-03-18 13:17:35.18 Server Authentication mode is WINDOWS-ONLY. 2009-03-18 13:17:35.18 Server Error: 17112, Severity: 16, State: 1. 2009-03-18 13:17:35.18 Server An invalid startup option was supplied, either from the registry or the command promp t. Correct or remove the option. Please help me.....

From stackoverflow
  • Maybe it's just a typo in your message, but in the command you wrote there's a blank between the first hyphen and the letter "m". You wrote - m instead of -m.

Capturing datagrid cell header click

Hi,

I just want to check if a click is made in an datagrid whether the click is made on a header r on a cell content.

I am facing a problem when...

when cell is clicked i am manipulating with the data. But if the header is clicked for sorting ,same cell click event is triggered.

How can i stop this ?

From stackoverflow
  • In your event code, check if

    e.RowIndex >= 0
    

    prior to executing the code. If the user clicks on the header cell, the RowIndex will be -1 therefore the code will not be executed.

Capturing all the data that has changed during a Linux install

I am trying to figure out which files were changed when I run an app install via make install. I can look at the script, but that calls other scripts and may or may not touch other files, etc. How can I do this programmatically?

From stackoverflow
  • Implementation: http://asic-linux.com.mx/~izto/checkinstall/

    Several ways come to mind. First, use some sort of LD_PRELOAD to track all files opened. Second approach, compare filesystem before and after.

  • If your kernel supports it, you can use inotify (a handy interface is inotify tools) and watch your home directory, if the package was configured with --prefix=/home/myusername

    I've noticed that checkinstall (using installwatch via LD_PRELOAD) does not always catch everything, the last time I used it it did not catch empty directories that were created for spooling, which caused the subsequent generated .deb's to break.

    Note, don't use inotify if you are installing to /, in that case you have to use installwatch or just read all of the makefiles / install scripts closely.

Most stable solution for doing AJAX with ASP.NET as a backend?

I'm planning a ASP.NET project for which I'm going to use AJAX. I'm researching all the available technologies for doing so in the .NET world. I need a solution that is well documented and stable. The current solutions I've found are: 1. ASP.NET AJAX UpdatePanel 2. ASP.NET AJAX with Web Services + JQuery 3. JQuery + Http Handlers

In the second and third solutions the backend would only send JSON or XML messages to the client.

From stackoverflow
  • All will work but I've had most performance and stability with using JQuery and a script service.

    An update panel will work but as its designed to work in the general case it can be a little bloated if you aren't careful. One reason being is that it posts the viewstate back with each update.

    I recommend you check out the site: encosia.com as it has a number of posts on how to use script services and page methods. Then you can make a more informed decision. I would say that I've not used page methods and probably won't but that's entirely for personal reasons.

    One other thing to consider will be any mvc you may end up doing. The general consensus is that it's a whole lot easier with JQuery. Added to that Microsoft have officially adopted it and also provide intellisense in VS2008.

    All compelling reasons to include at least some of it in your project. In mine I only use the built in ScriptManager when I absolutely have to.

    HTH!

    S

  • In my experience the best way to go is JQuery with WCF with JSON webservices.

    The reason is:

    1. ASP.NET ajax is gives you alot for free in terms of coding but is bloated from the start and needs to be stipted and slimed. On the other hand you have JQuery that you needs more development but is light weight. JQuery has a great plugin library as well.

    2. XML is to slow, JSON is fast.

    Thats how I would do it today.

vc++ install creator

VC++ 6.0 Project

After Completing my project i created the project EXE ,using Create Installer,

But the problem is without vc++ 6.0 software the EXE project it will not execute ,

it shows error:

This application has failed to sart because MFC42.DLL has not found,Re-installing the application may fix this.

When i insatll vc++ 6.0 software then it will fine no error.

plz any body help me that the without the vc++ 6.0 s/w the project must be execute.

or plz tell me how to make the project EXE(setup)

From stackoverflow
  • Check if mfc42.dll is freely distributable. I think it's part of Microsoft's runtime libs, and thus should be legal to redistribute, but you need to verify this (unless someone else can verify it).

    Then just include that dll with your setup, so that the dll is in the same folder the exe is started from.

  • You might want to consider moving to a more widely used installation utility. A lot of open source projects (and a fair number of commercial projects as well) use InnoSetup to build installers.

    Regardless of the tool you use, the general process is the same.

    1. Create a Release build of your program.
    2. Identify all the files that need to be installed. (Try the depends.exe tool that came with Visual Studio to learn what DLLs are required.) Don't forget about help files and samples.
    3. List files and other install-time tasks (creating shortcuts, registering DLLs, and so forth).
    4. Build and test the installation package.

    Testing installations can be difficult, and really should be the subject of a whole other question. Be careful that what is installed can be uninstalled, and that running the installer again does something sensible. It may also be a good idea to make sure that you have a way to detect if a user is trying to install an update while an older copy is still running, and to take an appropriate action when that happens. (It will.)

how to create command application like run command for vista

how to create application like window run command using C#. When i insert any command (for example: ipconfig) , this return result (for example: 192.168.1.1) on the textbox.

  1. how to get windows command list?
  2. how to get command result?
  3. how to get installed application list on the machine?
From stackoverflow
  • Create a Windows Forms application using the wizard. Draw a text box and a button. Add a Click handler to the button which takes the contents of the text box and launches a process. Use the Process class. That class also has a StandardOutput property that you can read the output from so you can put it into the text box.

    You may find that to use many Command Prompt commands, you need to type CMD /C in front, because they aren't separate programs from the command interpreter.

    As for discovering a list of commands, that's not generally possible. A command is just a program (or a feature of the CMD command interpreter). You could search the hard drive for .exe files, but then many of them wouldn't be suitable as "commands".

  • (1) The command list will most likely come from whatever executables are found in your %PATH%. You can figure out your list by finding all .exe/.bat/other executable files in every folder specified by %PATH%. You may not even need to know which apps are available, the Process.Start method will find them for you. (see below)

    (2) You can run a command-line tool programmatically using:

    System.Diagnostics.Process.Start("notepad.exe"); // located using %PATH%
    

    To capture the output, you have to redirect it like this:

    System.Diagnostics.ProcessStartInfo psi =
        new System.Diagnostics.ProcessStartInfo(@"ipconfig");
    psi.RedirectStandardOutput = true;
    psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    psi.UseShellExecute = false;
    
    System.Diagnostics.Process myProcess;
    myProcess = System.Diagnostics.Process.Start(psi);
    System.IO.StreamReader myOutput = myProcess.StandardOutput; // Capture output
    myProcess.WaitForExit(2000);
    if (myProcess.HasExited)
    {
        string output = myOutput.ReadToEnd();
        Console.WriteLine(output);
    }
    

    (3) Probably the same answer as 1

Dynamically load additional jar files using Web Start / JNLP

The Web Start Developers Guide states

All application resources must be retrieved from the JAR files specified in the resources section of the JNLP file, or retrieved explicitly using an HTTP request to the Web server.

Storing resources in JAR files is recommended, since they will be cached on the local machine by Java Web Start.

Now, I have some resources I want to dynamically load after my application has been started (for example OSGi bundles). I can do this using plain HTTP, but I would like to make use of Web Start's support for local caching and versioned/architecture-specific resources.

Is there a way to download additional jar files from the original code base (as specified in the application's jnlp file) using the Web Start infrastructure?

Or alternatively: is there already an established way to integrate OSGi and Web Start that would relieve me of the task to install bundles from the Web Start server?

From stackoverflow
  • If you make your application in itself an Equinox-based OSGI application, you can web-start it with all the addition bundles you need.

    This article "WebStarting Equinox OSGi Apps" can give you a good introduction on the required settings.

    • All bundles have to be deployed as signed JAR files
    • You need a feature that contains all the necessary bundles
    • When exporting the feature, make sure that PDE creates a JNLP (Java Network Lauching Protocol) file (a checkbox in the export wizard) for this feature
    • Provide a root JNLP file for you application
    • Deploy your application to a web server and make sure that the web server is aware of the application/x-java-jnlp-file mime type

    He also has an OSGI demo.

    Thilo : Aha! The article makes use of an "extension" tag in the JNLP file, something that was not mentioned in the Developers Guide. I'll see if I can make that work, too. Thanks.
    Thilo : Found two points I do not like about this method: the bundles need to be known at startup time, and Web Start adds them to the boot classpath, from where Eclipse's WebStartMain seems to extract them and start them as bundles again. Still good to see that Eclipse already has this support built-in.
    Thorbjørn Ravn Andersen : The extension tag was afaik introduced with the Java 6 updating of Java Web Start. There was a lot of nice new features.
  • I havent tried it but look at the javax.jnlp.DownloadService API

RunTime Error

hi guys, I am running a shopping cart application in asp.net.I am running my application in IIS.I am getting following error while running.

Server Error in '/cart' Application.

Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

Source Error:

Line 32: --> Line 33: Line 34: Line 35:

Source File: D:\ecomm_3_1_LITE\wwwroot\web.config Line: 34


Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42

Following is my web.config file

Asp.Net Configuration option in Visual Studio. A full list of settings and comments can be found in machine.config.comments usually located in \Windows\Microsoft.Net\Framework\v2.x\Config -->

 <!-- SQL SP & TABLES PREFIX -->
 <add key="SQLprefix" value="gaspprod_"/>


</appSettings>

<connectionStrings> 
<add name="ConnStr" connectionString="Data Source=GRAPHIX\SQLEXPRESS;Initial Catalog=GlitzCart;Integrated Security=True " providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
 <globalization uiCulture="en" culture="en-US"/>
 <!--<globalization uiCulture="hr" culture="hr-HR"/>-->

 <authentication mode="Forms"> 
  <forms name="guru_aspnet_cart"
      protection="All"
      timeout="30"
      path="/"
      loginUrl="AdminLogin.aspx"></forms>
 </authentication>

 <pages maintainScrollPositionOnPostBack="false"
     buffer="true"
      validateRequest="false"
     compilationMode="Auto"></pages>
 <customErrors mode="Off"
      defaultRedirect="error.html"></customErrors>
 <compilation debug="true">
 </compilation>
 <!--<trace  enabled="true"  pageOutput="true"/>-->

</system.web>

<!--disable access to Admin directory for everyone, except for the administrators -->
<location path="admin"  allowOverride="false">
 <system.web>
  <authorization>
   <allow users="admin, admin2, malik "/> <!--ADMINISTRATORS USERNAMES, SEPARATED BY ", " -->
   <deny users="*"/>
  </authorization>
 </system.web>
</location>

<!--disable access to Admin/Modules directory -->
<location path="admin/modules"  allowOverride="false">
 <system.web>
  <authorization>
   <deny users="*"/>
  </authorization>
 </system.web>
</location>

<!--disable access to Modules directory -->
<location path="modules"  allowOverride="false">
 <system.web>
  <authorization>
   <deny users="*"/>
  </authorization>
 </system.web>
</location>

<!--disable access to Modules directory -->
<location path="SQLbackup"  allowOverride="false">
 <system.web>
  <authorization>
   <deny users="*"/>
  </authorization>
 </system.web>
</location>

What change i have to make my application run?Can anybody help?

From stackoverflow
  • The error itself asks if you've enabled the virtual directory and set it as an application.

    Is that the case? Your web.config is in the file root so I would say no.

    Regardless, have you double checked you've enabled applications, enabled the correct version of ASP.NET and ensured ASP.NET is permitted to run.

    If they are all ok then I would recommend you next take a vanilla ASP.NET website/web application (I prefer the latter) and deploy it to that folder. Don't write any code and double check it works.

    If it doesn't then the default web.config doesn't work. It could be an error with your machine.config or something similar. Personally I'd reinstall and re-register .NET. A sledgehammer approach!

    If it does work, then your web.config may be corrupt.

    These are all guess-timates but I hope they help out!

    S

SharePoint ListItem Error: "Value does not fall within the expected range"

Hi I am developing using the SharePoint namespace and I ran into the following error when I try to retrieve a Title field from the list items.

"Value does not fall within the expected range"

I know however that the field exists because I printed out all the fields.

string value = (string)listItem[listItem.Fields["Title"].Id];
Console.WriteLine("Title = " + value);

Update: To what extent does the View that was used to retrieve the list items play a role in what fields will be available? This code fails with the same exception:

SPListItemCollection items = list.GetItems(list.DefaultView);
foreach (SPListItem listItem in items)
{
  try
  {
    Console.WriteLine("Title = " + listItem.Title);
  }
  catch (Exception e) 
  { 
    Console.WriteLine("Exception: " + e.Message); 
  }
}

In both cases the list.DefaultView property was used to retrieve the list items.

From stackoverflow
  • The "Title" field may exist in the list but not in the default view. Can you do this?

    foreach (var item in list.Items) Console.WriteLine((string)item["Title"]);
    
    Ries : Any attempt to reference item["Title"] throws that exception.

Returning data from SQL Server reporting web service call

Hi, I am generating a report that contains the version number. The version number is stored in the DB and retrieved/incremented as part of the report generation.

The only problem is, I am calling SSRS via a web service call, which returns the generated report as a byte array.

Is there any way to get the version number out of this generated report? For example to display a dialog that says "You generated Status Report, Version number 3". I tried passing in an output parameter and setting it inside the storedproc. Its modified when i execute it in sql management studio, but not in the reporting studio. Or atleast i can't seem to bind to the modified, post execution value (using expression "=Parameters!ReportVersion.Value").

Of course, I could get/increment the version number from database myself before calling the SSRS webservice and pass it along as a parameter to the Report, but that might cause concurrancy problems.

On the whole, it just seems neater for the storedproc to access/generate a version number and return it to the ReportingEngine, which will generate the report with the version number and return the updated version number to the WebService client.

Any thoughts/Ideas?

From stackoverflow
  • Since I can't add a comment yet...

    Just throwing this out. Maybe render the report as XML(to a XML document object) and pull your version number out via XQuery or XPath.

    Of course that would probably bugger up your whole "versioning" scheme as you would be rendering the report twice. Perhaps add a parameter that indicates whether or not to increment your version number?

  • Hi,

    As a workaround, you could create a sub-report to do this. Instead of returning the version as an output variable, return it as a column in a resultset.

    Hope this helps,

    Bill

Normal Distribution function

edit

So based on the answers so far (thanks for taking your time) I'm getting the sense that I'm probably NOT looking for a Normal Distribution function. Perhaps I'll try to re-describe what I'm looking to do.

Lets say I have an object that returns a number of 0 to 10. And that number controls "speed". However instead of 10 being the top speed, I need 5 to be the top speed, and anything lower or higher would slow down accordingly. (with easing, thus the bell curve)

I hope that's clearer ;/


-original question
These are the times I wish I remembered something from math class.

I'm trying to figure out how to write a function in obj-C where I define the boundries, ex (0 - 10) and then if x = foo y = ? .... where x runs something like 0,1,2,3,4,5,6,7,8,9,10 and y runs 0,1,2,3,4,5,4,3,2,1,0 but only on a curve

Something like the attached image.

I tried googling for Normal Distribution but its way over my head. I was hoping to find some site that lists some useful algorithms like these but wasn't very successful.

So can anyone help me out here ? And if there is some good sites which shows useful mathematical functions, I'd love to check them out.

TIA!!!

-added
I'm not looking for a random number, I'm looking for.. ex: if x=0 y should be 0, if x=5 y should be 5, if x=10 y should be 0.... and all those other not so obvious in between numbers

alt text

From stackoverflow
  • Well, there's good old Wikipedia, of course. And Mathworld.

    What you want is a random number generator for "generating normally distributed random deviates". Since Objective C can call regular C libraries, you either need a C-callable library like the GNU Scientific Library, or for this, you can write it yourself following the description here.

    dizy : So my confusion is with the fact that... i'm not looking for a random number.... i want to know if x = 5 then y should be 5... if x is 10 then y should be 0 ... and all those other not so easy in between ones :)
  • The thing you want to plot is the probability density function (pdf) of the normal distribution. You can find it on the mighty Wikipedia.

    Luckily, the pdf for a normal distribution is not difficult to implement - some of the other related functions are considerably worse because they require the error function.

    To get a plot like you showed, you want a mean of 5 and a standard deviation of about 1.5. The median is obviously the centre, and figuring out an appropriate standard deviation given the left & right boundaries isn't particularly difficult.

    A function to calculate the y value of the pdf given the x coordinate, standard deviation and mean might look something like:

    double normal_pdf(double x, double mean, double std_dev) {
        return( 1.0/(sqrt(2*PI)*std_dev) *
                exp(-(x-mean)*(x-mean)/(2*std_dev*std_dev)) );
    }
    
    dizy : 1.5 for the std_dev isn't exactly giving me 5, and you said figuring it out shouldn't be particularly difficult, but I can't seem to figure it out :)
  • Try simulating rolls of dice by generating random numbers between 1 and 6. If you add up the rolls from 5 independent dice rolls, you'll get a surprisingly good approximation to the normal distribution. You can roll more dice if you'd like and you'll get a better approximation.

    Here's an article that explains why this works. It's probably more mathematical detail than you want, but you could show it to someone to justify your approach.

  • A normal distribution is never equal to 0. Please make sure that what you want to plot is indeed a normal distribution.

    If you're only looking for this bell shape (with the tangent and everything) you can use the following formula:

    x^2*(x-10)^2 for x between 0 and 10
                    0 elsewhere
    

    (Divide by 125 if you need to have your peek on 5.)

    double bell(double x) {
        if ((x < 10) && (x>0))
            return x*x*(x-10.)*(x-10.)/125.;
        else
            return 0.;
    }
    
    dizy : I have no clue if what I really need is actually a normal distribution, so if you avoid what I called it and just go by my description.... what would it be called?
    dizy : seems like the answer has to be devided by 25 to get it to peek at 5
    poulejapon : Sorry I corrected, by the way isn't it 125? Could you explain why you need such a function so that we can tell you whether you need a normal psf or not?
    kquinn : "if you avoid what I called it and just go by my description.... what would it be called?" You described a pretty generic function of one variable; hard to know if it's a PDF or not. Can you edit the question with what you need it *for*/want to *do* with it?
    dizy : edited the question
    poulejapon : Thank you for editing the question. My answer is correct for your purpose and is very fast to compute.
  • If what you want is the value of the probability density function, p(x), of a normal (Gaussian) distribution of mean mu and standard deviation sigma at x, the formula is

    p(x) = exp( ((x-mu)^2)/(2*sigma^2) ) / (sigma * 2 * sqrt(pi))
    

    where pi is the area of a circle divided by the square of its radius (approximately 3.14159...). Using the C standard library math.h, this is:

    #include <math>
    
    double normal_pdf(double x, double mu, double sigma) {
      double n = sigma * 2 * sqrt(M_PI); //normalization factor
      p = exp( -pow(x-mu, 2) / (2 * pow(sigma, 2)) ); // unnormalized pdf
    
      return p / n;
    }
    

    Of course, you can do the same in Objective-C.

    For reference, see the Wikipedia or MathWorld articles.

  • It sounds like you want to write a function that yields a curve of a specific shape. Something like y = f(x), for x in [0:10]. You have a constraint on the max value of y, and a general idea of what you want the curve to look like (somewhat bell-shaped, y=0 at the edges of the x range, y=5 when x=5). So roughly, you would call your function iteratively with the x range, with a step that gives you enough points to make your curve look nice.

    So you really don't need random numbers, and this has nothing to do with probability unless you want it to (as in, you want your curve to look like a the outline of a normal distribution or something along those lines).

    If you have a clear idea of what function will yield your desired curve, the code is trivial - a function to compute f(x) and a for loop to call it the desired number of times for the desired values of x. Plot the x,y pairs and you're done. So that's your algorithm - call a function in a for loop.

    The contents of the routine implementing the function will depend on the specifics of what you want the curve to look like. If you need help on functions that might return a curve resembling your sample, I would direct you to the reading material in the other answers. :) However, I suspect that this is actually an assignment of some sort, and that you have been given a function already. If you are actually doing this on your own to learn, then I again echo the other reading suggestions.

  • Okay, your edit really clarifies things. You're not looking for anything to do with the normal distribution, just a nice smooth little ramp function. The one Paul provides will do nicely, but is tricky to modify for other values. It can be made a little more flexible (my code examples are in Python, which should be very easy to translate to any other language):

    def quarticRamp(x, b=10, peak=5):
        if not 0 <= x <= b:
            raise ValueError   #or return 0
        return peak*x*x*(x-b)*(x-b)*16/(b*b*b*b)
    

    Parameter b is the upper bound for the region you want to have a slope on (10, in your example), and peak is how high you want it to go (5, in the example).

    Personally I like a quadratic spline approach, which is marginally cheaper computationally and has a different curve to it (this curve is really nice to use in a couple of special applications that don't happen to matter at all for you):

    def quadraticSplineRamp(x, a=0, b=10, peak=5):
        if not a <= x <= b:
            raise ValueError   #or return 0
        if x > (b+a)/2:
            x = a + b - x
        z = 2*(x-a)/b
        if z > 0.5:
            return peak * (1 - 2*(z-1)*(z-1))
        else:
            return peak * (2*z*z)
    

    This is similar to the other function, but takes a lower bound a (0 in your example). The logic is a little more complex because it's a somewhat-optimized implementation of a piecewise function.

    The two curves have slightly different shapes; you probably don't care what the exact shape is, and so could pick either. There are an infinite number of ramp functions meeting your criteria; these are two simple ones, but they can get as baroque as you want.

    dizy : exactly what I was looking for, thanks!
  • y=-1*abs(x-5)+5