Sunday, March 27, 2011

C# if string contains 'abc' within the first X characters...

Hi all, I want to check that Value1 below contains abc but only within the first X characters, how would you write the if statement to check for this?

Value1 = ddabcgghh

if (Value1.Contains(abc))
   {
       found = true;
   }

Thanks

PS It could be within the first 3,4 or 5 characters.

From stackoverflow
  • if (Value1.StartsWith("abc")) { found = true; }
    
    Will : I don't think that meets the requirements.
    Jim Anderson : Isn't that the same as found = Value1.StartsWith("abc") ?
    olle : @Will - true but as in all software projects the requirements have been changed since I had a go at it. @Jim - True but I kept the style of the author of question.
  • You're close... but use: if (Value1.StartsWith("abc"))

  • This is what you need :

    if (Value1.StartsWith("abc"))
    {
    found = true;
    }
    
  • Or if you need to set the value of found:

    found = Value1.StartsWith("abc")
    

    Edit: Given your edit, I would do something like:

    found = Value1.Substring(0, 5).Contains("abc")
    
  • shorter version;

    found = Value1.StartsWith("abc");

    sorry, but I am a stickler for 'less' code.


    Given the edit of the questioner I would actually go with something that accepted an offset, this may in fact be a Great place to an Extension method that overloads StartsWith

    public static class StackOverflowExtensions
    {
        public static bool StartsWith(this String val, string findString, int count)
        {
            return val.Substring(0, count).Contains(findString);
        }
    }
    
    Will : I think he wanted to match "1abcwhatever" and "xyabcwhatever" as well.
    keithwarren7 : he changed that after most of us had written an answer
  • A more explicit version is

    found = Value1.StartsWith("abc", StringComparison.Ordinal);
    

    It's best to always explicitly list the particular comparison you are doing. The String class can be somewhat inconsistent with the type of comparisons that are used.

  • Use IndexOf is easier and high performance.

    int index = Value1.IndexOf("abc");
    bool found = index >= 0 && index < x;
    
  • You can also use regular expressions (less readable though)

    string regex = "^.{0,7}abc";
    
    System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex);
    string Value1 = "sssddabcgghh";
    
    Console.WriteLine(reg.Match(Value1).Success);
    
  • I would use one of the of the overloads of the IndexOf method

    bool found = Value1.IndexOf("abc", 0, 7) != -1;
    

Best file manager for developers

Developers have high demands, so I think many of us are unsatisfied with the average file manager shipped with the operating system.

What is your file manager of choice, and why?

From stackoverflow
  • Given the types of file manipulations that tend to be necessary in development or systems administration, I find the only really usable "file manager" for me is a command prompt, preferably one with UNIX tools, so Cygwin or something similar on Windows. I find that this combined with a tabbed-interface terminal app meets my needs better than any GUI file manager I've tried.

  • My file manager of choice is Emacs. It's pretty consistent across Windows and Unix (which are the only platforms I develop in really).

    Gnu Emacs using mc.el, it's what's on the inside that counts!

    alt text

    In addition to being the most awesomest developer's file manager, emacs can also do:

    • Ediff
    • file compression
    • ftp
    • calendar
    • email
    • usenet
    • source editing: ruby, python, C#, java, sql, etc.
    • interface to make and gdb
    • version control: rcs, cvs, svn
    • extensible via Lisp
    • pyschotherapist
    Jason Baker : Just out of curiosity, what other platform would you develop in? They're pretty much all either windows or a derivative of Unix.
    barneytron : LOL, well you got me there. I'm sure that developers work on other systems too, but I can't think of any off the top of my head.
    Roberto Russo : Emacs is a great file manager, lacking only a decent editor.
    barneytron : I definitely got a good chuckle out of the decent editor comment Roberto! That's a holy war igniter so I better stop now :)
    strager : PLAN9! @Roberto, I lol'd!
    RSabet : and then think of `mc.el`
  • I like Konquerer a lot (on KDE), but I don't use KDE all that much, so I tend to stick with the good old command line. I use the command line less on windows, but let's face it: Windows wasn't made with command line users in mind.

    I personally find that the default file managers seem to do the task I need, but not particularly well. They tend to be easiest when I'm not 100% sure where a file I'm looking for is or when I don't want to type the path (drag and drop for the win!).

    In similar regards, why is it that virtually no OS or window manager's default file manager has picked up on tabbed browsing? I really hate having my taskbar cluttered up with every file system location I have open at the time.

    Quamis : konqueror actually has it(or had it, i dont use it for about 2 years now). I've got used to using mc in a tabbed shell
  • Total Commander is the best.

    alt text

    There is no better file manager for Windows. It has everything you expect and while still being lightweight. It has great OS integration and customization capabilities. Simple UI and keyboard shortcuts for productivity.

    You can use it to:

    • diff / merge files
    • compare / synchronize directories
    • deploy using ftp / sftp
    • start / stop servers
    • browse source tree and edit files
    • start / stop services
    • kill / view processes and registry
    • and pretty much everything file related
    • Pack/unpack files
      ... and more!
    unforgiven3 : No offense, but Total Commander is awful. The UI is cluttered, unintuitive and the application (visually) looks like it was written for Windows 98.
    Midday : I love TC , mostly because I used NC back in those days.
    Midday : for got to say TC (initaly WindowsCommander) was made for Win 3.1 v1 was on 1993-09-29
    Piskvor : TC indeed *looks* horrible, but with all the built-in fuctionality and the customization available, I've never seen a need to look back.
    Simucal : I jacked the feature list from: http://stackoverflow.com/questions/465267/which-programming-tools-do-you-pay-for#465359
    cschol : Best file manager. Period.
    Loren Pechtel : Look ugly--it's modelled after the dos program Norton Commander. Works much better than it looks, though.
    RSabet : pity there is no 64 bit version of TC - author said it is because TC is written in Delphi.
    pbz : TC is keyboard oriented. If you don't do most of the things using the keyboard you're doing it wrong. After you disable all the "useless" UI you're left with a basic two panel window and all the power in the world. If you get to see how an advanced user can use this software you'd think everything else is a toy.
    Jonas Gulle : it's the best filemanager despite its 98ish UI, I grew up with NC so it was a natural transition to TC.
    Jonas Gulle : @RSabet: Isn't the TC ported to C++ Builder since version 6.x something?
    dawntrader : The best file manager. This is the first utility I install every time I have a new PC.
    argh : too much mouse usage
    Thomas : IMHO, that is quite possibly the most heinous UI I've seen. Even for a Win98 UI it would be awful.
    Auguste : @unforgiven3 Total Commander doesn't normally look as bad as that screenshot, at least, not in my experience. A number of those toolbars are unnecessary and can be hidden, same for the tabs. That said, it's not exactly a thing of beauty on the outside, but the true beauty is in the functionality.
  • For me it's SpeedCommander as the ultimate Windows reincarnation of Norton Commander. Price is OK, it's not as ugly as Total Commander, has a 64 bit version, keyboard shortcuts, directory comparison, quick viewers for lots of file types and tons of other features. It even has an optional command line at the bottom of the window where you can drop files from the file window as parameters for other programs. Worth checking out.

    musicfreak : Wow, a third-party file manager that doesn't look like crap! I'll have to check it out.
  • I use FreeCommander under Windows, which has been working fine for me the last 6 months I've been using it. Looks better than most *Commander clones, and does its job.

    I do find, though, that when I as developer am faced with files and directory manipulations that occur frequently, I'm better off writing a dedicated tool. I usually use Python, and because I like (helpful) GUIs, I also use wxPYthon, the python binding of wxWidgets.

    jcollum : Looks good, thanks for the link.
    SchaeferFFM : +1 Same here, on all accounts
    mloskot : +1 I've started to use FC recently, it's best and free replacement for TotalCommander for me, so far.
  • Orthodox File Managers (OFMs) are also known as "Commanders". They are remote descendants of Norton Commander

    Members of this family of file managers with the most prominent example of FAR Manager on Windows and Midnight Commander in Unix use simple yet very powerful command line windows managers with file management capabilities that use three windows: two symmetrical windows with listings of files in two possibly separate directories called panels and one "terminal style" window that initially is minimized to one (bottom) line.

    Modern OFM interface is a Screen inspired generalization of Norton Commander interface and preserved "look and feel" of the original program with its ability to shrink and manipulate visibility of left and right panel windows as well as expand command window (preferably gradually but at least to half-screen and full-screen).

    An advantage of OFM is that this is the only type of file manager that is standardized and the skills are transferable from command line to GUI and back as well as from one platform to another.

    My file manager of choice is FAR + MSYS + Cygwin on Windows and MC on Unix.

    Roman Kuzmin : +1 for Far Manager. I have to add that out of the box it is rather bare and its adoption is not that easy. But the power comes with flexible customization and several hundreds of all sorts of plug-ins. The Colorer provides syntax highlighting in the editor for tons of text formats, programming languages in the first place. .NET modules and PowerShell scripting is provided by FarNet and PowerShellFar. With all these tools Far Manager becomes a real Swiss Army knife for a developer. Besides, it is free.
  • As I do web development mostly, I like to see my thumbnails of images and videos. So, it is rox-filer which is quite a fast and no-frills file manager. I really don't need my file manager to be very user friendly and integrated to my window manager.

  • I use the V fileViewer from http://fileviewer.com/ on Windows. It was conceptually based on the old LIST program, but has progressed far beyond in terms of features and capability, including easy viewing of NTFS Alternate Data Streams.

    RSabet : thats a new one, never heared of that one, thanks.
  • I'm surprised nobody mentioned Altap Salamander. That's what I use on Windows and I haven't found anything better yet.

    RSabet : haven't heared of Servant Salamander for years, didn't know it still was out there ...
    jcollum : 1998 called and they want their ui back.
    Diaa Sami : My only problem with Altap is that it doesn't support tabs ... it's 2010 and it's not even on their roadmap
  • I like Directory Opus for windows. It's got everything I can think of with regards to file management including scripting, macros, etc.

    jcollum : I've used this in the past but it was long long ago. Has it been updated?
    RSabet : There is even a 64 bit version available.
  • I really like Total Commander, especially since it included the "Multiple Tabs" feature, and have been using it for quite a long time (actually since I switched from Norton Commander ;-). What I like about it is that it is highly customizable and can be used with keyboard only, has a command prompt integrated, and it integrates well with Windows - it's just a shame that there is no 64bit version and it's only available for Windows...

  • I use Xplorer2 lite on Vista, because

    1. The Vista File Manager is evil (though slightly less evil if you force it to force it stop changing folder views)
    2. Xplorer2 supports TortoiseSVN overlays and context menus (any file manager that doesn't I can't even consider, I live in Tortoise).
  • Another vote for xplorer2 from http://www.zabkat.com/. First thing I install on a clean vista system, as I cant stand the default file manager / explorer.

    Lucas Jones : Just vote it up and comment, please.
  • kde's filemanager (konq) is quite amazing. you can quickly split it vertically(ctrl+shift+t) or horizontally(ctrl+shift+l) and have tabs(ctrl+t) and even (get this) "open a command prompt from here" with f4. you can open docs in the same window (depends on file type setting). also a neat little feature is renaming files (when in list/detail mode), you hit f2 and it doesn't highlight extension, you can hit up/down arrow to move to next item. also you can select multiple files easily with arrows and keyboard only (use space to toggle selection). also compressed files can be browsed just like normal folders and doesn't get clunky like xp does (at least when i last used xp). and the most awesomest feature... when you drag a file from one folder to another, you don't have to guess at what its going to do (like windows), it pops up a context menu with options: copy, move, link.

  • The Sunrise Commander is another file manager for GNU Emacs that descends directly from mc.el -- the same dog that has learned many nifty new tricks, like copying and renaming files in the background, integration with AVFS (linux only, I'm afraid) for transparent navigation inside compressed files, integration with eshell and term-mode for command-line navigation and path expansion, history rings for last visited directories, integration with recentf for list of files recently visited and much more.

    If you happen to be a Midnight Commander user and an Emacs user at the same time, give Sunrise a try -- there's a high chance you will like it a lot. I use it all the time, not only because I developed it, but principally because it currently covers all of my FM needs, at work as well as at home.

    This is how it looks like:

    Cheers,

    José A. Romero L.
    escherdragon at gmail dot com
    "We who cut mere stones must always be envisioning cathedrals."
    (Quarry worker's creed)

  • Q-Dir is excellent. Simple, powerful, featured and multi-language (and FREE).

    Q-Dir website

  • On Windows, 7-zip can be used as a good (free) file-manager: it has a 2-panel commander style and familiar keyboard shortcuts, history, favourites and customizable text editor. Also reads and writes a lot of archive formats.

  • You can try Proto

    here is a screencast

    Why?

    1. Blazing fast
    2. Keyboard friendly
    3. Filtering
    4. Regex rename
    5. Calculator
    6. App Launcher
  • Windows Explorer (Vista or 7) (dont kill me :D )

    Seriously, how advanced features do you really need, who needs a freakin calendar(cough emacs) in their FILE MANAGER? 99% of the operations i use are rename, move and copy and that on code files that usually are very small. For that explorer does the job good enough while it also looks good as opposed to most other file managers.

    It has great support for the built in Windows Indexer so you have instant search, that also searches inside the files and on metadata, in every indexed folder as default. Thumbnails with easy zoom is also nice.

    WinRar and Tortoise also integrates nice into the contextmenus so no need for built in diff and zip functions.

    Only thing i miss is working FTP-support.

    The preview pane could also have been better for code-files. As it is now you manually have to add support for most common code-files even though they all are just plain text, and the interface for doing this is not nice! (Does anyone have tips on preview handlers with syntax highlightning btw?)

    RCIX : +1 Amen to that. I actually use my mouse some and i'd like a UI that doesn't look like it came from when GUIs were new...
    Matthew Whited : Between Windows Explorer and cmd.exe I'm pretty well covered... when I need something more crazy I bust out Visual Studio. System.IO + LINQ = Fun!!

mail/Session Resource Factory does not work in Struts application

I want to use the standard resource factory provided by Tomcat 6.0, which create javax.mail.Sessions instance for me. As described in the JNDI Resource HOW-TO tutorial.

My META-INF/context.xml looks like:

<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true">
    <Resource name="mail/Session" 
          auth="Container" 
          type="javax.mail.Session" 
          mail.smtp.host="smtp.gmail.com"
          mail.smtp.port="587"
          mail.smtp.auth="true"
          mail.smtp.user="someone@gmail.com"
          mail.smtp.password="secretpassword" 
          mail.smtp.starttls.enable="true"/>    
</Context>

I have the next resource-ref in my WEB-INF/web.xml, just before </webapps>. Web.xml validates. I validated using McDowell's way.

<resource-ref>
    <description>Resource reference to a factory for javax.mail.Session instances that may be used for sending electronic mail messages, preconfigured
    to connect to the appropiate SMTP server.
    </description>
    <res-ref-name>mail/Session</res-ref-name>
    <res-type>javax.mail.Session</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>

I am using the next code snipett access my javax.mail.Session object.

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session)envCtx.lookup("mail/Session");
System.out.println("HERE smtp.user: " + session.getProperty("mail.smtp.user"));

I tested it in a sample app and it worked. Unfortunately when I moved the same code to a struts application, I get NULL in the above print statement. I do the context look up in singleton Class called mailer (which is defined in my WEB-INF/classes folder) but I get the same problem if i do the context look up in Struts action class.

I have been thinking about what is different to find the problem. My struts application web.xml is more complicated than simple application's web.xml. It has security-constraint, filters and the Struts Servlet configuration. I position resource-ref just before the servlet definitions. It seems like the resource-ref is being ignored.

I have another issue. If I have the mailapi.jar, needed by the javax.mail.Session, in the myapp/WEB-INF/lib folder I get:

java.lang.NoClassDefFoundError: javax/mail/Authenticator

If I put it in $CATALINA_HOME/lib is found.

Any ideas? I use struts and hibernate. Maybe it has something to do with that.

Debug

I tried to debug it puting the debug attribut in context

<Context reloadable="true" debug="99" ...

But I do not see anything interesting.

01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log

I tried:

Session session = (Session) initCtx.lookup("java:comp/env/mail/Session");

instead of:

Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session =
        
From stackoverflow
  • JNDI Lookup code quirks

    I've seen multiple issues with not finding JNDI resources. On Websphere (I know, you don't use it, but it's good to know...) you'll have problems with

    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    Session session = (Session)envCtx.lookup("mail/Session");
    

    What works (on Websphere) is

    Session session = (Session) initCtx.lookup("java:comp/env/mail/Session");
    

    From what you wrote in another answer I understand that this is not your problem - I'm leaving it here for people coming across the same problem under different circumstances later.

    Lookup of JNDI Resources from self-spawned threads

    Also, access to JNDI resources might depend upon the thread looking up the resources. As far as I remember, threading is not well defined in the servlet api (or JEE or related areas. It might even be voluntarily and explicitly be non-defined.) Therefor it's not mandatory for the server to provide JNDI resources in threads that you've spawned yourself (again Websphere did bite me with this, I haven't tested Tomcat6 in this regard, earlier versions used to provide JNDI resources to all threads)

    You've written that you are looking up JNDI resources from a singleton. If you, at the point of looking up resources, examine the stacktrace (either in your IDE, by throwing an exception or messing with Thread.currentThread().getStacktrace()): is there any Tomcat connector in the stacktrace or is one of your own Thread's run() method at the root of the stacktrace ? This would answer the question behind Jacks question if you are making the lookup from an Action class. (see Jack's answer)

    Threads and call-environment part two

    Create a new Struts Action and call your JNDI lookup code from there, see if this works if placed as close to struts and within the processing of a http request. If it works here, continue with the steps above.

    validity of web.xml

    Also, you might want to have a look at the schema definition for web.xml to make sure your resource-ref is positioned correctly. The servlet spec 2.4 is available at jcp.org and should be sufficient to check, even if tomcat implements 2.5.

    After all, I believe that tomcat6 validates web.xml, so that you probably already have it at the correct position. (Can't remember, as my IDEs editor complains when I get it wrong, should I need to write a web.xml)

    Tomcat debug options

    Many context.xml entries honour the attribute 'debug'. Though I believe that low one-digit values are sufficient, I've adopted the habit to add 'debug="99"' to elements like 'Context' or others. You might want to see if this results in some helpful log entries.

    Make sure it's not the classpath

    As you seem to have fundamentally changed the environment, make sure that you have all required libraries on board - the mail api consists of several jars. Download a new copy and unpack all libraries to $CATALINA_HOME/lib. You might take unused away once it worked with all libraries in there.

    Regarding your classpath question:

    The reason for finding the class when put into $CATALINA_HOME/lib is, that the connection is done by the server (remember - you've defined it in context.xml which is read by the server in order to start the application), thus the jar must be on the servers classpath - not just on the applications (see the tomcat class loader HOWTO for more information)

    EDIT:

    Regarding your partial solution:

    $CATALINA_HOME/conf/context.xml contains the global "default" context elements. This is not where you want your application specific configuration to be.

    The standard position for tomcat is either in the webapps META-INF/context.xml or in an xml file (named as you like, ending .xml) in $CATALINA_HOME/conf/Catalina/localhost/. The later solution is actually prefered with regards to META-INF/context.xml because this way the configuration is independent of the application and doesn't get overwritten when a new application is deployed.

    This context usually contains additional attributes like docBase and path:

    <Context docBase="/location/where/you/deployed/your/application" path="/app">
      ...
    </Context>
    

    This way your application is available at http://servername:8080/app . If you deploy to the $CATALINA_HOME/webapps directory, the docBase value can be relative to webapp. Be careful with regards to race conditions though: Tomcat will autodeploy applications in $CATALINA_HOME/webapps and might create the context file. Also, deleting the webapp in order to deploy a new one might cause tomcat to delete the xml config file.

    Therefor - whatever your problem might be: Try if your context definition / application work when placed in $CATALINA_HOME/conf/Catalina/localhost/app.xml . I have the feeling that it's something very simple, where only the last bit of information is missing in order to see the real problem.

    Sergio del Amo : "Create a new Struts Action and call your JNDI lookup code from there, see if this works if placed as close to struts and within the processing of a http request. If it works here, continue with the steps above." I tried did and it did not work
    Olaf : I suppose it's short - care to post the action code to the question? Also, make sure META-INF/context.xml ends up in your WAR (not just the IDE). Make sure CAPITAL letters are for META-INF. Try placing the file (with in conf/Catalina/localhost/c.xml
    Olaf : Now that I've had more time I've added my last comments content to the answer and provided some more in-depth details. Hope that helps.
  • I believe you should define your context in META-INF/context.xml, not META-INF/web.xml (though this may just be a typo in your original post).

    When you said you moved your code to a Struts application, could you be more specific? Do you mean you are doing your context look up in an Action class now?

    Also, you may know this already, but while defining your context (JNDI entries etc) in your web apps META-INF/context.xml is acceptable in a developer's environment, I highly discourage using it in any form of shared environments, and certainly not in a production environment.

    Sergio del Amo : Thanks for the answer. I have made some comments to your answer
  • And what do you recommend?

    Define it in JNDI, but outside of your web application/WAR. In Tomcat, you can do this by putting it in the ${CATALINA_BASE}/conf/context.xml file. This allows external resource (mail, database etc) configuration to be defined outside of your web application, avoiding the need to repackage your WAR when you database configuration changes, or you move to a different environment with a different database, for instance.

    I do the context look up in singleton Class called mailer.

    This mailer class, is it in WEB-INF/classes, or a JAR within WEB-INF/lib? Or is it defined elsewhere in your classpath? If the latter, you may want to consider moving it into your application.


    Edit: Based on your latest findings, it looks like your web app's META-INF/context.xml is not taking effect. There are several scenarios in Tomcat that will lead to this. I don't know these in detail, but here are some information I was able to find:

    Per - http://tomcat.apache.org/tomcat-5.5-doc/config/host.html

    If the "deployXML" attribute is set to false in your Host element (I believe in server.xml).

    deployXML - Set to false if you want to disable parsing the context.xml file embedded inside the application (located at /META-INF/context.xml). Security consious environments should set this to false to prevent applications from interacting with the container's configuration. The administrator will then be responsible for providing an external context configuration file, and put it in $CATALINA_HOME/conf/[enginename]/[hostname]/. The flag's value defaults to true.

    Per - http://tomcat.apache.org/tomcat-5.5-doc/config/context.html

    If you have the $CATALINA_HOME/conf/[enginename]/[hostname]/[context-path].xml file defined.

    I'm sure there are others, these are just the ones I was able to find quickly.

    Sergio del Amo : Mailer is defined in my WEB-INF/classes folder
    Jack Leow : See? You have another reason not to use META-INF now :) I will be posting something else that I think may help your situation.
  • As this is a completely different scenario compared with the solution above, I've opted to add another answer rather than editing the previous one:

    Just in case: Make extra-extra-extra-sure that there's no typo in your context definition. Compare it extra-carefully with the working version in $CATALINA_HOME/conf/context.xml

    We wouldn't want a "mail/Sessoin" to make the difference...

list named with a function argument in python

I get the feeling this is probably something I should know but I can't think of it right now. I'm trying to get a function to build a list where the name of the list is an argument given in the function;

e.g.

def make_hand(deck, handname):
    handname = []
    for c in range(5):
        handname.append(deck.pop())
    return handname

    # deck being a list containing all the cards in a deck of cards earlier

The issue is that this creates a list called handname when i want it to be called whatever the user enters as handname when creating the hand.

Anyone can help? thanks

From stackoverflow
  • Since you are returning the list I don't see how the name of it within the function matters. Can you provide more context on what you want to do?

    : In this example it doesn't matter much, this function works fine as is, it's just that in later function (titled make_game) I need it to be making several hands with different names and I was just looking for a relatively clean way of doing this.
    Teifion : I would go with the dictionary suggestion from Kiv
  • You can keep a dictionary where the keys are the name of the hand and the values are the list.

    Then you can just say dictionary[handname] to access a particular hand. Along the lines of:

    hands = {} # Create a new dictionary to hold the hands.
    hands["flush"] = make_hand(deck) # Generate some hands using your function.
    hands["straight"] = make_hand(deck) # Generate another hand with a different name.
    print hands["flush"] # Access the hand later.
    
    : good idea, thanks
  • While you can create variables with arbitrary names at runtime, using exec (as sykora suggested), or by meddlings with locals, globals or setattr on objects, your question is somewhat moot.

    An object (just about anything, from integers to classes with 1000 members) is just a chunk of memory. It does not have a name, it can have arbitrarily many names, and all names are treated equal: they just introduce a reference to some object and prevent it from being collected.

    If you want to name items in the sense that a user of your program gives a user-visible name to an object, you should use a dictionary to associated objects with names.

    Your approach of user-supplied variable names has several other severe implications: * what if the user supplies the name of an existing variable? * what if the user supplies an invalid name?

    You're introducing a leaky abstraction, so unless it is really, really important for the purpose of your program that the user can specify a new variable name, the user should not have to worry about how you store your objects - an not be presented with seemingly strange restrictions.

How "Advertisement server" works?

I am looking for some information about Advertisement servers.

  1. Implementation details
    • tracking code generation
    • user data collection
    • serving the ad in response to a click-through
  2. Applicable standards
  3. Reference material (Please provide links or search teams to search)
    • books
    • white papers
  4. Implementations in .NET (Open Source)
From stackoverflow
  • I work for such a company, and I'm afraid this kind of proprietary information is considered extremely sensitive. AFAIK there are no public standards, and the bulk of the documentation available is as required for user implementation only.

    There may be some white papers out there, probably from academia, but it's possible google may have benevolently published something.

    Mahesh : can you please let me know where i can find these information or what should i search at least.
    annakata : no, I've no idea - as I said this information is generally considered trade secrets, for competitive and anti-fraud reasons
  • Check out the IAB (Interactive Advertising Bureau)

    They have specs on some commonly agreed-upon things like ad-banner formats. They seem to deal mostly in business issues and less on the technical/implementation specifics.

    The simplest implementation is simply pointing to an image from another server. That server will identify on which site the advertisement is being displayed (from the 'Referer' header, or from an id or token passed with the image request). Then the image is returned and the pageview is recorded. If the viewer clicks on the add, a link also pointing back to the ad server will record a 'clickthrough' and then forward the request on to the advertiser.

    The database might look like this (drasticly oversimplified, for example only):

    Pages
    +---------+----------------+
    | page_id | name           |
    +---------+----------------+
    |    1    | mycoolsite.com |
    +---------+----------------+
    
    Advertisements
    +-----------------+------------------+--------------------------------+
    |advertisement_id | image_name       | target_url                     |
    +-----------------+------------------+--------------------------------+
    |     1           |  banner1_468.png | http://new-amazing-product.com | 
    +-----------------+------------------+--------------------------------+
    
    Actvity
    +--------------+--------------------+--------+--------+
    | page_id      |  advertisement_id  | views  | clicks |
    +--------------+--------------------+--------+--------+
    |    1         |       1            |   0    |   0    |
    +--------------+--------------------+--------+--------+
    

    In the page which will display the add you'd put this in the html:

    <iframe src="http://your-ad-server.com/ads/image?site=1" />
    

    When a user viewed the page, the request for the image would go to the ad-server. The ad-server would look up the request, select an advertisement to show (many proprietary algorithms here), record the request, and finally return the response.

    Actvity
    +--------------+--------------------+--------+--------+
    | page_id      |  advertisement_id  | views  | clicks |
    +--------------+--------------------+--------+--------+
    |    1         |       1            | * 1 *  |   0    |
    +--------------+--------------------+--------+--------+
    

    The response could contain the following (retreived from the database):

    <a href="http://your-ad-server.com/ads/click?id=1">
      <img src="http://your-ad-server.com/ads/banner1_468.png" />
    </a>
    

    Now the image is loaded and shown on the page. If the user decides to click on it, again the request goes to the ad server which records the click and finally redirects the request to the page being advertised.

    GET /ads/click?id=1
    
    301 Moved Permanently
    Location: http://mycoolsite.com
    
    Actvity
    +--------------+--------------------+--------+--------+
    | page_id      |  advertisement_id  | views  | clicks |
    +--------------+--------------------+--------+--------+
    |    1         |       1            |   1    |  * 1 * |
    +--------------+--------------------+--------+--------+
    
    Mahesh : Thanks... For this wonderful information. Is there any books/white papers available for the same, so that i can have better idea.
    : Shouldn't it be `302` here according to this answer:http://stackoverflow.com/questions/1393280/http-redirect-301-vs-302-temporary-vs-permanent/1393298#1393298 ?
  • Hello,

    There are actually some very specific guidelines for how to measure things like impressions, clicks, conversions, Rich Media Events, etc. These guidelines can be found at the following url: http://www.iab.net/iab_products_and_industry_services/508676/guidelines

    If you conform to these guidelines, you can ask IAB to approve your ad server. Once approved, advertisers and publishers should trust the numbers being generated through your reports.

    annakata : This says a lot about my company :(

Can we not run BTSHTTPReceive.dll in Win XP (IIS 5)

I am trying to run the sample of Biztalk Samples\AdaptersUsage\HTTPRequestResponse in my machine where bizTalk is properly setup. Being Windows XP, it has IIS 5.1 and in the tutorial (ms-help://MS.BTS.2006/BTS06CoreDocs/html/81c66f61-d86c-49cf-8d24-21c67c68bc5a.htm) it is written in the 3rd step to create the application pool, but there is no concept of application pool in IIS 5. Is it not possible to run this tutorial in win xp?

If not, can i not run biztalk application to communicate with web service too in windows xp machine?

From stackoverflow

Python + SQLite query to find entries that sit in a specified time slot

Hi, I want to store a row in an SQLite 3 table for each booking in my diary.

Each row will have a 'start time' and a 'end time'.

Does any one know how I can query the table for an event at a given time?

E.g. Return any rows that happen at say 10:30am

Thanks

From stackoverflow
  • SQLite3 doesn't have a datetime type, though it does have date and time functions.

    Typically you store dates and times in your database in something like ISO 8601 format: YYYY-MM-DD HH:MM:SS. Then datetimes sort lexicographically into time order.

    With your datetimes stored this way, you simply use text comparisons such as

    SELECT * FROM tbl WHERE tbl.start = '2009-02-01 10:30:00'
    

    or

    SELECT * FROM tbl WHERE '2009-02-01 10:30:00' BETWEEN tbl.start AND tbl.end;
    
    DEzra : Ok, I looked at the link on sqlite site, but I am unclear how to say if the time i am searching for is between startime and endtime. Can you help?

Maintain CSS styling when converting HTML to PDF in ASP.NET

Hi,

I am using ITextSharp to convert a HTML page to PDF.

However, ITextSharp prints the CSS in the STYLE declaration straight out, ignores stylesheets even when added programatically and only listens to some inline styles (e.g. font-size and color but not background-color).

Is there something I am missing with ITextSharp, or is there a better (and free) way of doing this conversion?

Thanks in advance,

From stackoverflow

How can I create a random simulation?

I've been playing this flash game and after I'd gotten over the initial ('lol, fire') reaction I started to wonder how I could replicate this contact-mutate behaviour in programming. I guess it's a little like the honeypot xkcd.

I was thinking of starting with a scenario where particles deflect off each other and the containing walls. The sequence would start with a set number of 'mutant' particles, and when these mutants collide with regular particles they'd become mutants themselves. I could work in some more fun things later.

My problem is how to get started with this. I'm planning to do it in C# using the Drawing elements of .NET (although I'm fairly new to C# - if there's a different part of .NET I should use let me know) but if there's any general papers on it I'd be interested to read them (if they're available online of course).

Thanks, Ross

From stackoverflow
  • I think you are on the right track with what you are thinking, some particles in a box would do fine here. I can't imagine you would find papers on such a specific and simple case but perhaps for some of the techniques required, but an implementation of the backend should be relatively simple compared to a renderer.

    To move the particles around a simple method is Euler iteration, where you store the positions and velocities. position = position + velocity*dt; where dt is the change in time since the last frame. It is best to keep dt fixed, and interpolate between points for the renderer if you can... this will reduce stability issues and make collision detection easier.

    To reflect a particle off of a wall, check if its x components or y components of position will exceed the bounds and then flip the sign of the other component of the velocity, e.g.

    if(Math.Abs(position.x_component + velocity.x_component * dt) > x_bound) 
        velocity.y_component = -velocity.y_component;
    
    if(Math.Abs(position.y_component + velocity.y_component * dt) > y_bound)
        velocity.x_component = -velocity.x_component;
    

    If you have constant dt, this works quite well, but if it varies you will need to do something more complicated. find the collision point with the box and reflect the part of the vector outside the box in the face that was collided with.

    For colliding the particles with each other a distance check is probably best, triggering reflection once the distance is too small. i.e. If they get too close they collide. Reflect the velocity components as though the particles were spheres, so the normal for reflection is the difference of their positions.

    You may find this article on gamedev useful too...

    Hope this helps.

  • Why not have a look at the classic Asteroids game as a starting point? Here is alink to one that doesn't use DirectX and is in c#

    http://www.codeproject.com/KB/GDI-plus/asteroids.aspx

Comma seperated textbox value to list/array of strings - Is there a better way to write this code?

I want to create an array/list of strings of the Comma seperated strings (file extensions) that are entered in a Textbox.

For the following block of code:

            Dim csv As String = Textbox1.Text + ","

            While csv.IndexOf(".") <> -1
                lstOfStrings.Add(csv.Substring(0, csv.IndexOf(",")))
                csv = csv.Remove(0, csv.IndexOf(",") + 1)
            End While

The output is:

Textbox1.Text = ".exe,.php"

listOfStrings = { ".exe", ".php" }

Is there a better way to write this code?

From stackoverflow
  • A better way would be to use the Split method:

    Dim lstOfStrings() As String = Textbox1.Text.Split(","c)
    
    : Thank you! Also, is a List "lighter" than an Array of strings?
    Darin Dimitrov : A list of strings uses internally an array of strings for storage, so an array is lighter, but with fixed size. You can add elements to the list and it will dynamically resize if the internal array cannot hold the new data.
    ggf31416 : No, a List is slightly heavier than an Array, but the difference will be insignificant for a typical GUI program.
    configurator : Also, to create a list (which is 'heavier') if you need one, simply call it's constructor with the array as a parameter: Dim lstOfStrings As List(Of String) = New List(Of String)(Textbox1.Text.Split(","c)) - hope I got the VB syntax right.
  • Here is a different way with Regex+LINQ. It allows for whole file names, if thats something you value. Split is preferable depending on how conditioned the input is (spaces and the like).

    using System;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Collections.Generic;
    
    namespace ConsoleApplication2
    {
        class Program
        {
            static void Main(string[] args)
            {
                string s = "fileone.aspx, filetwo.csv,filethree.exe, filefour.php";
                List<string> extensions = Regex.Matches(s, @"(\.\w+)\s*,?")
                    .OfType<Match>().Select(m => m.Groups[1].Value)
                    .ToList();
                extensions.ForEach(i => Console.WriteLine(i));
                Console.ReadLine();
            }
        }
    }
    

    OUTPUT

    .aspx

    .csv

    .exe

    AFTERTHOUGHT

    You could add .Distinct() if you wanted unique extensions

How do I get the UIPickerView to slide up over another view?

I am looking for a way to slide a UIPickerView (and UIDatePickerView) up over a view (UITableView in particular) when a particular button press takes place.

I understand how to get the events for clicks into the UITableView, but there doesn't seem to be a good way to have the UIPickerView slide up on top of it...

All the examples I have seen so far just have it snapped to the bottom of another view and I am able to do this without issue.

Thoughts?

Thanks in advance.

From stackoverflow
  • Have you tried using UIView's animation blocks do do this? See the Apple docs on +[UIView beginAnimations:context:] and +[UIView commitAnimations]. Basically, wrap your calls to display the UIPickerView in these calls, and you can slow it down a bit.

  • Modally presented view controllers slide up from the bottom to cover the current view.

    See the documentation for -presentModalViewController:animated: in the UIViewController Class Reference. You would invoke this method on your UITableViewController and pass the UIPickerViewController as the first parameter and YES as the second.

  • An example of what Ben mentions above (Animation Blocks) is the following, which will animate to a subview.

    UIWindow *window = [[Director sharedDirector] window];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.75];
    [UIView setAnimationTransition:(UIViewAnimationTransitionCurlDown)
            forView:window
           cache:YES];
    [window addSubview:aView];
    [UIView commitAnimations];
    

Client side Infragistics webgrid data populate..

I am using ultra web Grid.. I am populating data using datatable and the grid is bound to the datatable. I am able to fetch the data and show the grid from the database.

  1. I have a editable column in the grid, I need to loop thru this grid and populate the second grid in the same page.. How do i do ? Please give me the client side code. Please help..

  2. The editable column in the grid. I have handled the client side event to check the correctness of the data entered. User enters the data and just skips to the next column.

From stackoverflow

Browser application & local file system access

I want to enhance my browser-based web application with functionality that enables management of local files and folders. E.g. folder tree structures should be synchronized between local workstation and server via HTTP(S).

I am aware of security-related limitations in browser-based applications. However, there are some techniques that "work around" these issues:

  • Signed Java applets (full trust)
  • .NET Windows Forms browser controls (no joke, that works. Just the configuration is horrible)
  • ActiveX

My question is: What do you use/suggest, both technology and implementation practice? Key requirement is that the installation process is as simple as possible.

Thanks for your opinions!

From stackoverflow
  • Google Gears.

    it lets you write Javascript applications with a much bigger platform support than the usual browser, and go 'unconnected' with local file access, cache and DB. and if/when connected it syncs to the central server.

    available for several browsers on all platforms; but still under heavy evolution.

  • Definitely not ActiveX. No sense spending time on something that out-of-date.

  • Adobe AIR (essentially, Flash for the Desktop), is something that we considered in my last contract, as opposed to Java applets. Last I checked, though it's been several months, the installation of the AIR runtime environment was fast and easy

  • Both Gears and Adobe Air require the user to manually select a local file before you get any programmatic access. Very limited because of security considerations when it comes to local filesystem access, so no chance for any web based file sync type functionality there as far as I can see. Maybe I'm wrong about Adobe Air but this is definitely the case with gears. But If I'm wrong let me know!

  • Your best bet might be to write a custom application that interacts with your web application. For example, Dropbox lets you synchronize files across computers by use of a background application that watches a Dropbox-enabled folder. It also lets you view your Dropbox files online through a web browser. The Dropbox web application then allows you to delete/move/copy files which is echoed in your local filesystem.

  • In the demo of Google Wave...

    http://www.youtube.com/watch?v=v_UyVmITiYQ&fmt=18

    ...at 15:30 in, a group of img files are drag-and-dropped from the file system to the browser. The functionality is attributed to Google Gears. This seems a bit different from what Daniel OCallaghan and the official documentation suggest is possible.

    Anybody know what's actually possible w/ Google Gear and the local file system?

    Rob Lord : Gears File System documentation: http://code.google.com/p/gears/wiki/FileSystemAPI
  • Silverlight 4 (still in beta) allows file system access:

    "Read and write files to the user’s MyDocuments, MyMusic, MyPictures and MyVideos folder (or equivalent for non-windows platforms) for example storage of media files and taking local copies of reports"

    http://www.silverlight.net/getstarted/silverlight-4/

Why should I use the keyword "final" on a method parameter in Java?

I can't understand where the final keyword is REALLY handy when it is used on method parameters.

If we exclude the usage of anonymous classes, readability and intent declaration then it seems almost worthless to me.

Enforcing that some data remains constant is not as strong as it seems.

A) If the parameter is a primitive then it will have no effect since the parameter is passed to the method as a value and changing it will have no effect outside the scope.

B) If we are passing a parameter by reference, then the reference itself is a local variable and if the reference is changed from within the method, that would not have any effect from outside of the method scope.

Consider the simple test example below. This test passes although the method changed the value of the reference given to it, it has no effect.

public void testNullify(){

 Collection<Integer> c  = new ArrayList<Integer>();  
 nullify(c);
 assertNotNull(c);  
 final Collection<Integer> c1 = c;
 assertTrue(c1.equals(c));
 change(c);
 assertTrue(c1.equals(c));
}


private void change(Collection<Integer> c) {
 c = new ArrayList<Integer>();  
}


public void nullify(Collection<?> t){
 t = null;  
}
From stackoverflow
  • Yes, excluding anonymous classes, readability and intent declaration it's almost worthless. Are those three things worthless though?

    Personally I tend not to use final for local variables and parameters unless I'm using the variable in an anonymous inner class, but I can certainly see the point of those who want to make it clear that the parameter value itself won't change (even if the object it refers to changes its contents). For those who find that adds to readability, I think it's an entirely reasonable thing to do.

    Your point would be more important if anyone were actually claiming that it did keep data constant in a way that it doesn't - but I can't remember seeing any such claims. Are you suggesting there's a significant body of developers suggesting that final has more effect than it really does?

    EDIT: I should really have summed all of this up with a Monty Python reference; the question seems somewhat similar to asking "What have the Romans ever done for us?"

    matt b : Well... what have the Romans ever done for us?
    Yuval : Sanitation, medicine, education, wine, public order, irrigation, roads, the fresh water system and public health. Oh, and peace =8-)
    James Schek : But to paraphrase Krusty with his danish, what have they done for us *LATELY*? =)
  • I am suggesting that there might be a significant body of developers who misunderstand "final" to have more effect than it really has.

    I think that for some developers, "final" as a method parameter, unlike as a local field modifier is a misleading concept.

    Thorbjørn Ravn Andersen : Adding final to parameters is so good an idea that Eclipse has a Source Cleanup option for it. It declares that the object in the variableis the same all through the method, which is important for maintainers who need to understand it fast.
    Jon Skeet : You think there are lots of programmers who believe that final parameters behave differently to final local variables? I find that hard to believe. Do you have any evidence of this?
    TofuBeer : parameter = var; instead of var = parameter; no misunderstanding of what it does, added safety is a good thing.
  • Using final in a method parameter has nothing to do with what happens to the argument on the caller side. It is only meant to mark it as not changing inside that method. As I try to adopt a more functional programming style, I kind of see the value in that.

  • Personally I don't use final on method parameters, because it adds too much clutter to parameter lists. I prefer to enforce that method parameters are not changed through something like Checkstyle.

    For local variables I use final whenever possible, I even let Eclipse do that automatically in my setup for personal projects.

    I would certainly like something stronger like C/C++ const.

  • Let me explain a bit about the one case where you have to use final, which Jon already mentioned:

    If you create an anonymous inner class in your method and use a local variable (such as a method parameter) inside that class, then the compiler forces you to make the parameter final:

    public Iterator<Integer> createIntegerIterator(final int from, final int to)
    {
        return new Iterator<Integer>(){
            int index = from;
            public Integer next()
            {
                return index++;
            }
            public boolean hasNext()
            {
                return index <= to;
            }
            // remove method omitted
        };
    }
    

    Here the from and to parameters need to be final so they can be used inside the anonymous class.

    The reason for that requirement is this: Local variables live on the stack, therefore they exist only while the method is executed. However, the anonymous class instance is returned from the method, so it may live for much longer. You can't preserve the stack, because it is needed for subsequent method calls.

    So what Java does instead is to put copies of those local variables as hidden instance variables into the anonymous class (you can see them if you examine the byte code). But if they were not final, one might expect the anonymous class and the method seeing changes the other one makes to the variable. In order to maintain the illusion that there is only one variable rather than two copies, it has to be final.

    hhafez : You lost me from "But if they are not final...." Can you put try to rephrase it, Maybe I haven't had enough cofee.
    Michael Borgwardt : You have a local variables from - the question is what happens if you use the anon class instance inside the method and it changes the values of from - people would expect the change to be visible in the method, since they see only one variable. In order to avoid this confusion, it must be final.
    vickirk : It doesn't make a copy, it is simply a reference to whatever object was referenced.
    Michael Borgwardt : @vickirk: sure it makes a copy - of the reference, in case of reference types.
  • I use final all the time on parameters.

    Does it add that much? Not really.

    Would I turn it off? No.

    The reason: I found 3 bugs where people had written sloppy code and failed to set a member variable in accessors. All bugs proved difficult to find.

    I'd like to see this made the default in a future version of Java. The pass by value/reference thing trips up an awful lot of junior programmers.

    One more thing.. my methods tend to have a low number of parameters so the extra test on a method declaration isn't an issue.

  • Sometimes its nice to be explicit(for readability) that the variable doesn't change. Here's a simple example where using final can save some possible headaches

    public void setTest(String test) {
        test = test;
    }
    

    if you forget the 'this' keyword on a setter the variable you want to set doesn't get set. However if you used the final keyword on the parameter then the bug would be caught at compile time.

  • One additional reason to add final to parameter declarations is that it helps to identify variables that need to be renamed as part of a "Extract Method" refactoring. I have found that adding final to each parameter prior to starting a large method refactoring quickly tells me if there are any issues I need to address before continuing.

    However, I generally remove them as superfluous at the end of the refactoring.

  • Using final on method parameters in an optimization. Parameters are passed by reference. But what happens if I modify a variable that was passed by reference as a parameter? It won't break, because Java has made a copy for the function to use as it wishes. What about the overhead for this copy? That's where "final" comes in. If you specify "final" you can't modify teh parameter in the function (the "compile-time" checking will prevent it). Thus, the compiler does not nee dto make a extra copy of teh variable in case it is messed with, since it won't be. So you get the savings of not making an extra copy if you are not going to modify it anyway. Why not always have final by default? What if you want to use teh parametr as a variable to mess with? By not having it assumed final, you save a line of code that would declare a copy of the variable. I could see a case being made for this, but it doesn't seem like a big deal either way.

    -Dan8080

    "My IQ is bigger than my shoe size, and I have BIG feet" -anonymous