text
stringlengths
8
267k
meta
dict
Q: What's the difference between a worker thread and an I/O thread? Looking at the processmodel element in the Web.Config there are two attributes. maxWorkerThreads="25" maxIoThreads="25" What is the difference between worker threads and I/O threads? A: Fundamentally not a lot, it's all about how ASP.NET and IIS allocate I/O wait objects and manage the contention and latency of communicating over the network and transferring data. I/O threads are set aside as such because they will be doing I/O (as the name implies) and may have to wait for "long" periods of time (hundreds of milliseconds). They also can be optimized and used differently to take advantage of I/O completion port functionality in the Windows kernel. A single I/O thread may be managing multiple completion ports to maintain throughput. Windows has a lot of capabilities for dealing with I/O blocking whereas ASP.NET/.NET has a plain concept of "Thread". ASP.NET can optimize for I/O by using more of the unmanaged threading capabilities in the OS. You wouldn't want to do this all the time for every thread as you lose a lot of capabilities that .NET gives you which is why there is a distinction between how the threads are intended to be used. Worker threads are threads upon which regular "work" or just plain code/processing happens. Worker threads are unlikely to block a lot or wait on anything and will be short running and therefore require more aggressive scheduling to maximize processing power and throughput. [Edit]: I also found this link which is particularly relevant to this question: http://blogs.msdn.com/ericeil/archive/2008/06/20/windows-i-o-threads-vs-managed-i-o-threads.aspx A: Just to add on to chadmyers... Seems like I/O Threads was the old way ASP.NET serviced requests, "Requests in IIS 5.0 are typically serviced over I/O threads, or threads performing asynchronous I/O because requests are dispatched to the worker process using asynchronous writes to a named pipe." with IIS6.0 this has changed. "Thus all requests are now serviced by worker threads drawn from the CLR thread pool and never on I/O threads." Source: http://msdn.microsoft.com/hi-in/magazine/cc164128(en-us).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/137400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Is there any way in .NET to programmatically listen to HTTP traffic? I'm using browser automation for testing web sites but I need to verify HTTP requests from the browser (i.e., images, external scripts, XmlHttpRequest objects). Is there a way to programmatically instantiate a proxy or packet sniffer for the browser to use in order to see what its sending? I'm already using Fiddler to watch the traffic but I want something that's UI-less that I can use in continuous build integration. Can I easily get the HTTP-specific information from WinpCap? A: Try winpcap . It's a driver/library combination which can be used to monitor packets. Based on what you are trying to do (watch traffic w/o a UI), this is probably a simpler solution than writing your own proxy. A: You probably don't want to proxy, that will introduce a lot of unnecessary complexity. Consider packet sniffing instead, which is pretty much a solved problem. Wireshark is handy as a stand alone utility you can use manually, but it's also possible to do packet sniffing programmatically, using WinPcap, the library on which Wireshark is based. Here's a couple of examples of WinPcap in .Net, .NetNomad's example with sample project, and a CodeProject tutorial, also with source. A: There are numerous apps for this. My recommendation is Wireshark A: Have you looked at implementing an Http Module or an Http Handler (.ashx)? They will allow you to intercept each and every web request and process them as you need before getting to your page.
{ "language": "en", "url": "https://stackoverflow.com/questions/137407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using client side reporting vs. server side reporting? When do we use client side reporting and when do we use server side reporting? Which reporting is best practice (client/server)? This pertains to SSRS reporting. A: Well... client side reporting you'd use if you've got something like a winforms client that you can't guarantee will have constant access to the data source. It might have a set of data cached on the client side which you need to report on even if the connection to the server is unavailable. Server side reporting you'd use in the scenario where you either need to simplify the report distribution and deployment as you just deploy the reports to one place and everyone can access them. This has the downfall of always requiring a connection be available to the server A: Client side reporting is also handy when you have a client gathering data from very different sources. We have an in-house corporate application that calls internal services to get data from financials as well as our separate production database, and it combines them into a single dataset which it passes to a ReportViewer control. From an aesthetic point of view, it's nice to integrate reporting into an application so that the user doesn't feel that they're leaving the app to print or export the app's data. A: Client site reporting If one of the following is true then you should use client site reporting: * *If you have the data only on the client and not in the network or on the server. This is mostly true for desktop applications. *There is no server (Home systems). Server site reporting If one of the following is true then you should use server site reporting: * *The data is on the server or on a static place in the network. *You only have thin clients. *The reporting should be scheduled. *The license cost for a single server is smaller than for many desktop installations. *Report templates are shared and can change frequently. A: It depends what you call "server" in this case. As you mention SSRS I am assuming you consider the database (SQL Server) as the server. It all depends on the application/project structure and requirements. If you have a database that contains also the business logic (store procedures) and you simply want to query data and display/export it, then SSRS is handy. However if you have a web application with your persistence layer (database) that simply stores information and ensures the information is consistent, but then your business logic is for example in a Web API (i.e: a RESTful API project) that queries/maintains the database data (CRUD) and adds some logic and then responses to HTTP requests with the results/information requested (i.e: with JSON) to a rich front-end, then I would add reporting functionality at client-side (front end) with for example a Javascript library executed in the browser that is able to display the retrieved data in whichever way, it is able to export it to a DOC, Excel, Email it, etc. Separation of concerns for a typical Web Application: * *persistence layer (Database) to store information and guarantee consistency *business layer (Back end RESTful API) to do all the smart things on the resources, calculations, authentication, authorization for each HTTP request. *Rich front-end (Javascript + HTML + CSS) to interact with the user and request/display information to the back-end. As part of the concern of displaying information, this front-end would also generate reports.
{ "language": "en", "url": "https://stackoverflow.com/questions/137422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I automate a web proxy in .NET for unit tests (including set up and tear down)? Following Jonathan Holland's suggestion in his comment for my previous question: Is there any way in .NET to programmatically listen to HTTP traffic? I've made a separate (but not exactly a duplicate) question for what I really want to know: How do I automate a web proxy in .NET for unit tests (including set up and tear down) for spying on HTTP traffic that comes from the browser (particularly images, scripts, and XmlHttpRequests on the requested page)? I prefer to have zero set-up (so no Fiddler installed on Windows) where everything can be unpacked from an assembly, deployed, and then removed without a trace, so to speak. A: Roll your own pass-through proxy, then have your test harness issue configuration commands on the admin port of the proxy. The proxy will dutifully route any normal connection to the specified ip:port, with minimal "setup." A: WebAii 2.0 has a built-in HTTP proxy: http://www.artoftest.com/community/blogs/09-03-25/WebAii_2_0_Beta_Released.aspx A: If you want to take control of a browser-like request and look at requests and headers from a stimulated web browser to your localhost, you can use System.Net.WebClient If you want a .NET solution, where you use complete proxy detection, then have a look at this MSDN article: http://msdn.microsoft.com/en-us/magazine/cc300743.aspx. It explains how to integrate with a proxy like Fiddler Before using any of these solutions, I strongly recommend that you review your unit tests and what you're trying to accomplish. A full proxy solution is often times out of the scope of unit tests and you may want to scale your tests down a bit. However, if you are writing integration tests, then these solutions should serve you well. A: I'm not sure if it's what you're looking for, but here is an example of ASP.NET unit testing using selenium. http://www.stevetrefethen.com/blog/AutomatedTestingOfASPNETWebApplicationsUsingSelenium.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/137425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I turn an image file of a game map into boundaries in my program? I have an image of a basic game map. Think of it as just horizontal and vertical walls which can't be crossed. How can I go from a png image of the walls to something in code easily? The hard way is pretty straight forward... it's just if I change the image map I would like an easy way to translate that to code. Thanks! edit: The map is not tile-based. It's top down 2D. A: I need more details. Is your game tile based? Is it 3d? If its tile based, you could downsample your image to the tile resolution and then do a 1:1 conversion with each pixel representing a tile. A: I suggest writing a script that takes each individual pixel and determines if it represents part of a wall or not (ie black or white). Then, code your game so that walls are built from individual little block, represented by the pixels. Shouldn't be TOO hard... A: I dabble in video games, and I personally would not want the hassle of checking the boundaries of pictures on the map. Wouldn't it be cleaner if these walls were objects that just happened to have an image property (or something like it)? The image would display, but the object would have well defined coordinates and a function could decide whether an object was hit every time the player moved. A: If you don't need to precompute anything using the map info. You can just check in runtime logic using getPixel(x,y) like function. A: Well, i can see two cases with two different "best solution" depending on where your graphic comes from: * *Your graphics is tiled, and thus you can easily "recognize" a block because it's using the same graphics as other blocks and all you would have to do is a program that, when given a list of "blocking tiles" and a map can produce a "collision map" by comparing each tile with tiles in the "blocking list". *Your graphics is just some graphics (e.g. it could be a picture, or some CG graphics) and you don't expect pixels for a block to be the same as pixels from another block. You could still try to apply an "edge detection" algorithm on your picture, but my guess is then that you should rather split your picture in a BG layer and a FG layer so that the FG layer has a pre-defined color (or alpha=0) and test pixels against that color to define whether things are blocking or not. *You don't have much blocking shapes, but they are usually complex (polygons, ellipses) and would be unefficient to render using a bitmap of the world or to pack as "tile attributes". This is typically the case for point-and-click adventure games, for instance. In that case, you're probably to create path that match your boundaries with a vector drawing program and dig for a library that does polygon intersection or bezier collisions. Good luck and have fun.
{ "language": "en", "url": "https://stackoverflow.com/questions/137443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redundancy in C#? Take the following snippet: List<int> distances = new List<int>(); Was the redundancy intended by the language designers? If so, why? A: The reason the code appears to be redundant is because, to a novice programmer, it appears to be defining the same thing twice. But this is not what the code is doing. It is defining two separate things that just happen to be of the same type. It is defining the following: * *A variable named distances of type List<int>. *An object on the heap of type List<int>. Consider the following: Person[] coworkers = new Employee[20]; Here the non-redundancy is clearer, because the variable and the allocated object are of two different types (a situation that is legal if the object’s type derives from or implements the variable’s type). A: Because declaring a type doesn't necessarily have anything to do with initializing it. I can declare List<int> foo; and leave it to be initialized later. Where's the redundancy then? Maybe it receives the value from another function like BuildList(). As others have mentioned the new var keyword lets you get around that, but you have to initialize the variable at declaration so that the compiler can tell what type it is. A: instead of thinking of it as redundant, think of that construct as a feature to allow you to save a line. instead of having List distances; distances = new List(); c# lets you put them on one line. One line says "I will be using a variable called distances, and it will be of type List." Another line says "Allocate a new List and call the parameterless constructor". Is that too redundant? Perhaps. doing it this way gives you some things, though 1. Separates out the variable declaration from object allocation. Allowing: IEnumerable<int> distances = new List<int>(); // or more likely... IEnumerable<int> distances = GetList(); 2. It allows for more strong static type checking by the compiler - giving compiler errors when your declarations don't match the assignments, rather than runtime errors. Are both of these required for writing software? No. There are plenty of languages that don't do this, and/or differ on many other points. "Doctor! it hurts when I do this!" - "Don't do that anymore" If you find that you don't need or want the things that c# gives you, try other languages. Even if you don't use them, knowing other ones can give you a huge boost in how you approach problems. If you do use one, great! Either way, you may find enough perspective to allow yourself to say "I don't need the strict static type checking enforced by the c# compiler. I'll use python", rather than flaming c# as too redundant. A: Could also do: var distances = new List<int>(); A: The compiler improvements for C# 3.0 (which corresponds with .Net 3.5) eliminate some of this sort of thing. So your code can now be written as: var distances = new List<int>(); The updated compiler is much better at figuring out types based on additional information in the statement. That means that there are fewer instances where you need to specify a type either for an assignment, or as part of a Generic. That being said, there are still some areas which could be improved. Some of that is API and some is simply due to the restrictions of strong typing. A: The redunancy wasn't intended, per se, but was a side-effect of the fact that all variables and fields needed to have a type declaration. When you take into account that all object instantiations also mention the type's name in a new expression, you get redundant looking statements. Now with type-inferencing using the var keyword, that redundancy can be eliminated. The compiler is smart enough to figure it out. The next C++ also has an auto keyword that does the same thing. The main reason they introduced var, though, was for anonymous types, which have no name: var x = new {Foo = Bar, Number = 1}; A: It's only "redundant" if you are comparing it to dynamically typed languages. It's useful for polymorphism and finding bugs at compile time. Also, it makes code auto-complete/intellisense easier for your IDE (if you use one). A: What's redudant about this? List<int> listOfInts = new List<int>(): Translated to English: (EDIT, cleaned up a little for clarification) * *Create a pointer of type List<int> and name it listofInts. *listOfInts is now created but its just a reference pointer pointing to nowhere (null) *Now, create an object of type List<int> on the heap, and return the pointer to listOfInts. *Now listOfInts points to a List<int> on the heap. Not really verbose when you think about what it does. Of course there is an alternative: var listOfInts = new List<int>(); Here we are using C#'s type inference, because you are assigning to it immediately, C# can figure out what type you want to create by the object just created in the heap. To fully understand how the CLR handles types, I recommend reading CLR Via C#. A: You could always say: var distances = new List<int>(); A: As others have said: var removes the redundancy, but it has potential negative maintenance consequences. I'd say it also has potential positive maintenance consequences. Fortunately Eric Lippert writes about it a lot more eloquently than I do: http://csharpindepth.com/ViewNote.aspx?NoteID=63 http://csharpindepth.com/ViewNote.aspx?NoteID=61 A: C# is definitely getting less verbose after the addition of functional support. A: A historical artifact of static typing / C syntax; compare the Ruby example: distances = [] A: Use var if it is obvious what the type is to the reader. //Use var here var names = new List<string>(); //but not here List<string> names = GetNames(); From microsofts C# programing guide The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code A: Your particular example is indeed a bit verbose but in most ways C# is rather lean. I'd much prefer this (C#) int i; to this (VB.NET) Dim i as Integer Now, the particular example you chose is something about .NET in general which is a bit on the long side, but I don't think that's C#'s fault. Maybe the question should be rephrased "Why is .NET code so verbose?" A: I see one other problem with the using of var for laziness like that var names = new List<string>(); If you use var, the variable named "names" is typed as List<string>, but you would eventually only use one of the interfaces inherited by List<T>. IList<string> = new List<string>(); ICollection<string> = new List<string>(); IEnumerable<string> = new List<string>(); You can automatically use everything of that, but can you consider what interface you wanted to use at the time you wrote the code? The var keyword does not improve readability in this example. A: In many of the answers to this question, the authors are thinking like compilers or apologists. An important rule of good programming is Don't repeat yourself! Avoiding this unnecessary repetition is an explicit design goal of Go, for example: Stuttering (foo.Foo* myFoo = new(foo.Foo)) is reduced by simple type derivation using the := declare-and-initialize construct. A: Because we're addicted to compilers and compiler errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/137448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: CSS for hover that includes all child elements I have a draggable div element with a hover style. This works fine, but the div contains some form elements (label, input). The problem is that when the mouse is over these child elements the hover is disabled. <div class="app_setting"> <label">Name</label> <input type="text" name="name"/> </div> .app_setting:hover { cursor:move; } Any ideas how to get the hover to apply also to the child elements? A: .app_setting *:hover { cursor:move } A: At least 2 ways of doing it: * *hover states for each child, either explicitly or with * selector, as suggested by garrow .class *:hover *cascade hover state to children .class:hover * There are probably others A: This isn't a css answer, but it might still be useful to you. Someone else already suggested that you might have to resort to javascript for browser compatibility. If you do resort to javascript, you can use the jquery library to make it easy. $(".appsetting").hover(hoverInFunc,hoverOutFunc); This sets an event handler for hovering into and out of the selected element(s) as matched by the css style selector in the $() call. A: You might have to resort to JS to make it happen for IE6.
{ "language": "en", "url": "https://stackoverflow.com/questions/137449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: How do I change SQL Server 2005 to be case sensitive? I hate case sensitivity in databases, but I'm developing for a client who uses it. How can I turn on this option on my SQL Server, so I can be sure I've gotten the case right in all my queries? A: How about: ALTER DATABASE database_name COLLATE collation_name See BOL for a list of collation options and pick the case-sensitive one that best fits your needs (i.e. the one your client is using). Obviously, it's probably a good idea to make a full backup of your database before you try this. I've never personally tried to use a database with a different collation than the server's default collation, so I don't know of any "gotchas". But if you have good backups and test it in your environment before deploying it to your client, I can't imagine that there's much risk involved. A: You don't actually need to change the collation on the entire database, if you declare it on the table or columns that need to be case-sensitive. In fact, you can actually append it to individual operations as needed. SELECT name WHERE 'greg' = name COLLATE Latin1_GENERAL_CS_AS I know, you said that you want this to apply throughout the database. But I mention this because in certain hosted environments, you can't control this property, which is set when the database is created. A: If you have a DB that has a different collation to the instance default, you can run into problems when you try and join your tables with temporary ones. Temporary tables have to collation of the instance (because they're system objects) so you need to use the COLLATE database_default clause in your joins. select temp.A, table.B from #TEMPORARY_TABLE temp inner join table on temp.X COLLATE database_default = table.Y This forces the collation of temp.X (in this example) to the collation of the current DB. A: You'll have to change the database collation. You'll also need to alter the table and column level collation. I beleive you can find a script out there if you google it.
{ "language": "en", "url": "https://stackoverflow.com/questions/137452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What does the "private" modifier do? Considering "private" is the default access modifier for class Members, why is the keyword even needed? A: The private modifier explains intent. A private member variable is not intended for direct manipulation outside the class. get/set accessors may or may not be created for the variable. A private method is not intended for use outside the class. This may be for internal functionality only. Or you could make a default constructor private to prevent the construction of the class without passing in values. The private modifier (and others like it) can be a useful way of writing self documenting code. A: There's a certain amount of misinformation here: "The default access modifier is not private but internal" Well, that depends on what you're talking about. For members of a type, it's private. For top-level types themselves, it's internal. "Private is only the default for methods on a type" No, it's the default for all members of a type - properties, events, fields, operators, constructors, methods, nested types and anything else I've forgotten. "Actually, if the class or struct is not declared with an access modifier it defaults to internal" Only for top-level types. For nested types, it's private. Other than for restricting property access for one part but not the other, the default is basically always "as restrictive as can be." Personally, I dither on the issue of whether to be explicit. The "pro" for using the default is that it highlights anywhere that you're making something more visible than the most restrictive level. The "pro" for explicitly specifying it is that it's more obvious to those who don't know the above rule, and it shows that you've thought about it a bit. Eric Lippert goes with the explicit form, and I'm starting to lean that way too. See http://csharpindepth.com/viewnote.aspx?noteid=54 for a little bit more on this. A: As pointed out by Jon Skeet in his book C# In Depth, there is one place in C# where the private keyword is required to achieve an effect. If my memory serves correctly, the private keyword is the only way to create a privately scoped property getter or setter, when its opposite has greater than private accessibility. Example: public bool CanAccessTheMissileCodes { get { return canAccessTheMissileCodes; } private set { canAccessTheMissileCodes = value; } } The private keyword is required to achieve this, because an additional property accessability modifier can only narrow the scope, not widen it. (Otherwise, one might have been able to create a private (by default) property and then add a public modifier.) A: Private is only the default for methods on a type, but the private modifier is used elsewhere. From C# Language Specification 3.0 (msdn) Section 3.5.1 Depending on the context in which a member declaration takes place, only certain types of declared accessibility are permitted. Furthermore, when a member declaration does not include any access modifiers, the context in which the declaration takes place determines the default declared accessibility. * *Namespaces implicitly have public declared accessibility. No access modifiers are allowed on namespace declarations. *Types declared in compilation units or namespaces can have public or internal declared accessibility and default to internal declared accessibility. *Class members can have any of the five kinds of declared accessibility and default to private declared accessibility. (Note that a type declared as a member of a class can have any of the five kinds of declared accessibility, whereas a type declared as a member of a namespace can have only public or internal declared accessibility.) *Struct members can have public, internal, or private declared accessibility and default to private declared accessibility because structs are implicitly sealed. Struct members introduced in a struct (that is, not inherited by that struct) cannot have protected or protected internal declared accessibility. (Note that a type declared as a member of a struct can have public, internal, or private declared accessibility, whereas a type declared as a member of a namespace can have only public or internal declared accessibility.) *Interface members implicitly have public declared accessibility. No access modifiers are allowed on interface member declarations. *Enumeration members implicitly have public declared accessibility. No access modifiers are allowed on enumeration member declarations. A: For completenes. And some people actually prefer to be explicit in their code about the access modifiers on their methods. A: It's for you (and future maintainers), not the compiler. A: For symmetry and to conform with coding styles that like everything to be explicit (personally I like it ...) A: Explicitness. I never use the default and always explicitly add the modifier. This could be because of my Java background where the default was 'package' (roughly equivalent to 'internal' in C#) and so the difference always bothered me. I found explicitness to be preferable. I also use ReSharper now which defaults to being explicit, so it only confirms and reinforces my bias :) A: Some coding styles recommend that you put all the "public" items first, followed by the "private" items. Without a "private" keyword, you couldn't do it that way around. Update: I didn't notice the "c#" tag on this so my answer applies more to C++ than to C#. A: Using private explicitly signals your intention and leaves clues for others who will support your code ;) A: I usually leave private out but I find it useful for lining up code: private int x; public string y; protected float z; VS: int x; public string y; protected float z; A: As Robert Paulson said in his answer, the private modifier is not just used on members, but also on types. This becomes important because the default for types is internal which can leak unintentionally if you use the InternalsVisibleToAttribute. A: Actually, if the class or struct is not declared with an access modifier it defaults to internal. So if you want to make it private, use private.
{ "language": "en", "url": "https://stackoverflow.com/questions/137454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Null vs. False vs. 0 in PHP I am told that good developers can spot/utilize the difference between Null and False and 0 and all the other good "nothing" entities. What is the difference, specifically in PHP? Does it have something to do with ===? A: In PHP you can use === and !== operators to check not only if the values are equal but also if their types match. So for example: 0 == false is true, but 0 === false is false. The same goes for != versus !==. Also in case you compare null to the other two using the mentioned operators, expect similar results. Now in PHP this quality of values is usually used when returning a value which sometimes can be 0 (zero), but sometimes it might be that the function failed. In such cases in PHP you return false and you have to check for these cases using the identity operator ===. For example if you are searching for a position of one string inside the other and you're using strpos(), this function will return the numeric position which can be 0 if the string is found at the very beginning, but if the string is not found at all, then strpos() will return false and you have to take this into account when dealing with the result. If you will use the same technique in your functions, anybody familiar with the standard PHP library will understand what is going on and how to check if the returned value is what is wanted or did some error occur while processing. The same actually goes for function params, you can process them differently depending on if they are arrays or strings or what not, and this technique is used throughout PHP heavily too, so everybody will get it quite easily. So I guess that's the power. A: False, Null, Nothing, 0, Undefined, etc., etc. Each of these has specific meanings that correlate with actual concepts. Sometimes multiple meanings are overloaded into a single keyword or value. In C and C++, NULL, False and 0 are overloaded to the same value. In C# they're 3 distinct concepts. null or NULL usually indicates a lack of value, but usually doesn't specify why. 0 indicates the natural number zero and has type-equivalence to 1, 2, 3, etc. and in languages that support separate concepts of NULL should be treated only a number. False indicates non-truth. And it used in binary values. It doesn't mean unset, nor does it mean 0. It simply indicates one of two binary values. Nothing can indicate that the value is specifically set to be nothing which indicates the same thing as null, but with intent. Undefined in some languages indicates that the value has yet to be set because no code has specified an actual value. A: null is null. false is false. Sad but true. there's not much consistency in PHP (though it is improving on latest releases, there's too much backward compatibility). Despite the design wishing some consistency (outlined in the selected answer here), it all get confusing when you consider method returns that use false/null in not-so-easy to reason ways. You will often see null being used when they are already using false for something. e.g. filter_input(). They return false if the variable fails the filter, and null if the variable does not exists (does not existing means it also failed the filter?) Methods returning false/null/string/etc interchangeably is a hack when the author care about the type of failure, for example, with filter_input() you can check for ===false or ===null if you care why the validation failed. But if you don't it might be a pitfall as one might forget to add the check for ===null if they only remembered to write the test case for ===false. And most php unit test/coverage tools will not call your attention for the missing, untested code path! Lastly, here's some fun with type juggling. not even including arrays or objects. var_dump( 0<0 ); #bool(false) var_dump( 1<0 ); #bool(false) var_dump( -1<0 ); #bool(true) var_dump( false<0 ); #bool(false) var_dump( null<0 ); #bool(false) var_dump( ''<0 ); #bool(false) var_dump( 'a'<0 ); #bool(false) echo "\n"; var_dump( !0 ); #bool(true) var_dump( !1 ); #bool(false) var_dump( !-1 ); #bool(false) var_dump( !false ); #bool(true) var_dump( !null ); #bool(true) var_dump( !'' ); #bool(true) var_dump( !'a' ); #bool(false) echo "\n"; var_dump( false == 0 ); #bool(true) var_dump( false == 1 ); #bool(false) var_dump( false == -1 ); #bool(false) var_dump( false == false ); #bool(true) var_dump( false == null ); #bool(true) var_dump( false == '' ); #bool(true) var_dump( false == 'a' ); #bool(false) echo "\n"; var_dump( null == 0 ); #bool(true) var_dump( null == 1 ); #bool(false) var_dump( null == -1 ); #bool(false) var_dump( null == false ); #bool(true) var_dump( null == null ); #bool(true) var_dump( null == '' ); #bool(true) var_dump( null == 'a' ); #bool(false) echo "\n"; $a=0; var_dump( empty($a) ); #bool(true) $a=1; var_dump( empty($a) ); #bool(false) $a=-1; var_dump( empty($a) ); #bool(false) $a=false; var_dump( empty($a) ); #bool(true) $a=null; var_dump( empty($a) ); #bool(true) $a=''; var_dump( empty($a) ); #bool(true) $a='a'; var_dump( empty($a)); # bool(false) echo "\n"; #new block suggested by @thehpi var_dump( null < -1 ); #bool(true) var_dump( null < 0 ); #bool(false) var_dump( null < 1 ); #bool(true) var_dump( -1 > true ); #bool(false) var_dump( 0 > true ); #bool(false) var_dump( 1 > true ); #bool(true) var_dump( -1 > false ); #bool(true) var_dump( 0 > false ); #bool(false) var_dump( 1 > true ); #bool(true) A: I have just wasted 1/2 a day trying to get either a 0, null, false to return from strops! Here's all I was trying to do, before I found that the logic wasn't flowing in the right direction, seeming that there was a blackhole in php coding: Concept take a domain name hosted on a server, and make sure it's not root level, OK several different ways to do this, but I chose different due to other php functions/ constructs I have done. Anyway here was the basis of the cosing: if (strpos($_SERVER ['SERVER_NAME'], dirBaseNAME ()) { do this } else { or that } { echo strpos(mydomain.co.uk, mydomain); if ( strpos(mydomain, xmas) == null ) { echo "\n1 is null"; } if ( (strpos(mydomain.co.uk, mydomain)) == 0 ) { echo "\n2 is 0"; } else { echo "\n2 Something is WRONG"; } if ( (mydomain.co.uk, mydomain)) != 0 ) { echo "\n3 is 0"; } else { echo "\n3 it is not 0"; } if ( (mydomain.co.uk, mydomain)) == null ) { echo "\n4 is null"; } else { echo "\n4 Something is WRONG"; } } FINALLY after reading this Topic, I found that this worked!!! { if ((mydomain.co.uk, mydomain)) !== false ) { echo "\n5 is True"; } else { echo "\n5 is False"; } } Thanks for this article, I now understand that even though it's Christmas, it may not be Christmas as false, as its also can be a NULL day! After wasting a day of debugging some simple code, wished I had known this before, as I would have been able to identify the problem, rather than going all over the place trying to get it to work. It didn't work, as False, NULL and 0 are not all the same as True or False or NULL? A: Below is an example: Comparisons of $x with PHP functions Expression gettype() empty() is_null() isset() boolean : if($x) $x = ""; string TRUE FALSE TRUE FALSE $x = null; NULL TRUE TRUE FALSE FALSE var $x; NULL TRUE TRUE FALSE FALSE $x is undefined NULL TRUE TRUE FALSE FALSE $x = array(); array TRUE FALSE TRUE FALSE $x = false; boolean TRUE FALSE TRUE FALSE $x = true; boolean FALSE FALSE TRUE TRUE $x = 1; integer FALSE FALSE TRUE TRUE $x = 42; integer FALSE FALSE TRUE TRUE $x = 0; integer TRUE FALSE TRUE FALSE $x = -1; integer FALSE FALSE TRUE TRUE $x = "1"; string FALSE FALSE TRUE TRUE $x = "0"; string TRUE FALSE TRUE FALSE $x = "-1"; string FALSE FALSE TRUE TRUE $x = "php"; string FALSE FALSE TRUE TRUE $x = "true"; string FALSE FALSE TRUE TRUE $x = "false"; string FALSE FALSE TRUE TRUE Please see this for more reference of type comparisons in PHP. It should give you a clear understanding. A: It's language specific, but in PHP : Null means "nothing". The var has not been initialized. False means "not true in a boolean context". Used to explicitly show you are dealing with logical issues. 0 is an int. Nothing to do with the rest above, used for mathematics. Now, what is tricky, it's that in dynamic languages like PHP, all of them have a value in a boolean context, which (in PHP) is False. If you test it with ==, it's testing the boolean value, so you will get equality. If you test it with ===, it will test the type, and you will get inequality. So why are they useful ? Well, look at the strrpos() function. It returns False if it did not found anything, but 0 if it has found something at the beginning of the string ! <?php // pitfall : if (strrpos("Hello World", "Hello")) { // never exectuted } // smart move : if (strrpos("Hello World", "Hello") !== False) { // that works ! } ?> And of course, if you deal with states: You want to make a difference between DebugMode = False (set to off), DebugMode = True (set to on) and DebugMode = Null (not set at all, will lead to hard debugging ;-)). A: From the PHP online documentation: To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument. When converting to boolean, the following values are considered FALSE: * *the boolean FALSE itself *the integer ``0 (zero) *the float 0.0 (zero) *the empty string, and the string "0" *an array with zero elements *an object with zero member variables (PHP 4 only) *the special type NULL (including unset variables) *SimpleXML objects created from empty tags Every other value is considered TRUE (including any resource). So, in most cases, it's the same. On the other hand, the === and the ==are not the same thing. Regularly, you just need the "equals" operator. To clarify: $a == $b //Equal. TRUE if $a is equal to $b. $a === $b //Identical. TRUE if $a is equal to $b, and they are of the same type. For more information, check the "Comparison Operators" page in the PHP online docs. Hope this helps. A: The differences between these values always come down to detailed language-specific rules. What you learn for PHP isn't necessarily true for Python, or Perl, or C, etc. While it is valuable to learn the rules for the language(s) you're working with, relying on them too much is asking for trouble. The trouble comes when the next programmer needs to maintain your code and you've used some construct that takes advantage of some little detail of Null vs. False (for example). Your code should look correct (and conversely, wrong code should look wrong). A: Null is used in databases to represent "no record" or "no information". So you might have a bit field that describes "does this user want to be sent e-mails by us", where True means they do, False means they don't want to be sent anything, but Null would mean that you don't know. They can come about through outer joins and suchlike. The logical implications of Null are often different - in some languages NULL is not equal to anything, so if(a == NULL) will always be false. So personally I'd always initialise a boolean to FALSE, and initialising one to NULL would look a bit icky (even in C where the two are both just 0... just a style thing). A: In PHP it depends on if you are validating types: ( ( false !== 0 ) && ( false !== -1 ) && ( false == 0 ) && ( false == -1 ) && ( false !== null ) && ( false == null ) ) Technically null is 0x00 but in PHP ( null == 0x00 ) && ( null !== 0x00 ). 0 is an integer value. A: I think bad developers find all different uses of null/0/false in there code. For example, one of the most common mistakes developers make is to return error code in the form of data with a function. // On error GetChar returns -1 int GetChar() This is an example of a sugar interface. This is exsplained in the book "Debuging the software development proccess" and also in another book "writing correct code". The problem with this, is the implication or assumptions made on the char type. On some compilers the char type can be non-signed. So even though you return a -1 the compiler can return 1 instead. These kind of compiler assumptions in C++ or C are hard to spot. Instead, the best way is not to mix error code with your data. So the following function. char GetChar() now becomes // On success return 1 // on failure return 0 bool GetChar(int &char) This means no matter how young the developer is in your development shop, he or she will never get this wrong. Though this is not talking about redudancy or dependies in code. So in general, swapping bool as the first class type in the language is okay and i think joel spoke about it with his recent postcast. But try not to use mix and match bools with your data in your routines and you should be perfectly fine. A: One interesting fact about NULL in PHP: If you set a var equal to NULL, it is the same as if you had called unset() on it. NULL essentially means a variable has no value assigned to it; false is a valid Boolean value, 0 is a valid integer value, and PHP has some fairly ugly conversions between 0, "0", "", and false. A: Null is nothing, False is a bit, and 0 is (probably) 32 bits. Not a PHP expert, but in some of the more modern languages those aren't interchangeable. I kind of miss having 0 and false be interchangeable, but with boolean being an actual type you can have methods and objects associated with it so that's just a tradeoff. Null is null though, the absence of anything essentially. A: Well, I can't remember enough from my PHP days to answer the "===" part, but for most C-style languages, NULL should be used in the context of pointer values, false as a boolean, and zero as a numeric value such as an int. '\0' is the customary value for a character context. I usually also prefer to use 0.0 for floats and doubles. So.. the quick answer is: context. A: In pretty much all modern languages, null logically refers to pointers (or references) not having a value, or a variable that is not initialized. 0 is the integer value of zero, and false is the boolean value of, well, false. To make things complicated, in C, for example, null, 0, and false are all represented the exact same way. I don't know how it works in PHP. Then, to complicate things more, databases have a concept of null, which means missing or not applicable, and most languages don't have a direct way to map a DBNull to their null. Until recently, for example, there was no distinction between an int being null and being zero, but that was changed with nullable ints. Sorry to make this sound complicated. It's just that this has been a harry sticking point in languages for years, and up until recently, it hasn't had any clear resolution anywhere. People used to just kludge things together or make blank or 0 represent nulls in the database, which doesn't always work too well. A: False and 0 are conceptually similar, i.e. they are isomorphic. 0 is the initial value for the algebra of natural numbers, and False is the initial value for the Boolean algebra. In other words, 0 can be defined as the number which, when added to some natural number, yields that same number: x + 0 = x Similarly, False is a value such that a disjunction of it and any other value is that same value: x || False = x Null is conceptually something totally different. Depending on the language, there are different semantics for it, but none of them describe an "initial value" as False and 0 are. There is no algebra for Null. It pertains to variables, usually to denote that the variable has no specific value in the current context. In most languages, there are no operations defined on Null, and it's an error to use Null as an operand. In some languages, there is a special value called "bottom" rather than "null", which is a placeholder for the value of a computation that does not terminate. I've written more extensively about the implications of NULL elsewhere. A: Somebody can explain to me why 'NULL' is not just a string in a comparison instance? $x = 0; var_dump($x == 'NULL'); # TRUE !!!WTF!!! A: The issues with falsyness comes from the PHP history. The problem targets the not well defined scalar type. '*' == true -> true (string match) '*' === true -> false (numberic match) (int)'*' == true -> false (string)'*' == true -> true PHP7 strictness is a step forward, but maybe not enough. https://web-techno.net/typing-with-php-7-what-you-shouldnt-do/
{ "language": "en", "url": "https://stackoverflow.com/questions/137487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "160" }
Q: Fully unwrap a view In Oracle, is there an easy way to fully unwrap a view? eg: If I have a view which is made up of selects on more views, is there some way to unwrap it to just select directly on real tables? A: * *Get the query text of your view. SELECT text FROM dba_views WHERE owner = 'the-owner' AND view_name = 'the-view-name'; *Parse. Search for view names within the query text. *Get the query text for each view name found. (see item 1.) *Replace each view name in the query with the related query text. *Do this recursively until there are no more views found. Easy? EDIT: The above instructions do not do everything required. Thinking about this a little more it gets hairy, grows legs, and maybe another arm. Finding column names, and column names that might be elaborate functions and subqueries. Bringing it all back together with the joins and clauses. The resulting query might look very ugly. Somewhere within Oracle there may be something that is actually unwrapping a view. I don't know. I am glad I didn't use views that much in Oracle. A: The concept of in-line views can be used to do this. Suppose you have these 2 views: create or replace view london_dept as select * from dept where loc = 'LONDON'; and create or replace view london_mgr as select * from emp where job='MANAGER' and deptno in (select deptno from london_dept); In the second view's SQL, the reference to view london_dept can be replaced by an in-line view using the SQL from the london_dept view definition as follows: select * from emp where job='MANAGER' and deptno in (select deptno from (select * from dept where loc = 'LONDON')); Of course, you can now see that is overly verbose and could be simplified to: select * from emp where job='MANAGER' and deptno in (select deptno from dept where loc = 'LONDON'); Finally, some advice from Tom Kyte on the advantages and disadvantages of creating views of views A: Up until Oracle 12.1 the correct answer is no, there is no easy way. Now, in 12.1 there is DBMS_UTILITY.EXPAND_SQL_TEXT : Expand SQL References to Views in Oracle Database 12c Release 1 (12.1) does exactly this. See the documentation of dbms_utility
{ "language": "en", "url": "https://stackoverflow.com/questions/137497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I programmatically show or hide the Outlook envelope icon? For example, how do I show or hide the Outlook envelope icon from an Outlook Rule? The envelope icon option is set by going to: * *Tools -> Options... *E-mail Options *Advanced E-mail Options *Show an envelope icon in the notification area The reason why I say programmatically is because none of the standard Rule actions apply. (The "Clear the message flag" action doesn't seem to work. Also, there's no "Set the message flag" action.) This means that the solution will probably be in the form of a VBA script, Add-in or custom action. As a last resort, I'll write my own task bar notification. In the documentation, I found IMsoEnvelope, but that is only for sending email from other Office applications. A: The action is "Clear the message flag"
{ "language": "en", "url": "https://stackoverflow.com/questions/137519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to protect a Rails model attribute? My Invoice model has an address_id attribute, and I don't want this address_id to change FOREVER. So I don't want this to happen outside the class: invoice.address_id = 1 invoice.address = some_address Rails automatically adds this address_id attribute to the model from the invoice table, so how can I declare this attribute private/protected? Calling attr_protected :address_id is most likely not the solution since based on the documentation it only prevents mass assignments. Thanks! A: Not as pretty as a one liner, but code below should work (and you could always do some metaprogramming to write an 'immutable' method) def address_id=(id) if new_record? write_attribute(:address_id, id) else raise 'address is immutable!' end end A: You want attr_readonly.
{ "language": "en", "url": "https://stackoverflow.com/questions/137521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Where can I find tools for learning assembler on OS X? I'd like to learn assembler. However, there are very few resources for doing assembler with OS X. Is there anyone out there who has programmed in assembly on a Mac? Where did you learn? And, is there any reason I shouldn't be doing assembly? Do I risk (significantly) crashing my computer irreparably? A: The assembler language is determined by the hardware platform, not the operating system. Given that OS X runs on Intel platform and is 64-bit, you should look for information on x64 (also called AMD64) assembler. Check the Wikipedia article (http://en.wikipedia.org/wiki/X86-64) for a lot of links to documentation about x64. Also, the OS X tools documentation might contains a lot of information about x64 assembler. In particular, the Netwide Assembler (NASM - http://developer.apple.com/documentation/DeveloperTools/nasm/nasmdoc0.html) might have documentation on how to build OS X applications using assembler. A: To start learning assembly, you might want to start with simple C programs and ask GCC to generate the assembler code for it using the -S option: gcc -S hello.c -o hello.asm You will then be able to understand how to call functions, pass arguments, etc. A: Nasm/yasm are your best bet; gcc inline syntax is quite crippling and can be very painful to use at times, plus there are literally some things it cannot do. Nasm's macro syntax is also much much more useful, a godsend in a language like assembly that has no built-in templating features. A: If you're using a PowerPC Mac, look into gcc inline assembler. Otherwise, look into nasm. I can't give any decent references to PPC ASM (they're few and far between), but I suggest the following things to learn x86 asm: * *The book Reversing by Eldad Eilam *Compile simple C source with gcc -S and read the assembly generated *Use Sandpile *Join #openrce on irc.freenode.net and use OpenRCE Also, if you're not in kernel mode then there's no chance of screwing anything up, really, and even if you are in kernel mode it's hard to really destroy anything. Edit: Also, get gcc and such from XCode not Macports or somesuch. You're in for a world of malformed Mach-O files if you don't. Not fun to diagnose file format issues when you're just starting asm hacking. A: XCode (ie. GCC) has great support for writing assembler. It's a fun thing to learn (although you're unlikely to need it much), and the worst you can do is crash the program you're writing, same as in C. Just Google for 'gcc inline asm x86 tutorial' and you should find plenty of starting points. Don't worry that some will seem to be Linux specific, they'll generally work just as well in XCode. (edit) ...assuming you have an Intel Mac of course; if not then replace 'x86' with 'ppc'. A: here I programmed assembly on a Mac. It was Motorola 680x0 assembler using MPW. I've touched on the PowerPC assembler a few times in CodeWarrior and ProjectBuilder. Now ProjectBuilder is called XCode, and there is Intel. The assembler is one of the many tools within XCode. I originally learned assembler on the Apple II: the 6502 machine language monitor built in ROM, the Sweet16 mini-assembler, and others. Later, I used Intel 80186 assembler to speed up slow bits of C code, and work paid for a one day course on Intel 80186 assembler at a university. Later, I had to maintain some 680x0 assembly for the Mac. That was a long time ago. I don't think there is any reason not to do assembly. Learning is great. Learn all you can. Drop into a low enough level debugger and look at the disassembled code. My advice is: Don't be scared. A: There's no reason why you shouldn't; there is nothing you can do in assembly language that you can't do in a higher level language like C. As far as tools go, you might want to install MacPorts and get the GNU assembler. That may or may not be the easiest way, but it's free and you can probably find tutorial documentation for writing Unix programs in GNU assembler somewhere on the net. A: There are two three things you to know need for writing assembly language on a system with an operating system (as opposed to 'bare metal' assembly which is a world of its own): * *How the instruction set works - loads of resources for Intel X86 if you have an Intel Mac, still reasonable set for PPC for example Mac OS X Internals. *How to assemble link your programmes - if you have the Developer tools installed you have GCC and associated tools *How to talk to the OS - here is where Mac assembly is a lot less well documented than Windows or Linux. It may be you have to write equivalent C programs and use 'gcc -S' to see what calling/stack restoration conventions are appropriate. It depends what you want to do but at a miniumum you need OS system calls for IO and memory allocation. A good starting point is here. A: If you've got Developer Tools installed, you can simply open Terminal and type as (GNU Assembler - part of Binutils). A: For PPC try Lightsoft
{ "language": "en", "url": "https://stackoverflow.com/questions/137523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How can I set what encoding must be used by a site? On some systems it is UTF-8, on others latin-1. How do you set this? Is it something in php.ini? (I know you can set the encoding/charset for a given page by setting HTTP headers, but this is not what I am looking for.) Alex A: There is a default_charset setting in php.ini A: If you need to change the character set of non php files you can tell apache what to use. AddDefaultCharset utf-8
{ "language": "en", "url": "https://stackoverflow.com/questions/137526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is my stored procedure receiving a null parameter? Ok, this is a curly one. I'm working on some Delphi code that I didn't write, and I'm encountering a very strange problem. One of my stored procedures' parameters is coming through as null, even though it's definitely being sent 1. The Delphi code uses a TADOQuery to execute the stored procedure (anonymized): ADOQuery1.SQL.Text := "exec MyStoredProcedure :Foo,:Bar,:Baz,:Qux,:Smang,:Jimmy"; ADOQuery1.Parameters.ParamByName("Foo").Value := Integer(someFunction()); // other parameters all set similarly ADOQuery1.ExecSQL; Integer(SomeFunction()) currently always returns 1 - I checked with the debugger. However, in my stored proc ( altered for debug purposes ): create procedure MyStoredProcedure ( @Foo int, @Bar int, @Baz int, @Qux int, @Smang int, @Jimmy varchar(20) ) as begin -- temp debug if ( @Foo is null ) begin insert into TempLog values ( "oh crap" ) end -- do the rest of the stuff here.. end TempLog does indeed end up with "oh crap" in it (side question: there must be a better way of debugging stored procs: what is it?). Here's an example trace from profiler: exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL declare @p3 int set @p3=NULL exec sp_executesql N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', N'@P1 int OUTPUT,@P2 int,@P3 int,@P4 int,@P5 int,@P6 int', @p3 output,1,1,1,0,200 select @p3 This looks a little strange to me. Notice that it's using @p3 and @P3 - could this be causing my issue? The other strange thing is that it seems to depend on which TADOConnection I use. The project is a dll which is passed a TADOConnection from another application. It calls all the stored procedures using this connection. If instead of using this connection, I first do this: ConnectionNew := TADOQuery.Create(ConnectionOld.Owner); ConnectionNew.ConnectionString := ConnectionOld.ConnectionString; TADOQuery1.Connection := ConnectionNew; Then the issue does not occur! The trace from this situation is this: exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL declare @p1 int set @p1=64 exec sp_prepare @p1 output, N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)', N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', 1 select @p1 SET FMTONLY ON exec sp_execute 64,0,0,0,0,0,' ' SET FMTONLY OFF exec sp_unprepare 64 SET NO_BROWSETABLE OFF exec sp_executesql N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)', 1,1,1,3,0,'400.00' Which is a bit much for lil ol' me to follow, unfortunately. What sort of TADOConnection options could be influencing this? Does anyone have any ideas? Edit: Update below (didn't want to make this question any longer :P) A: In my programs, I have lots of code very similar to your first snippet, and I haven't encountered this problem. Is that actually your code, or is that how you've represented the problem for us to understand? Is the text for the SQL stored in your DFM or populated dynamically? I was wondering if perhaps somehow the Params property of the query had already got a list of parameters defined/cached, in the IDE, and that might explain why P1 was being seen as output (which is almost certainly causing your NULL problem). Just before you set the ParamByName.Value, try ParamByName("Foo").ParamType=ptInput; I'm not sure why you changing the connection string would also fix this, unless it's resetting the internal sense of the parameters for that query. Under TSQLQuery, the Params property of a query gets reset/recreated whenever the SQL.Text value is changed (I'm not sure if that's true for a TADOQuery mind you), so that first snippet of yours ought to have caused any existing Params information to have been dropped. If the 'ParamByname.ParamType' suggestion above does fix it for you, then surely there's something happening to the query elsewhere (at create-time? on the form?) that is causing it to think Foo is an output parameter... does that help at all? :-) A: caveat: i don't know delphi, but this issue rings a faint bell and so i'm interested in it do you get the same result if you use a TADOStoredProc instead of a TADOQuery? see delphi 5 developers guide also, it looks like the first trace does no prepare call and thinks @P1 is an output paramer in the execute, while the second trace does a prepare call with @P1 as an output but does not show @P1 as an output in the execute step - is this significant? it does seem odd, and so may be a clue you might also try replacing the function call with a constant 1 good luck, and please let us know what you find out! A: I suspect you have some parameters mismatch left over from the previous use of your ADOQuery. Have you tried to reset your parameters after changing the SQL.Text: ADOQuery1.Parameters.Refresh; Also you could try to clear the parameters and explicitly recreate them: ADOQuery1.Parameters.Clear; ADOQuery1.Parameters.CreateParameter('Foo', ftInteger, pdInput, 0, 1); [...] I think changing the connection actually forces an InternalRefresh of the parameters. A: ADOQuery1.Parameters.ParamByName("Foo").Value = Integer(someFunction()); Don't they use := for assignment in Object Pascal? A: @Constantin It must be a typo from the Author of the question. @Blorgbeard Hmmm... When you change SQL of a TADOQuery, is good use to clear the parameters and recreate then using CreateParameter. I would not rely on ParamCheck in runtime - since it leaves the parameters' properties mostly undefined. I've had such type of problem when relying on ParamCheck to autofill the parameters - is rare but occurs. Ah, if you go the CreateParameter route, create as first parameter the @RETURN_VALUE one, since it'll catch the returned value of the MSSQL SP. A: The only time I've had a problem like this was when the DB Provider couldn't distinguish between Output (always sets it to null) and InputOutput (uses what you provide) parameters. A: Ok, progress is made.. sort of. @Robsoft was correct, setting the parameter direction to pdInput fixed the issue. I traced into the VCL code, and it came down to TParameters.InternalRefresh.RefreshFromOleDB. This function is being called when I set the SQL.Text. Here's the (abridged) code: function TParameters.InternalRefresh: Boolean; procedure RefreshFromOleDB; // .. if OLEDBParameters.GetParameterInfo(ParamCount, PDBPARAMINFO(ParamInfo), @NamesBuffer) = S_OK then for I := 0 to ParamCount - 1 do with ParamInfo[I] do begin // .. Direction := dwFlags and $F; // here's where the wrong value comes from // .. end; // .. end; // .. end; So, OLEDBParameters.GetParameterInfo is returning the wrong flags for some reason. I've verified that with the original connection, (dwFlags and $F) is 2 (DBPARAMFLAGS_ISOUTPUT), and with the new connection, it's 1 (DBPARAMFLAGS_ISINPUT). I'm not really sure I want to dig any deeper than that, for now at least. Until I have more time and inclination, I'll just make sure all parameters are set to pdInput before I open the query. Unless anyone has any more bright ideas now..? Anyway, thanks everyone for your suggestions so far. A: I was having a very similar issue using TADOQuery to retrieve some LDAP info, there is a bug in the TParameter.InternalRefresh function that causes an access violation even if your query has no parameters. To solve this, simply set TADOQuery.ParamCheck to false.
{ "language": "en", "url": "https://stackoverflow.com/questions/137530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What makes this the fastest JavaScript for printing 1 to 1,000,000 (separated by spaces) in a web browser? I was reading about output buffering in JavaScript here, and was trying to get my head around the script the author says was the fastest at printing 1 to 1,000,000 to a web page. (Scroll down to the header "The winning one million number script".) After studying it a bit, I have a few questions: * *What makes this script so efficient compared to other approaches? *Why does buffering speed things up? *How do you determine the proper buffer size to use? *Does anyone here have any tricks up her/his sleeve that could optimize this script further? (I realize this is probably CS101, but I'm one of those blasted, self-taught hackers and I was hoping to benefit from the wisdom of the collective on this one. Thanks!) A: What makes this script so efficient compared to other approaches? There are several optimizations that the author is making to this algorithm. Each of these requires a fairly deep understanding of how the are underlying mechanisms utilized (e.g. Javascript, CPU, registers, cache, video card, etc.). I think there are 2 key optimizations that he is making (the rest are just icing): * *Buffering the output *Using integer math rather than string manipulation I'll discuss buffering shortly since you ask about it explicitly. The integer math that he's utilizing has two performance benefits: integer addition is cheaper per operation than string manipulation and it uses less memory. I don't know how JavaScript and web browsers handle the conversion of an integer to a display glyph in the browser, so there may be a penalty associated with passing an integer to document.write when compared to a string. However, he is performing (1,000,000 / 1000) document.write calls versus 1,000,000 - 1,000 integer additions. This means he is performing roughly 3 orders of magnitude more operations to form the message than he is to send it to the display. Therefore the penalty for sending an integer vs a string to document.write would have to exceed 3 orders of magnitude offset the performance advantage of manipulating integers. Why does buffering speed things up? The specifics of why it works vary depending on what platform, hardware, and implementation you are using. In any case, it's all about balancing your algorithm to your bottleneck inducing resources. For instance, in the case of file I/O, buffer is helpful because it takes advantage of the fact that a rotating disk can only write a certain amount at a time. Give it too little work and it won't be using every available bit that passes under the head of the spindle as the disk rotates. Give it too much, and your application will have to wait (or be put to sleep) while the disk finishes your write - time that could be spent getting the next record ready for writing! Some of the key factors that determine ideal buffer size for file I/O include: sector size, file system chunk size, interleaving, number of heads, rotation speed, and areal density among others. In the case of the CPU, it's all about keeping the pipeline full. If you give the CPU too little work, it will spend time spinning NO OPs while it waits for you to task it. If you give the CPU too much, you may not dispatch requests to other resources, such as the disk or the video card, which could execute in parallel. This means that later on the CPU will have to wait for these to return with nothing to do. The primary factor for buffering in the CPU is keeping everything you need (for the CPU) as close to the FPU/ALU as possible. In a typical architecture this is (in order of decreasing proximity): registers, L1 cache, L2 cache, L3 cache, RAM. In the case of writing a million numbers to the screen, it's about drawing polygons on your screen with your video card. Think about it like this. Let's say that for each new number that is added, the video card must do 100,000,000 operations to draw the polygons on your screen. At one extreme, if put 1 number on the page at a time and then have your video card write it out and you do this for 1,000,000 numbers, the video card will have to do 10^14 operations - 100 trillion operations! At the other extreme, if you took the entire 1 million numbers and sent it to the video card all at once, it would take only 100,000,000 operations. The optimal point is some where in the middle. If you do it one a time, the CPU does a unit of work, and waits around for a long time while the GPU updates the display. If you write the entire 1M item string first, the GPU is doing nothing while the CPU churns away. How do you determine which buffer size to use? Unless you are targeting a very specific and well defined platform with a specific algorithm (e.g. writing packet routing for an internet routing) you typically cannot determine this mathematically. Typically, you find it empirically. Guess a value, try it, record the results, then pick another. You can make some educated guesses of where to start and what range to investigate based on the bottlenecks you are managing. Does anyone here have any tricks up her/his sleeve that could optimize this script further? I don't know if this would work and I have not tested it however, buffer sizes typically come in multiples of 2 since the under pinnings of computers are binary and word sizes are typically in multiples of two (but this isn't always the case!). For example, 64 bytes is more likely to be optimal than 60 bytes and 1024 is more likely to be optimal than 1000. One of the bottlenecks specific to this problem is that most browsers to date (Google Chrome being the first exception that I'm aware of) have javascript run serially within the same thread as the rest of the web page rendering mechanics. This means that the javascript does some work filling the buffer and then waits a long time until the document.write call returns. If the javascript was run as separate process, asynchronously, like in chrome, you would likely get a major speed up. This is of course attacking the source of the bottleneck not the algorithm that uses it, but sometimes that is the best option. Not nearly as succinct as I would like it, but hopefully it's a good starting point. Buffering is an important concept for all sorts of performance issues in computing. Having an good understanding of the underlying mechanisms that your code is using (both hardware and software) is extremely useful in avoiding or addressing performance issues. A: I would bet the slowest thing in printing 1m numbers is the browser redrawing the page, so the fewer times you call document.write(), the better. Of course this needs to be balanced against large string concatenations (because they involve allocating and copying). Determining the right buffer size is found through experimentation. In other examples, buffering helps align along natural boundaries. Here are some examples * *32 bit CPUs can transfer 32 bits more efficiently. *TCP/IP packets have maximum sizes. *File I/O classes have internal buffers. *Images, like TIFFs, may be stored with their data in strips. Aligning with the natural boundaries of other systems can often have performance benefits. A: One way to think about it is to consider that a single call to document.write() is very expensive. However, building an array and joining that array into a string is not. So reducing the number of calls to document.write() effectively reduces the overall computational time needed to write the numbers. Buffers are a way to try and tie together two different cost pieces of work. Computing and filling arrays has a small cost for small arrays, bug large cost for large arrays. document.write has a large constant cost regardless of the size of the write but scales less than o(n) for larger inputs. So queuing up larger strings to write, or buffering them, speeds overall performance. Nice find on the article by the way. A: So this one has been driving me crazy cause I don't think it really is the fastest. So here is my experiment that anyone can play with. Perhaps I wrote it wrong or something, but it would appear that doing it all at once instead of using a buffer is actually a faster operation. Or at least in my experiments. <html> <head> <script type="text/javascript"> function printAllNumberBuffered(n, bufferSize) { var startTime = new Date(); var oRuntime = document.getElementById("divRuntime"); var oNumbers = document.getElementById("divNumbers"); var i = 0; var currentNumber; var pass = 0; var numArray = new Array(bufferSize); for(currentNumber = 1; currentNumber <= n; currentNumber++) { numArray[i] = currentNumber; if(currentNumber % bufferSize == 0 && currentNumber > 0) { oNumbers.textContent += numArray.join(' '); i = 0; } else { i++; } } if(i > 0) { numArray.splice(i - 1, bufferSize - 1); oNumbers.textContent += numArray.join(' '); } var endTime = new Date(); oRuntime.innerHTML += "<div>Number: " + n + " Buffer Size: " + bufferSize + " Runtime: " + (endTime - startTime) + "</div>"; } function PrintNumbers() { var oNumbers = document.getElementById("divNumbers"); var tbNumber = document.getElementById("tbNumber"); var tbBufferSize = document.getElementById("tbBufferSize"); var n = parseInt(tbNumber.value); var bufferSize = parseInt(tbBufferSize.value); oNumbers.textContent = ""; printAllNumberBuffered(n, bufferSize); } </script> </head> <body> <table border="1"> <tr> <td colspan="2"> <div>Number:&nbsp;<input id="tbNumber" type="text" />Buffer Size:&nbsp;<input id="tbBufferSize" type="text" /><input type="button" value="Run" onclick="PrintNumbers();" /></div> </td> </tr> <tr> <td style="vertical-align:top" width="30%"> <div id="divRuntime"></div> </td> <td width="90%"> <div id="divNumbers"></div> </td> </tr> </table> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/137534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Assembler library for .NET, assembling runtime-variable strings into machine code for injection Is there such a thing as an x86 assembler that I can call through C#? I want to be able to pass x86 instructions as a string and get a byte array back. If one doesn't exist, how can I make my own? To be clear - I don't want to call assembly code from C# - I just want to be able to assemble code from instructions and get the machine code in a byte array. I'll be injecting this code (which will be generated on the fly) to inject into another process altogether. A: See this project: https://github.com/ZenLulz/MemorySharp This project wraps the FASM assembler, which is written in assembly and as a compiled as Microsoft coff object, wrapped by a C++ project, and then again wrapped in C#. This can do exactly what you want: given a string of x86/x64 assembly, this will produce the bytes needed. If you require the opposite, there is a port of the Udis86 disassembler, fully ported to C#, here: https://github.com/spazzarama/SharpDisasm This will convert an array of bytes into the instruction strings for x86/x64 A: Take a look at Phoenix from Microsoft Research. A: As part of some early prototyping I did on a personal project, I wrote quite a bit of code to do something like this. It doesn't take strings -- x86 opcodes are methods on an X86Writer class. Its not documented at all, and has nowhere near complete coverage, but if it would be of interest, I would be willing to open-source it under the New BSD license. UPDATE: Ok, I've created that project -- Managed.X86 A: Not directly from C# you can't. However, you could potentially write your own wrapper class that uses an external assembler to compile code. So, you would potentially write the assembly out to a file, use the .NET Framework to spin up a new process that executes the assembler program, and then use System.IO to open up the generated file by the assembler to pull out the byte stream. However, even if you do all that, I would be highly surprised if you don't then run into security issues. Injecting executable code into a completely different process is becoming less and less possible with each new OS. With Vista, I believe you would definitely get denied. And even in XP, I think you would get an access denied exception when trying to write into memory of another process. Of course, that raises the question of why you are needing to do this. Surely there's got to be a better way :). A: Cosmos also has some interesting support for generating x86 code: http://www.gocosmos.org/blog/20080428.en.aspx A: Take a look at this: CodeProject: Using unmanaged code and assembly in C#. A: I think you would be best off writing a native Win32 dll. You can then write a function in assembler that is exported from the dll. You can then use C# to dynamically link to the dll. This is not quite the same as passing in a string and returning a byte array. To do this you would need an x86 assembler component, or a wrapper around masm.exe. A: i don't know if this is how it works but you could just shellexecute an external compiler then loading the object generated in your byte array.
{ "language": "en", "url": "https://stackoverflow.com/questions/137544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Is programming a subset of math? I've heard many times that all programming is really a subset of math. Some suggest that OO, at its roots, is mathematically based, but I don't get the connection, aside from some obvious examples: * *using induction to prove a recursive algorithm, *formal correctness proofs, *functional languages, *lambda calculus, *asymptotic complexity, *DFAs, NFAs, Turing Machines, and theoretical computation in general, *and the fact that everything on the box is binary. I know math is very important to programming, but I struggle with this "subset" view. In what ways is programming a subset of math? I'm looking for an explanation that might have relevance to enterprise/OO development, if there is a strong enough connection, that is. A: It's math in the sense that it requires abstract thought about algorithms etc. It's engineering when it involves planning schedules, deliverables, testing. It's art when you have no idea how it's going to eventually turn out. A: Disclaimer: I work as an IT consultant and develop mainly portals and Architecture stuff. I have a Psychology degree. I never studied Maths in University. And i get my job done. And usually well. Why? Because I don't think you need to know Maths (as in 'heavy' Maths stuff) to write code. You need analytical thinking, problem-solving skills, and a high level of abstraction. But Maths does not give you that. It's just another discipline that requires similar skills. My studies in Psychology also apply to my daily work when dealing with usability issues and data storage. Linguistics and Semiotics also play a part. But wait, just don't flame me yet. I'm not saying Maths are not needed at all for computers - obviously, you need real Math skills when designing encryption algorithms and hardware and etc -- but if, as lots of programmers, you just work an a mid/low level language (like C) or higher level stuff (like C# or java), consuming mostly pre-built frameworks and APIs, you don't really need to understand the mathematical principles behind Fourier transforms or Huffman trees or Moebius strips... let someone else handle that, and let me build value on top of it. I am not stupid. I know the difference between linear and exponential algorithms and data structures and etc. I just don't have the interest to rewrite quicksort or a spiffy new video compression technique. A: Programming is one of the most difficult branches of applied mathematics; the poorer mathematicians had better remain pure mathematicians. --E. W. Dijkstra A: Well, aside from all that...! Math is used for many aspects of programming such as * *Creating efficient and smart algorithms *Understanding Big O notation *Security (such as RSA) *Many more... I think that programming needs math to survive. But I wouldn't call it a subset. It's just like blowing glass uses properties of physics, but those artists don't call themselves physicists. A: Overall, remember that mathematics is a formal codification of logic, which is also what we do in software. The list of topics in your question is loaded with mathematical problems. We are able to do programming on a fairly high level of abstraction, so the raw mathematics may not be staring you in the face. For example, you mentioned DFAs.. you can use a regular expression in your programs without knowing any math, but you'll find more of a need for mathematics when you want to design a good regular expression engine. I think you've hit on an interesting point. Programming is an art and a science. There are a lot of "tools of the trade", and you don't necessarily sit down and do a lot of high-level mathematics in order to simply write a program. In fact, when you're programming, you many not really being doing much mathematics or computer science. It's when we start to solve difficult problems in computer science that mathematics shows up. The deeper you go, the more it will flesh itself out.. often in lower levels of abstraction. There are also some realms of programming that you don't necessarily have to work in, but they involve more math. For example, while you can certainly learn a language and write some apps without any formal mathematics, you won't get very far in algorithm analysis without some applied math. A: The foundation of everything we do is math. Luckily, we don't need to be good at math itself to do it. Just like you don't need to understand physics to drive a car or even fly a plane. A: OK, I was a math and CS major in college. I would say that if the set A is Math and the set B is CS, then A intersects B. It's not a subset. It's no doubt that many of the fathers and mothers of computer science were Mathematicians like Turing and Dykstra. Most of the founders of the internet were either Phd's in Math, Physics, or Engineering. Most of the core concepts of computer science come from math, but the act of programming isn't really math. Math helps us in our daily lives, but the two aren't the same. But there is no doubt that the original reasoning behind the computer was to well, compute things. We have come a long way from there in such a short time. A: Doesn't mention programming, but idea is still relevant. A: The difference between programming and pure mathematics is the concept of state. Have a look at http://en.wikipedia.org/wiki/Dynamic_logic_(modal_logic). It's a way of mathematically analyzing things changing through time. Also, Hoare triples is a way of formalizing the input-output behavior of programs. By having some axioms dealing with sequential composition of programs and how assignment works, you can perfectly well deal with state changing over time in a mathematically rigorous way. If the math you know is insufficient, "invent" some new math to deal with what you want to analyze. Newton and Leibniz did it for analysis (aka calculus, I think). No reason to not do it for computation and programming. A: Einstein was known in 1917 as a famous mathematician. It wasn't until Hiroshima that the general public finally came around to the realization that physics is not just applied mathematics. When people don't understand something, they try to understand it as a type of something that they do understand. They think by analogy. Programming has been described as a field of math, engineering, science, art, craft, construction... None of these are completely false; it borrows from all of these. The real issue is that the field of programming is only about 50 years old. People have not integrated it into their mental taxonomies. A: I don't believe I've heard that programming is a subset of math. Even the link you provide is simply a proposed approach to programming (not claiming it's a subset of mathematics) and the wiki page has plenty of disagreements in it as well. Programming requires (at least some) applied mathematics. Mathematics can be used to help describe and analyze programs and program fragments. Programming has a very close relationship with math and uses it and concepts from it heavily. But subset? no. I'd love to see someone actually claim that it is one with some clear reasoning. I don't think I ever have Just because you can use mathematics to reason about something does not imply that it is, ipso facto, a mathematical object. Mathematics is used to reason about internal combustion engines, radioactive decay and juggling patterns. Using mathematics is not doing mathematics. A: I would say... It's partly math, especially at the theoretical level. Imagine designing efficient searching/sorting/clustering/allocating/fooifying algorithms, that's all math... running the gamut from number theory to statistics. It's partly engineering. Complex systems can rarely achieve ideal levels of performance and reliability, and software is no exception. A lot of software development is about achieving robustness in the face of unreliable hardware and (ahem) humans. And it's partly art. Creative and idiosyncratic software design often comes up with great new ideas... like assembly language, multitasking operating systems, graphical user interfaces, dynamic languages, and the web. Just my 2¢... A: Math + art + logic A: You can actually argue that math, in the form of logical proofs, is analogous to programming -- Check out the Curry-Howard correspondence. It's probably more the way a mathematician would look at things, but I think this is hitting the proverbial nail on the head. A: Programming may have originally started as a quasi-subset of math, but the increasing complexity of the field over time has led to programming being the art and science of creating good abstractions for information processing and computation. Programming does involve math, engineering, and an aesthetic sense for good design and implementation. Algorithms are an extension of mathematics, and the systems engineering side overlaps with other engineering disciplines to some degree. However, neither mathematics nor other engineering fields have the same level of need for complex, flexible, and yet understandable abstractions that can be used and adapted at so many different levels to solve new and evolving problems. It is the need for useful, flexible, and dynamic abstractions which led first to the creation of function libraries, then class/component libraries, and in more recent years design patterns and service-oriented architectures. Although the latter have more of a design focus, they are a reaction to the increasing need to build high-level abstractional bridges between programming problems and solutions. For all of these reasons, programming is neither a subset nor a superset of math. It is simply yet another field which uses math that has deeper roots in it than others do. A: The topics you listed are topics in Theoretical Computer Science, and THAT is a branch of Pure Mathematics. Programming is an applied science which uses theoretical computer science. Programming itself isn't a branch of mathematics but the Lambda Calculus/theory of computation/formal logic/set theory etc that programming languages are based on is. Also I completely disagree with Dijkstra. It's either self-congratulatory or Dijkstra is being misquoted/quoted out of context. Pure mathematics is a very very very difficult field. It is so enormously abstract that no branch of applied mathematics is comparable in difficulty. It is one field that requires enormous leaps of imagination. I did my first degree in computer science where I focused a lot on theoretical CS and applied areas like programming, OS, compilers. I also did a degree in Electrical Engineering - arguably the most difficult branch of engineering - and worked on difficult areas of applied mathematics like Maxwell's equations, control theory and partial differential equations in general. I've also done research in applied and pure mathematics, and to this day I find applied far easier. As for the pure mathematicians, they're a whole different breed. Now there's a tendency for someone to study an year or two of calculus unhinged from application and conclude that pure mathematics is easy. They have no idea what they're talking about. Studying calculus or even topology unhinged from application does not give you any inkling of what a pure mathematician does. The task of actually proving those theorems are so profoundly difficult that I will defer to a computer scientist to point out the distinction: "If P = NP, then the world would be a profoundly different place than we usually assume it to be. There would be no special value in 'creative leaps,' no fundamental gap between solving a problem and recognizing the solution once it’s found. Everyone who could appreciate a symphony would be Mozart; everyone who could follow a step-by-step argument would be Gauss..." —Scott Aaronson, (Theoretical Computer Scientist, MIT) A: I think mathematics provides a set of tools for programmers which they use at abstract level to solve real world problems. A: There's a lot of confusion here. First of all, "programming" does not (currently) equal "computer science." When Dijkstra called himself a "programmer" (more or less inventing the title), he was not pumping out CRUD applications, but actually doing applied computer science. Let's not let that confuse us-- today, there is a vast difference between what most programmers in a business setting do and computer science. Now, the argument can be made that computer science is a branch of mathematics; but, as Knuth points out (in his paper "Computer Science and its Relation to Mathematics", collected in his Selected Papers on Computer Science) it can also be argued that mathematics is a branch of computer science. In fact, I'd strongly recommend this paper to anyone thinking about the relationship between mathematics and computer science, as Knuth lays out the territory nicely. But, to return to your original question: to a practitioner, "enterprise/OO development" is pretty far removed from mathematics-- but that's largely because most of the serious mathematics involved at the lower levels of operation have been abstracted away (by compilers, operating systems, instruction sets, etc.). Similarly, advanced knowledge of the physics of the internal combustion engine are not required for driving a car. Naturally, if you want to design a more efficient car.... A: if your definition of math includes all forms of formal logic, and programming is defined only by the logic and calculations extant in the code, then programming is a subset of math QED ;-) but this is like saying that painting is merely putting colored pigments on a surface - it completely igores the art, the insight, the intuition, the entire creative process one could argue that music is a subset of math by the same reasoning so i'd have to say no, programming is not a subset of math. Programming uses a subset of math, but requires non-math skills/talent as well [much like music composition] A: I would say that programming is less about math than it used to be as we move up to 4th Generation Languages. Assembly is very much about math, C#, not so much. Thoughts? A: If you just want the design specs handed out to you by your boss, then it's not much math but such a work isn't fun at all... However, coming up with how to do things does require mathematical ideas, at least things like abstraction, graphs, sometimes number theory stuffs and depending on the problems, calculus. Personally, more I've been involved with programming, more I see the mathematical side to it. However, most of the times IMO, you can just pick up the book from library and look up the basics of the thing you need to do but that requires some mathematical grasp upfront. You really can't design "good" algorithms without understanding the maths behind it. Searching in google takes you only so far. A: Programming is a too wide subject. Good software based not only on math (logic) but also on psychology, linguistics etc. Algorithms are part of math, but there are many other programming-related things besides algorithms. A: As a mathematician, it is clear to me that Math is not equal to Programming but that the process which is used to solve problems in either discipline is extremely similar. Solving a higher level mathematics questions requires analytical thinking, a toolbox of possible ways of solving problems, experience with the field, and some formalized ways of constructing your answer so that other mathematicians agree. If you find a particularly clever, abstract, or elegant way of solving a problem, you get Kudos from your fellow mathematicians. For particularly difficult math problems, you may solve the problem in stages, and codify your stage arguments using things called conjectures and proofs. I think programming involves the same set of skills. In programming, the same set of principles applies to the solving and presenting of solutions to problems. When you have a partial solution to a programming dilemna, you include it as part of your personal library and use it as part of another bigger problem later. These skills seem very similar to the skills used in mathematics. The major difference between Math and Programming is the latter has a lot more in common between different disciplines of programming than Math does. Two fields of mathematics can be very, very different in presentation and what is used to communicate the field. By contrast, programming structures, to me at least, look very similar in many different languages. A: The difference between programming and pure mathematics is the concept of state. A program is a state machine that uses logic (maths) to transition between states. The actual logic used to transition between states is usually very simple, which is why being a math genius doesn't necessarily help you all that much as a programmer. A: Part of the reason I'm a programmer is because I don't like math. I have no problem with math itself, and I'm fine with it conceptually, I just don't like doing calculations by hand. When I found I could tell a computer what the math problem is and let it do the calculating for me, a life-long passion and career was born. To answer the question, according to my alma mater, math == programming since they allowed me to take Intro to C++ to fulfill my math requirement. Edit: I should mention my degree is in telecommunications which, at the time, had only the standard liberal arts math requirement of one semester. A: Math is the purest form of truth. Everything inherits from math. Amen. A: It's interesting to compare programming with music too. In UK, anyway, there are computing based undergrad university courses that will accept applicants on the bases of music qualifications as supposed to computing due to the logic, patterns, etc. involved. A: Maths is powerful, programming is powerful, if maths is a subset of programming then it is equally true to state that programming is a subset of maths. Maths is described using language, often written down. Therefore is maths a subset of writing too? Historicly maths came before computer programming, but then lists and processes probably preceded maths, both of which could be equally thought of as mathematical or do with programming. Cirtainly programming can be represented using maths, so there is some bases for it being true that programming is a sub-set of maths. However a computer program could also implement maths, representing information symbolically, as maths typically does when done on paper, including the infinite and only somewhat defined, from the fundamental axioms, as well as allowing higher level structures to be defined that use each other and other sorts of relationships beyond composition, supporting the drawing of diagrams and allowing the system to be expanded. Maths is equally a subset of programming. While maths can represent structures such as words, maths is by design about numbers. Strings for example are more programmatic than mathematic. A: It's half math, half man speak, duh.
{ "language": "en", "url": "https://stackoverflow.com/questions/137550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "66" }
Q: How can I perform a HEAD request with the mechanize library? I know how to do a HEAD request with httplib, but I have to use mechanize for this site. Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file. Any suggestions how I could accomplish this? A: Mechanize itself only sends GETs and POSTs, but you can easily extend the Request class to send HEAD. Example: import mechanize class HeadRequest(mechanize.Request): def get_method(self): return "HEAD" request = HeadRequest("http://www.example.com/") response = mechanize.urlopen(request) print response.info() A: In mechanize there is no need to do HeadRequest class etc. Simply import mechanize br = mechanize.Browser() r = br.open("http://www.example.com/") print r.info() That's all.
{ "language": "en", "url": "https://stackoverflow.com/questions/137580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I embed a custom user-control in MS Word? Context: The environment is .Net 3.0 + WPF land, the DB is abstracted well out into the distance and the solution would need to work for Office 2000 and up I guess.. The need is to get a customized report for which the user would like to have certain application windows/boxes (e.g. a trend graph) displayed in Word. The window can be shown as a static image, the user can double-click and edit it (that would bring up an editor.. similar to behavior for an embedded spreadsheet) and OK out to update the object. Type some text around the box and save it or print it. Also take into account, that I would need some mechanism to pass in data and kind of "data-bind" these app-specific boxes to it. e.g. the graph may have to bind to a specific time-range of data that it needs. Now as a relative beginner to Word automation, what is the name of the tech / sub-tech that I would need to use for this? Also post any recommendations to books/posts that help you understand and get to running speed ASAP.. (since the business always believes the programmers are smart enough to figure it out.. we can give them complete trust.. but no time.) A: I think you are going to have to look into writing an OLE embeddable/compatible application. It sounds like this may be a very large and complex task. Is there any reason that Excel cannot do the graph that you are embedding? A: I would strongly recommend making it dependant on Office 2007 and later. If you do so, you can use the ribbon and do .Net programming via VSTO.
{ "language": "en", "url": "https://stackoverflow.com/questions/137586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the best way to parse a web page in Ruby? I have been looking at XML and HTML libraries on rubyforge for a simple way to pull data out of a web page. For example if I want to parse a user page on stackoverflow how can I get the data into a usable format? Say I want to parse my own user page for my current reputation score and badge listing. I tried to convert the source retrieved from my user page into xml but the conversion failed due to a missing div. I know I could do a string compare and find the text I'm looking for, but there has to be a much better way of doing this. I want to incorporate this into a simple script that spits out my user data at the command line, and possibly expand it into a GUI application. A: try hpricot, its well... awesome I've used it several times for screen scraping. A: Hpricot is over ! Use Nokogiri now. A: Unfortunately stackoverflow is claiming to be XML but actually isn't. Hpricot however can parse this tag soup into a tree of elements for you. require 'hpricot' require 'open-uri' doc = Hpricot(open("http://stackoverflow.com/users/19990/armin-ronacher")) reputation = (doc / "td.summaryinfo div.summarycount").text.gsub(/[^\d]+/, "").to_i And so forth. A: I always really like what Ilya Grigorik writes, and he wrote up a nice post about using hpricot. I also read this post a while back and it looks like it would be useful for you. Haven't done either myself, so YMMV but these seem pretty useful. A: Something I ran into trying to do this before is that few web pages are well-formed XML documents. Hpricot may be able to deal with that (I haven't used it) but when I was doing a similar project in the past (using Python and its library's built in parsing functions) it helped to have a pre-processor to clean up the HTML. I used the python bindings for HTML Tidy as this and it made life a lot easier. Ruby bindings are here but I haven't tried them. Good luck! A: it seems to be an old topic but here is a new one. Example getting reputation: #!/usr/bin/env ruby require 'rubygems' require 'hpricot' require 'open-uri' user = "619673/100kg" html = "http://stackoverflow.com/users/%s?tab=reputation" page = html % user puts page doc = Hpricot(open(page)) pars = Array.new doc.search("div[@class='subheader user-full-tab-header']/h1/span[@class='count']").text.each do |p| pars << p end puts "reputation " + pars[0]
{ "language": "en", "url": "https://stackoverflow.com/questions/137605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Is it ok to call a virtual method from Dispose or a destructor? I can't find a reference to it but I remember reading that it wasn't a good idea to call virtual (polymorphic) methods within a destructor or the Dispose() method of IDisposable. Is this true and if so can someone explain why? A: Calling virtual methods from a finalizer/Dispose is unsafe, for the same reasons it is unsafe to do in a constructor. It is impossible to be sure that the derived class has not already cleaned-up some state that the virtual method requires to execute properly. Some people are confused by the standard Disposable pattern, and its use of a virtual method, virtual Dispose(bool disposing), and think this makes it Ok to use any virtual method durring a dispose. Consider the following code: class C : IDisposable { private IDisposable.Dispose() { this.Dispose(true); } protected virtual Dispose(bool disposing) { this.DoSomething(); } protected virtual void DoSomething() { } } class D : C { IDisposable X; protected override Dispose(bool disposing) { X.Dispose(); base.Dispose(disposing); } protected override void DoSomething() { X.Whatever(); } } Here's what happens when you Dispose and object of type D, called d: * *Some code calls ((IDisposable)d).Dispose() *C.IDisposable.Dispose() calls the virtual method D.Dispose(bool) *D.Dispose(bool) disposes of D.X *D.Dispose(bool) calls C.Dispose(bool) statically (the target of the call is known at compile-time) *C.Dispose(bool) calls the virtual methods D.DoSomething() *D.DoSomething calls the method D.X.Whatever() on the already disposed D.X *? Now, most people who run this code do one thing to fix it -- they move the base.Dispose(dispose) call to before they clean-up their own object. And, yes, that does work. But do you really trust Programmer X, the Ultra-Junior Developer from the company you developed C for, assigned to write D, to write it in a way that the error is either detected, or has the base.Dispose(disposing) call in the right spot? I'm not saying you should never, ever write code that calls a virtual method from Dispose, just that you'll need to document that virtual method's requirement that it never use any state that's defined in any class derived below C. A: Virtual methods are discouraged in both constructors and destructors. The reason is more practical than anything: virtual methods can be overridden in any manner chosen by the overrider, and things like object initialization during construction, for example, have to be ensured lest you end up with an object that has random nulls and an invalid state. A: I do not believe there is any recommendation against calling virtual methods. The prohibition you are remembering might be the rule against referencing managed objects in the finalizer. There is a standard pattern that is defined the .Net documentation for how Dispose() should be implemented. The pattern is very well designed, and it should be followed closely. The gist is this: Dispose() is a non-virtual method that calls a virtual method Dispose(bool). The boolean parameter indicates whether the method is being called from Dispose() (true) or the object's destructor (false). At each level of inheritance, the Dispose(bool) method should be implemented to handle any cleanup. When Dispose(bool) is passed the value false, this indicates that the finalizer has called the dispose method. In this circumstance, only cleanup of unmanaged objects should be attempted (except in certain rare circumstances). The reason for this is the fact that the garbage collector has just called the finalize method, therefore the current object must have been marked ready-for-finalization. Therefore, any object that it references may also have been marked read-for-finalization, and since the sequence in non-deterministic, the finalization may have already occurred. I highly recommend looking up the Dispose() pattern in the .Net documentation and following it precisely, because it will likely protect you from bizarre and difficult bugs! A: To expand on Jon's answer, instead of calling virtual methods you should be overriding the dispose or the destructor on sub classes if you need to handle resources at that level. Although, I don't believe there is a "rule" in regards to behavior here. But the general thought is that you want to isolate resource cleanup to only that instance at that level of the implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/137621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is Test Driven Development good for a starter? Expanding this question on how I learnt to pass from problem description to code Two people mentioned TDD. Would it be good for a starter to get into TDD ( and avoid bad habits in the future ? ) Or would it be too complex for a stage when understand what a programming language is? A: TDD is meant to be simpler than the "traditional" method (of not testing it till the end) - because the tests clarify what you understand of the problem. If you actually didn't have a clear idea of what the problem was, writing tests is quite hard. So for a beginner, writing tests gets the thinking juice going in the right direction, which is contractual behaviour, not implementation behaviour. A: I wish TDD were around when I was first learning to program, and that I had picked it up before getting so entrenched in the 'old way' such that it's very difficult for me to learn TDD... A: Experiencing TDD Rules All I also think that ideally TDD would be very helpful in the early stages of learning. In hindsight I know it would of helped me approach the problems in a completely different light. What I'm perplexed about is that when one is learning, there are so many new concepts being absorbed that confusion can start to set in very early. Therefore, while I do think TDD would be super helpful, I don't think it can be something that's learned successfully by one's self. Just like anything else in life we tend to learn best when somebody is physically teaching us. Showing us how they approach the problems in a TDD manner can do so much more than reading about it in books or on the web. I mean, this can't hurt but it's not a substitute for a mentor that can truly show you the ropes. Experiencing TDD is everything so if you can have somebody teach you how to TDD during those early stages, I think learning as a whole would be accelerated beyond what anyone would expect. A: def self.learn_tdd_and_programming_together? if you_have_tdd_mentor_sitting_next_to_you? "go for it" else if language.ruby? "it's possible, there is quite a bit of good stuff out there that could give you a chance of learning programming with TDD from the start. It's sort of in the ruby culture" elsif language.dot_net? "learn TDD after you learn the basics of .NET" end end end A: it's certainly a lot to take in, but having said that I wish I started out writing unit tests. What would actually have been good was if I had a mentor at my workplace who could have guided my TDD progress. I've been self learning TDD on and off for about a year and there's a lot to cover and the more you do it the more involved it gets, but it's really starting to pay off now for me. A: I think this comment illustrates that it can be a very good thing for beginners to learn straight up. A: My programming motto is: * *Make it run -- the program solves the problem *Make it right -- the program is designed cleanly and there is a small amount of duplication *Make it fast -- optimized (if needed) Test Driven Development handles the first two. I think a beginner should be taught TDD so that he knows how to make programs run. IMHO, only then can good design techniques be taught. A: I think yes. Studies even found that the benefits are largest for beginners. It gives you more guidance for writing the code. You know what the results and behavior should be, and write the tests. Then you write the code. Tests pass. You're done. And you know you're done. A: Yes! Definitely. A: I think it's not good for someone just learning programming. How will that person know what to assert? :P TDD is for design, not for testing. Once a person knows how to program, it'll be a good thing to start studiying the TDD approach. A: First you need to understand how to code well. Read, study and practive that until you have a good handle on it. Once you have that, look into test driven design - it's very powerful. A: An important benefit of TDD is defining doneness. In simple algorithmic programming, if you come up with a couple scenarios where correctness is easily asserted, its easy to enumerate them in a unit test and keep coding until they all work. Sometimes unit testing can be hard for beginners, if there are many dependencies and you start to run into scenarios where mocking objects is necessary. However, if you can make a simple statement about correctness, and it is easy to type out, then definitely write it down in code. You may also note that if a simple statement of correctness is not easily described, you may not fully understand your problem. Good luck... A: It really depends on your definition of a "starter". If by "starter" you mean someone with absolutely no programming background, then no, I don't think TDD is a very good way to start out. A programmer needs to learn the basics (avoiding infinite loops, memory allocation, etc.) before worrying about refactoring and test driven development. A: code is code whether it is the thing you're trying to spike out, or a test. Learning TDD at the very beginning has a lot of value. It's one of those skills that should be a habit. There are a lot of us out there that understand and like the value of tdd but years of programming have instilled some some habits that can be hard to break later on. As far as TDD being for contract design/code implementation/testing it's all of those things. Will TDD bring you to the perfect code? No, experience and studying the craft will help you mature your coding approaches. But TDD is a very important tool for every developer. The use of TDD will hopefully help bring you to a design that is testable. And a design that is testable is in theory well encapsulated and should adhere to the open closed principal. In my opinion as long as people view TDD as something that's a niche tool or is somehow optional while writing code, those people obviously don't get the value of TDD.
{ "language": "en", "url": "https://stackoverflow.com/questions/137623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do you render primitives as wireframes in OpenGL? How do you render primitives as wireframes in OpenGL? A: In Modern OpenGL(OpenGL 3.2 and higher), you could use a Geometry Shader for this : #version 330 layout (triangles) in; layout (line_strip /*for lines, use "points" for points*/, max_vertices=3) out; in vec2 texcoords_pass[]; //Texcoords from Vertex Shader in vec3 normals_pass[]; //Normals from Vertex Shader out vec3 normals; //Normals for Fragment Shader out vec2 texcoords; //Texcoords for Fragment Shader void main(void) { int i; for (i = 0; i < gl_in.length(); i++) { texcoords=texcoords_pass[i]; //Pass through normals=normals_pass[i]; //Pass through gl_Position = gl_in[i].gl_Position; //Pass through EmitVertex(); } EndPrimitive(); } Notices : * *for points, change layout (line_strip, max_vertices=3) out; to layout (points, max_vertices=3) out; *Read more about Geometry Shaders A: If you are using the fixed pipeline (OpenGL < 3.3) or the compatibility profile you can use //Turn on wireframe mode glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the scene with polygons as lines (wireframe) renderScene(); //Turn off wireframe mode glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); In this case you can change the line width by calling glLineWidth Otherwise you need to change the polygon mode inside your draw method (glDrawElements, glDrawArrays, etc) and you may end up with some rough results because your vertex data is for triangles and you are outputting lines. For best results consider using a Geometry shader or creating new data for the wireframe. A: From http://cone3d.gamedev.net/cgi-bin/index.pl?page=tutorials/ogladv/tut5 // Turn on wireframe mode glPolygonMode(GL_FRONT, GL_LINE); glPolygonMode(GL_BACK, GL_LINE); // Draw the box DrawBox(); // Turn off wireframe mode glPolygonMode(GL_FRONT, GL_FILL); glPolygonMode(GL_BACK, GL_FILL); A: glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); to switch on, glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); to go back to normal. Note that things like texture-mapping and lighting will still be applied to the wireframe lines if they're enabled, which can look weird. A: Assuming a forward-compatible context in OpenGL 3 and up, you can either use glPolygonMode as mentioned before, but note that lines with thickness more than 1px are now deprecated. So while you can draw triangles as wire-frame, they need to be very thin. In OpenGL ES, you can use GL_LINES with the same limitation. In OpenGL it is possible to use geometry shaders to take incoming triangles, disassemble them and send them for rasterization as quads (pairs of triangles really) emulating thick lines. Pretty simple, really, except that geometry shaders are notorious for poor performance scaling. What you can do instead, and what will also work in OpenGL ES is to employ fragment shader. Think of applying a texture of wire-frame triangle to the triangle. Except that no texture is needed, it can be generated procedurally. But enough talk, let's code. Fragment shader: in vec3 v_barycentric; // barycentric coordinate inside the triangle uniform float f_thickness; // thickness of the rendered lines void main() { float f_closest_edge = min(v_barycentric.x, min(v_barycentric.y, v_barycentric.z)); // see to which edge this pixel is the closest float f_width = fwidth(f_closest_edge); // calculate derivative (divide f_thickness by this to have the line width constant in screen-space) float f_alpha = smoothstep(f_thickness, f_thickness + f_width, f_closest_edge); // calculate alpha gl_FragColor = vec4(vec3(.0), f_alpha); } And vertex shader: in vec4 v_pos; // position of the vertices in vec3 v_bc; // barycentric coordinate inside the triangle out vec3 v_barycentric; // barycentric coordinate inside the triangle uniform mat4 t_mvp; // modeview-projection matrix void main() { gl_Position = t_mvp * v_pos; v_barycentric = v_bc; // just pass it on } Here, the barycentric coordinates are simply (1, 0, 0), (0, 1, 0) and (0, 0, 1) for the three triangle vertices (the order does not really matter, which makes packing into triangle strips potentially easier). The obvious disadvantage of this approach is that it will eat some texture coordinates and you need to modify your vertex array. Could be solved with a very simple geometry shader but I'd still suspect it will be slower than just feeding the GPU with more data. A: The easiest way is to draw the primitives as GL_LINE_STRIP. glBegin(GL_LINE_STRIP); /* Draw vertices here */ glEnd(); A: You can use glut libraries like this: * *for a sphere: glutWireSphere(radius,20,20); *for a Cylinder: GLUquadric *quadratic = gluNewQuadric(); gluQuadricDrawStyle(quadratic,GLU_LINE); gluCylinder(quadratic,1,1,1,12,1); *for a Cube: glutWireCube(1.5); A: Use this function: void glPolygonMode(GLenum face, GLenum mode); face: Specifies the polygon faces that mode applies to. Can be GL_FRONT for the front side of the polygon, GL_BACK for the back and GL_FRONT_AND_BACK for both. mode: Three modes are defined. * *GL_POINT: Polygon vertices that are marked as the start of a boundary edge are drawn as points. *GL_LINE: Boundary edges of the polygon are drawn as line segments. (your target) *GL_FILL: The interior of the polygon is filled. P.S: glPolygonMode controls the interpretation of polygons for rasterization in the graphics pipeline. For more information look at the OpenGL reference pages in khronos group. A: If it's OpenGL ES 2.0 you're dealing with, you can choose one of draw mode constants from GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES, to draw lines, GL_POINTS (if you need to draw only vertices), or GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, and GL_TRIANGLES to draw filled triangles as first argument to your glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid * indices) or glDrawArrays(GLenum mode, GLint first, GLsizei count) calls. A: A good and simple way of drawing anti-aliased lines on a non anti-aliased render target is to draw rectangles of 4 pixel width with an 1x4 texture, with alpha channel values of {0.,1.,1.,0.}, and use linear filtering with mip-mapping off. This will make the lines 2 pixels thick, but you can change the texture for different thicknesses. This is faster and easier than barymetric calculations.
{ "language": "en", "url": "https://stackoverflow.com/questions/137629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "243" }
Q: Encapsulating SQL in a named_scope I was wondering if there was a way to use "find_by_sql" within a named_scope. I'd like to treat custom sql as named_scope so I can chain it to my existing named_scopes. It would also be good for optimizing a sql snippet I use frequently. A: While you can put any SQL you like in the conditions of a named scope, if you then call find_by_sql then the 'scopes' get thrown away. Given: class Item # Anything you can put in an sql WHERE you can put here named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1' end This works (it just sticks the SQL string in there - if you have more than one they get joined with AND) Item.mine.find :all => SELECT * FROM items WHERE ('user_id' = 887 and IS_A_NINJA() = 1) However, this doesn't Items.mine.find_by_sql 'select * from items limit 1' => select * from items limit 1 So the answer is "No". If you think about what has to happen behind the scenes then this makes a lot of sense. In order to build the SQL rails has to know how it fits together. When you create normal queries, the select, joins, conditions, etc are all broken up into distinct pieces. Rails knows that it can add things to the conditions without affecting everything else (which is how with_scope and named_scope work). With find_by_sql however, you just give rails a big string. It doesn't know what goes where, so it's not safe for it to go in and add the things it would need to add for the scopes to work. A: This doesn't address exactly what you asked about, but you might investigate 'contruct_finder_sql'. It lets you can get the SQL of a named scope. named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1' named_scope :additional { :condtions => mine.send(:construct_finder_sql,{}) + " additional = 'foo'" } A: sure why not :named_scope :conditions => [ your sql ]
{ "language": "en", "url": "https://stackoverflow.com/questions/137630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do you pipe an inputstream to a zipped file as it's read in with Java? I'm wanting to execute a program and as it runs read in it's output and pipe out the output into a zipped file. The output of the program can be quite large so the idea is to not hold too much in memory - just to send it to the zip as I get it. A: ZipOutputStream targetStream = new ZipOutputStream(fileToSaveTo); ZipEntry entry = new ZipEntry(nameOfFileInZipFile); targetStream.putNextEntry(entry); byte[] dataBlock = new byte[1024]; int count = inputStream.read(dataBlock, 0, 1024); while (count != -1) { targetStream.write(dataBlock, 0, count); count = inputStream.read(dataBlock, 0, 1024); } In otherwords: * *You create a ZipOutputStream, giving it the file you want to write to. *You create a ZipEntry, which constitutes a file within that zip file. i.e. When you open myFile.zip, and there are 3 files in there, each file is a ZipEntry. *You put that ZipEntry into your ZipOutputStream *Create a byte buffer to read your data into. *Read from your inputStream into your byte buffer, and remember the count. *While the count is not -1, write that byte byffer to your zipStream. *Read the next line. Close out your streams when you are done. Wrap it in a method as you see fit.
{ "language": "en", "url": "https://stackoverflow.com/questions/137645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: IoC Containers - Which is best? (.Net) I'd like to get a feel for what people are using for IoC containers. I've read some good things about Castle Windsor, but I know a lot of people use StructureMap, Unity, Ninject, etc. What are some of the differences amongst those mentioned (and any I neglected). Strengths? Weaknesses? Better fit (like StructureMap is great for ABC but not so good for XYZ)? A: I like much Ninject... is simple, easy to use, it has such kind of fluid notation to declare bindings between classes and interfaces and supports contextual binding. Awesome. A: "Best" will always be subjective. That said, I favor Castle Windsor because its XML is simpler. I've only tried Windsor and Spring.NET, by the way, so I couldn't say much about the others. A: I like StructureMap. The latest version allows you to declare inline too without having to resort to XML configuration files.
{ "language": "en", "url": "https://stackoverflow.com/questions/137647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Free install wizard software Is there something like InstallShield that I can use for free? A: Inno Setup has worked very well as the Zeus installer for many years. A: I googled for "free installer" and found Advanced Installer, which I recall that I have used successfully in the past. A: I have been using Inno Setup for several years now. It's mature enough that it has a lot of plug-ins. I've found that the forums/newsgroups are very good at answering all the questions I've had so far. A: +1 for Inno. I was not a fan of NSIS/Nullsoft. EDIT the reason I did not like NSIS was the hoops I had to jump trough just to get the version information in the installer title/script. Basically you have to preprocess the scripts or run the install generator twice. Maybe they fixed it, maybe not. But what a hassle. I also found that the versions of the plugins and the versions of the main component were brittle. For example, things didn't work well when mixed and matched/upgraded. We had to keep a specific version of NSIS and the plugins we used in a repository to ensure we had them. A: NullSoft NSIS http://nsis.sourceforge.net/Main_Page A: WiX * *Very powerful and flexible. *Can produce MSI packages (Microsoft deployment format of choice) *Almost no documentation *Very steep learning curve. *XML-based. *Recommended for very complex installators. Inno Setup * *Cannot produce MSI packages. *Its scripting part looks like INI files structure. *Uses Pascal Script based language for extra flexibility. NSIS * *Cannot produce MSI packages. *Fully scripted, very powerful but at cost of high learning curve. *Recommened if WiX is too much and Inno Setup not enough. AdvancedInstaller * *Basic version is free. *Can produce MSI packages. *Very good user-interface, almost no learning curve to get things done. *XML-based (but schema is not very user-friendly, doesn't really matter as you would use GUI editor anyway) *The best option if you have only basic installer requirements and don't have time to learn something new. IzPack * *Cross-platform *Maven integration *Customizable actions *Well documented *Opensource A: WiX (Windows Installer XML) is free. A: Nullsoft Installer is the way to go. It has a bit of a steep learning curve but once you've worked out the scripting you'll have a decent installer in no time. Check out the Eclipse plugin too, it is a great addition. A: I would consider dotNetInstaller as well. It's pretty easy to setup installation with prerequisites, has a nice wizard and an editor that let manage the xml scripting from a form. A: I was looking for a similar solution and found the new kid on the block to be InstallJammer. Open source, extremely friendly and powerful-looking (I say looking because I never actually finished using it on a project), able to produce installers for multiple platforms. Actions in particular seemed very easy to set up. If it were to live up to it's goals, it would easily give the other install solutions a run for their money. A: There's the open source Nullsoft Installer which began with WinAmp, if I'm not mistaken. For .NET development you may want to take a look at WiX, which Microsoft also open sourced. IT's good for those with continuous integration setups. A: NSIS (nullsoft scriptable installer system) will do the job. It's open source. http://nsis.sourceforge.net/Main_Page A: The Nullsoft installer is free, powerful and very, very good. A: The nullsoft scriptable install system is an open source solution that provides a very powerful and professional install system. A: We use MakeMSI here to construct Windows installers. Very steep learning curve, but it's guaranteed to work on any Windows system. We've had problems with Nullsoft installers in the past, as silent, automated installs (the kind done all the time in managed environments) aren't supported by default.
{ "language": "en", "url": "https://stackoverflow.com/questions/137657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "66" }
Q: Persistence of std::map in C++ Do you know any easy or simple way to make a map object (from the STL library) persistent (i.e. write it to a file) so that you can recover its state later when the program in run later ?? Thanks for your help A: The answer is serialization. Specifics depend on your needs and your environment. For starters, check out Boost Serialization library: http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/index.html A: I believe the Boost Serialization library is capable of serializing std::map, but the standard library itself provides no means. Serialization is a great library with a lot of features and is easy to use and to extend to your own types. A: If you want to do it manually, the same way you'd persist any other container structure, write out the individual parts to disk: outputFile.Write(thisMap.size()); for (map<...>::const_iterator i = thisMap.begin(); i != thisMap.end(); ++iMap) { outputFile.Write(i->first); outputFile.Write(i->second); } and then read them back in: size_t mapSize = inputFile.Read(); for (size_t i = 0; i < mapSize; ++i) { keyType key = inputFile.Read(); valueType value = inputFile.Read(); thisMap[key] = value; } Obviously, you'll need to make things work based on your map type and file i/o library. Otherwise try boost serialization, or google's new serialization library.
{ "language": "en", "url": "https://stackoverflow.com/questions/137659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Where does Console.WriteLine go in ASP.NET? In a J2EE application (like one running in WebSphere), when I use System.out.println(), my text goes to standard out, which is mapped to a file by the WebSphere admin console. In an ASP.NET application (like one running in IIS), where does the output of Console.WriteLine() go? The IIS process must have a stdin, stdout and stderr; but is stdout mapped to the Windows version of /dev/null or am I missing a key concept here? I'm not asking if I should log there (I use log4net), but where does the output go? My best info came from this discussion where they say Console.SetOut() can change the TextWriter, but it still didn't answer the question on what the initial value of the Console is, or how to set it in config/outside of runtime code. A: If you use System.Diagnostics.Debug.WriteLine(...) instead of Console.WriteLine(), then you can see the results in the Output window of Visual Studio. A: There simply is no console listening by default. Running in debug mode there is a console attached, but in a production environment it is as you suspected, the message just doesn't go anywhere because nothing is listening. A: Unless you are in a strict console application, I wouldn't use it, because you can't really see it. I would use Trace.WriteLine() for debugging-type information that can be turned on and off in production. A: I've found this question by trying to change the Log output of the DataContext to the output window. So to anyone else trying to do the same, what I've done was create this: class DebugTextWriter : System.IO.TextWriter { public override void Write(char[] buffer, int index, int count) { System.Diagnostics.Debug.Write(new String(buffer, index, count)); } public override void Write(string value) { System.Diagnostics.Debug.Write(value); } public override Encoding Encoding { get { return System.Text.Encoding.Default; } } } Annd after that: dc.Log = new DebugTextWriter() and I can see all the queries in the output window (dc is the DataContext). Have a look at this for more info: http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers A: The TraceContext object in ASP.NET writes to the DefaultTraceListener which outputs to the host process’ standard output. Rather than using Console.Write(), if you use Trace.Write, output will go to the standard output of the process. You could use the System.Diagnostics.Process object to get the ASP.NET process for your site and monitor standard output using the OutputDataRecieved event. A: Try to attach kinda 'backend debugger' to log your msg or data to the console or output window the way we can do in node console. System.Diagnostics.Debug.WriteLine("Message" + variable) instead of Console.WriteLine() this way you can see the results in Output window aka Console of Visual Studio. A: If you look at the Console class in .NET Reflector, you'll find that if a process doesn't have an associated console, Console.Out and Console.Error are backed by Stream.Null (wrapped inside a TextWriter), which is a dummy implementation of Stream that basically ignores all input, and gives no output. So it is conceptually equivalent to /dev/null, but the implementation is more streamlined: there's no actual I/O taking place with the null device. Also, apart from calling SetOut, there is no way to configure the default. Update 2020-11-02: As this answer is still gathering votes in 2020, it should probably be noted that under ASP.NET Core, there usually is a console attached. You can configure the ASP.NET Core IIS Module to redirect all stdout and stderr output to a log file via the stdoutLogEnabled and stdoutLogFile settings: <system.webServer> <aspNetCore processPath="dotnet" arguments=".\MyApp.dll" hostingModel="inprocess" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" /> <system.webServer> A: If you are using IIS Express and launch it via a command prompt, it will leave the DOS window open, and you will see Console.Write statements there. So for example get a command window open and type: "C:\Program Files (x86)\IIS Express\iisexpress" /path:C:\Projects\Website1 /port:1655 This assumes you have a website directory at C:\Projects\Website1. It will start IIS Express and serve the pages in your website directory. It will leave the command windows open, and you will see output information there. Let's say you had a file there, default.aspx, with this code in it: <%@ Page Language="C#" %> <html> <body> <form id="form1" runat="server"> Hello! <% for(int i = 0; i < 6; i++) %> <% { Console.WriteLine(i.ToString()); }%> </form> </body> </html> Arrange your browser and command windows so you can see them both on the screen. Now type into your browser: http://localhost:1655/. You will see Hello! on the webpage, but in the command window you will see something like Request started: "GET" http://localhost:1655/ 0 1 2 3 4 5 Request ended: http://localhost:1655/default.aspx with HTTP status 200.0 I made it simple by having the code in a code block in the markup, but any console statements in your code-behind or anywhere else in your code will show here as well. A: System.Diagnostics.Debug.WriteLine(...); gets it into the Immediate Window in Visual Studio 2008. Go to menu Debug -> Windows -> Immediate: A: if you happened to use NLog in your ASP.net project, you can add a Debugger target: <targets> <target name="debugger" xsi:type="Debugger" layout="${date:format=HH\:mm\:ss}|${pad:padding=5:inner=${level:uppercase=true}}|${message} "/> and writes logs to this target for the levels you want: <rules> <logger name="*" minlevel="Trace" writeTo="debugger" /> now you have console output just like Jetty in "Output" window of VS, and make sure you are running in Debug Mode(F5). A: This is confusing for everyone when it comes IISExpress. There is nothing to read console messages. So for example, in the ASPCORE MVC apps it configures using appsettings.json which does nothing if you are using IISExpress. For right now you can just add loggerFactory.AddDebug(LogLevel.Debug); in your Configure section and it will at least show you your logs in the Debug Output window. Good news CORE 2.0 this will all be changing: https://github.com/aspnet/Announcements/issues/255 A: Mac, In Debug mode there is a tab for the Output. A: Using console.Writeline did not work for me. What did help was putting a breakpoint and then running the test on debug. When it reaches the breakpoint you can observe what is returned. A: In an ASP.NET application, I think it goes to the Output or Console window which is visible during debugging.
{ "language": "en", "url": "https://stackoverflow.com/questions/137660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "369" }
Q: How do you do polymorphism in Ruby? In C#, I can do this: class Program { static void Main(string[] args) { List<Animal> animals = new List<Animal>(); animals.Add(new Dog()); animals.Add(new Cat()); foreach (Animal a in animals) { Console.WriteLine(a.MakeNoise()); a.Sleep(); } } } public class Animal { public virtual string MakeNoise() { return String.Empty; } public void Sleep() { Console.Writeline(this.GetType().ToString() + " is sleeping."); } } public class Dog : Animal { public override string MakeNoise() { return "Woof!"; } } public class Cat : Animal { public override string MakeNoise() { return "Meow!"; } } Obviously, the output is (Slightly paraphrased): * *Woof *Dog is Sleeping *Meow *Cat is Sleeping Since C# is often mocked for its verbose type syntax, how do you handle polymorphism/virtual methods in a duck typed language such as Ruby? A: All the answers so far look pretty good to me. I thought I'd just mention that the whole inheritance thing is not entirely necessary. Excluding the "sleep" behaviour for a moment, we can achieve the whole desired outcome using duck-typing and omitting the need to create an Animal base class at all. Googling for "duck-typing" should yield any number of explanations, so for here let's just say "if it walks like a duck and quacks like a duck..." The "sleep" behaviour could be provided by using a mixin module, like Array, Hash and other Ruby built-in classes inclue Enumerable. I'm not suggesting it's necessarily better, just a different and perhaps more idiomatically Ruby way of doing it. module Animal def sleep puts self.class.name + " sleeps" end end class Dog include Animal def make_noise puts "Woof" end end class Cat include Animal def make_noise puts "Meow" end end You know the rest... A: Building on the previous answer, is this how you might do it? Second cut after clarification: class Animal def MakeNoise raise NotImplementedError # I don't remember the exact error class end def Sleep puts self.class.to_s + " is sleeping." end end class Dog < Animal def MakeNoise return "Woof!" end end class Cat < Animal def MakeNoise return "Meow!" end end animals = [Dog.new, Cat.new] animals.each {|a| puts a.MakeNoise a.Sleep } (I'll leave this as is, but "self.class.name" wins over ".to_s") A: edit: added more code for your updated question disclaimer: I haven't used Ruby in a year or so, and don't have it installed on this machine, so the syntax might be entirely wrong. But the concepts are correct. The exact same way, with classes and overridden methods: class Animal def MakeNoise return "" end def Sleep print self.class.name + " is sleeping.\n" end end class Dog < Animal def MakeNoise return "Woof!" end end class Cat < Animal def MakeNoise return "Meow!" end end animals = [Dog.new, Cat.new] animals.each {|a| print a.MakeNoise + "\n" a.Sleep } A: Using idiomatic Ruby class Animal def sleep puts "#{self.class} is sleeping" end end class Dog < Animal def make_noise "Woof!" end end class Cat < Animal def make_noise "Meow!" end end [Dog, Cat].each do |clazz| animal = clazz.new puts animal.make_noise animal.sleep end A: The principle of duck typing is just that the object has to respond to the called methods. So something like that may do the trick too : module Sleeping def sleep; puts "#{self} sleeps" end dog = "Dog" dog.extend Sleeping class << dog def make_noise; puts "Woof!" end end class Cat include Sleeping def to_s; "Cat" end def make_noise; puts "Meow!" end end [dog, Cat.new].each do |a| a.sleep a.make_noise end A: A little variant of manveru's solution which dynamic create different kind of object based in an array of Class types. Not really different, just a little more clear. Species = [Dog, Cat] Species.each do |specie| animal = specie.new # this will create a different specie on each call of new print animal.MakeNoise + "\n" animal.Sleep end A: This is how I would write it: class Animal def make_noise; '' end def sleep; puts "#{self.class.name} is sleeping." end end class Dog < Animal; def make_noise; 'Woof!' end end class Cat < Animal; def make_noise; 'Meow!' end end [Dog.new, Cat.new].each do |animal| puts animal.make_noise animal.sleep end It's not really different from the other solutions, but this is the style that I would prefer. That's 12 lines vs. the 41 lines (actually, you can shave off 3 lines by using a collection initializer) from the original C# example. Not bad! A: There's a method becomes which implements a polymorphism (by coping all instance variables from given class to new one) class Animal attr_reader :name def initialize(name = nil) @name = name end def make_noise '' end def becomes(klass) became = klass.new became.instance_variables.each do |instance_variable| value = self.instance_variable_get(instance_variable) became.instance_variable_set(instance_variable, value) end became end end class Dog < Animal def make_noise 'Woof' end end class Cat < Animal def make_noise 'Meow' end end animals = [Dog.new('Spot'), Cat.new('Tom')] animals.each do |animal| new_animal = animal.becomes(Cat) puts "#{animal.class} with name #{animal.name} becomes #{new_animal.class}" puts "and makes a noise: #{new_animal.make_noise}" puts '----' end and result is: Dog with name Spot becomes Cat and makes a noise: Meow ---- Cat with name Tom becomes Cat and makes a noise: Meow ---- * *A polymorphism could be useful to avoid if statement (antiifcampaign.com) *If you use RubyOnRails becomes method is already implemented: becomes *Quicktip: if you mix polymorphism with STI it brings you the most efficient combo to refactor your code I wish it helped you
{ "language": "en", "url": "https://stackoverflow.com/questions/137661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Apache Redirect only when entering a password I setup phpMyID on one of my machines, and I'm trying to get apache to redirect to HTTPS only when a password is being submitted. I am doing this as my original setup of redirecting all openid traffic didn't work stackoverflow doesn't like my self signed certificate. This is the new rule I've written, but its not working: RewriteRule http://%{SERVER_NAME}/openid/index.php(\?.+)$ https://%{SERVER_NAME}/openid/index.php$1 A: You need to use a Cond to test for both port (http or httpd) and query string: RewriteCond %{SERVER_PORT} 80 RewriteCond %{QUERY_STRING} (.+) RewriteRule /openid/index.php https://%{SERVER_NAME}/openid/index.php?%1 if on .htaccess you must use instead RewriteCond %{SERVER_PORT} 80 RewriteCond %{QUERY_STRING} (.+) RewriteRule openid/index.php https://%{SERVER_NAME}/openid/index.php?%1 A: A better solution would be: RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^openid/index\.php$ https://%{SERVER_NAME}/openid/index.php Explaination: RewriteCond %{SERVER_PORT} 80 does also match ports that just include 80. The same applies to the pattern openid/index.php (where “.” also can be any character). And appending the query is not necessary since mod_rewrite automatically appends the originally requested query to the substitute unless the query of the substitute is given.
{ "language": "en", "url": "https://stackoverflow.com/questions/137679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# 3 new feature posts (and not about .Net 3.5 features) There are a lot of new features that came with the .Net Framework 3.5. Most of the posts and info on the subject list stuff about new 3.5 features and C# 3 changes at the same time. But C# 3 can be used without .Net 3.5. Does anyone know of a good post describing the changes to the language? (Besides the boring, explicit official specs at MSDN that is.) A: There's a "quick and dirty" list on my C# in Depth site (which is also slightly tongue in cheek): To respond somewhat to Charles Graham's post, I have an article about how applicable the language features are when targeting .NET 2.0: Just as a blatant plug, if you're interested in language rather than framework, C# in Depth is about as close to a "language only" book as I've seen. It's also divided into two parts (after the introduction): new features in C# 2, and new features in C# 3. A: Scott Guthrie has a good series of blog posts that describe a lot of the improvements. Scroll down to "Language Improvements and LINQ". Lambda Expressions Anonymous Types Automatic Properties and object/list initializers Extension Methods Query Syntax A: Update: I can certainly understand. Eric Lippert has some more indepth posts..Check them out. I liked the series of posts by scottgu on the new language features.. Some more info here as well http://www.danielmoth.com/Blog/2007/11/top-10-things-to-know-about-visual.html esp the section on language features. A: Check out Eric White's tutorial on functional programming in C# 3.0 A: That's one thing that I would concretely like to know myself. The one thing that I can tell you is that a lot of the new features in C# 3.0 will actually work in a purely 2.0 application if you do multi targeting in VS 2008. I know that extension methods are one such thing. A: here is a series of articles that helped me understand the new features quickly http://blah.winsmarts.com/2006/05/19/demystifying-c-30--part-4-lambda-expressions.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/137688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Does WebMethods ESB scale? I'm looking for people who have had experiences scaling WebMethods ESB to large traffic volumes (both size and number of messages). How has that gone? Were there any issues and how did you solve them? A: From the environments I've dealt with (from 4 to 1000 servers) it scales pretty well. It depends wildly on the type of information transport technology you are managing. Fastest is the proprietary webMethods Broker, which, on a well configured server, can easily handle millions of >100kb messages per day. If you use a JMS transport directly on the Broker (no transform/repush on the native broker format) the extra message handling steps slows it a little bit (but the new 7.1.2 version has improved greatly). Other types of transport (stateless web services and others) usually do not involve an ESB, but your logistics architecture may vary, so no clear answer there. Most of the time, cloning the components in cluster or non-cluster systems is enough (the process is mostly IO-bound, so you might get good results on virtualization [or para-virtual, container, systems]; sometimes you really need more metal. A: AFAIK, people get some nice numbers with webMethods (but they do not use webMethods clustering). The webMethods flows can scale, with the downside that they are not persisted through each stage. If you don't use processes, you should be ok with the scaling.
{ "language": "en", "url": "https://stackoverflow.com/questions/137699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do you use WaTiR? Is there a better unit testing tool than WaTiR for Ruby web testing? Or is the defacto standard? What unit testing tools do you use? A: We use it for all our web application testing, not just ruby based web applications. We did look into a number of products but felt that WaTiR was the best. Plus it is in Ruby so we can pat ourselves our backs and tell each other how cool we are for using Ruby. A: After taking a long look at waitr, my team decided on Selenium. Among the many reasons were: * *The one that Steven mentioned, Selenium has better browser and cross-platform support. We currently have machines running mac, linux, and windows with safari, firefox, and ie. *Selenium tests seemed to run faster than waitr, especially if you take advantage of selenium grid. *Selenium tests could be written in a wider variety of languages than just Ruby. *Selenium has an easy to use IDE. A: Used as web crawling tool. WaTiR is also great for testing as I have heard. Be aware that each browser has their own version of WaTir: WaTiR(IE), FireWaTir(Firefox) and SafariWatiR(Safari). A: I didn't feel that I could mark any 1 of these as an answer. From what I see from the responses, is that WaTiR is one of the best if you're sticking with Ruby as the testing language. I personally agree with Ryan Guest about Selenium due to the cross browser support and language-agnostic approach. On the other hand, it uses it's own language, so it's one more thing to learn. Scott Hanselman has a podcast titled Functional Testing Tools Roundup that sort of talks about this question. When it comes down to it, I think the answer is that WaTiR is a great testing tool if it fits your situation. A: I have been using Watir since 2007 but more as a scripting tool than an unit testing tool. As a manual tester, it is very useful for some repetitive tasks, but I never got around to actually use it "properly" (creating test cases to see what features are failing and whatnot). Also, I have showed Watir to some friends of mine who are programmers and they are using it to help them during development of systems written in Java, PHP and even ASP, so just because Watir is a Ruby project, it doesn't mean you should use it only with other Ruby projects :) A: I use Watir for Functional testing. For Unit testing, if at all possible a 'headless browser' solution such as webrat or capybara is prefered IMHO as they are far faster and don't complicate things by needing to invoke an instance of the browser etc. You want unit tests to be FAST, so they can run with every CI build. Then create an overnight build, and have it run your functional tests, that way if they take hours to run, it's no big deal. (and once you get a large suite of thousands of functional/acceptance/regression tests, it will take hours to run even with faster browser such as the new IE9, Firefox, or Chrome. I should also note that with the new Watir-Webdrive project you can get what amounts to the best of both worlds. The easy to code, very 'Rubyesque' Watir API, and the broad browser support (IE, FF, Chrome, Opera, Headless) of the selenium Webdriver back-end. A: Worth noting that the FireWatir project has been rolled into the Watir core and the codebases integrated as of the 1.6.2 release last week. A: We had a look at WaTiR a few years ago and decided against it for various reasons, mostly around ease of use compared to the likes of selenium (as in writing code vs visual tools). It's worth mentioning that the people who were doing the test-building where not developers let alone Ruby developers. This also wasn't for ruby apps, but as it's the web and the web serves HTML it shouldn't matter what it's built with.
{ "language": "en", "url": "https://stackoverflow.com/questions/137711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Spell-check in Aquamacs Emacs won't work: "Wrong endian order." This is aquamacs 1.5 on a macbook. Exact error when I try to spell-check: Error: The file "/Library/Application Support/cocoAspell/aspell6-en-6.0-0//en-common.rws" is not in the proper format. Wrong endian order. ADDED: I indeed had the wrong version of cocoAspell. But installing the right version didn't work until I actually wiped (or renamed) /Library/Application Support/cocoAspell and reinstalled from scratch. That's what had thrown me for a loop. Thanks for the quick answers! Stackoverflow rocks! A: I believe you have the wrong version of the coco interface to Aspell for your mac. Check this site and download the appropriate version (PowerPC/Intel): http://people.ict.usc.edu/~leuski/cocoaspell/ A: I'm not sure, but this page seems similar: http://www.emacswiki.org/cgi-bin/wiki/AquamacsFAQ (search for "format" on that page to find the relevant part) Have you been using fink to install an old version of aspell like in this posting?
{ "language": "en", "url": "https://stackoverflow.com/questions/137717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which distro of Linux is best suited for Java web apps? There are so many Linux distributions to choose from! What is the "best" linux flavor for a web hosting environment running primarily: Apache HTTP, Tomcat or JBoss, MySQL and Alfresco (not necessarily all in the same instance). Are there any significant differences in terms of ease of administration and configuration, performance and stability for such applications, etc.? What would you recommend? Thanks! Mike A: They all use similar tools to administer things like webmin, and sshd. What are you more familiar with. Red Hat based systems(fedora, mandriva) or Debian based systems(Ubuntu). This family divide will determine a few things. First rpm packaging vs deb packaging. You also want to look at the level of activity of the project. Mandriva and Ubuntu are two examples of active distributions. That try to keep up with current releases of software. Other than that most stuff performs with little difference. A: You also might want to consider OpenSolaris, as it is from the same company which developed Java in the first place and I've heard rumours, that it supports threading better than Linux does and in Java threads are quite important. Update: Since Oracle changed the distribution model of OpenSolaris to a more commercial one you might want to check out the open source fork OpenIndiana (thanks to sed for bringing this to my attention). Oracle seems to still be providing the non-open Solaris and does also own Java, so decide for yourself. A: No, not really. It is really more down to the packages you install than the distribution you run. For stability people always recommend Cent OS because it's the poor mans RHE (as in it's basically RHE but free-as-in-beer) A: It depends entirely on what tools (particularly commercial) you're using. Most Linux stuff is shipped for RHEL (Redhat Enterprise Linux) so you are usually best off using that. Centos is a free distribution based on RHEL (in fact it's almost identical) so a given vendor's stuff usually works the same there. It also depends on hardware support. If you're using (for example) Dell servers, they support RHEL, but probably not e.g. Ubuntu so you really want to use a distro which is supported by your hardware vendor or their tools may not work. It's not a case of "best" for hosting web applications, but for use in a commercial hosted environment. We use Centos so we can use RHEL stuff. A: I've generally been fine with plain old Debian (Ubuntu has its caveats that sometimes hit you at wrong times). Granted it requires a bit of configuration upfront but once there, its stable as anything. I generally don't use repositories unless they're very general stuff but rather compile things myself from the deb packages. It gives a bit more control over what you really want to do with your system and you can optimize to a certain extent. Currently, I'm running Tomcat 6 on Debian for some months without any big problems. However, I think the debian family is much more friendly to implement even things that you don't really have much idea on or if you want to implement something fast or if you're trying out something in the site. In an ideal world, I'd do testing in a different machine or chroot, but hey I'm just a lazy sysadmin at times :) A: I've been playing with a complete Sun stack and it seems to be working well so far. * *OpenSolaris *Glassfish *MySQL I deploy .war files developed in Groovy with Grails but there are more and more options for deploying PHP and Ruby solutions. If cost is important, Sun is getting very aggressive partnering with hosting companies to provide free hosting for one year. I haven't had many obstacles but sometimes I have to look up command syntax since I hadn't used Solaris before. A: You mentioned running Alfresco. You should look at the Supported Platforms page for the version you are planning on installing (even if you are installed Community Edition). Most people running Alfresco use either Ubuntu Server or CentOS/Red Hat Enterprise Linux. A: You mentioned Linux and Java. You did not mention other things like an Appserver, LDAP server, DB Server. With those things considered, you would be best off with Redhat, Fedora, CentOS and SUSE/OpenSUSE. Ubuntu will not hurt since they have a relationship with Sun but since JBoss has become part of REdhat, I would think that Redhat-based distros should be pretty good. I've used Redhat/Fedora and OpenSUSE to run banking production apps and they are pretty good. Dell offers good support for Redhat + JAVA + ORACLE.
{ "language": "en", "url": "https://stackoverflow.com/questions/137720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Free mulitplatform installer Expanding on Free install wizard software I am looking for a cross platform installer. We support something like 27 platform variations and most of the installers mentioned in the other question are windows only. We are looking for something portable, possibly java based but I suppose any scripting language would also work. Suggestions? Edit: In order of number of platforms under each OS: linux, solaris, windows, hpux, aix, zlinux, bsd, OSX, OS/360 (I don't care about this one). So about as much variation as you can get without VMS or mainframe. A lot of the linux platforms are similar varying only in version of libc. But we do support 32 and 64 bit on each processor on which the OS runs. As an example we support 4 solaris platforms: * *solaris sparc 32 *solaris sparc 64 *solaris x86 32 bit *solaris x86 64 bit A: IzPack ? A: I don't know of any free cross-platform ones, sorry. I do know that several commercial companies that I know swear by BitRock. There's quite a few Linux stacks built with it. A: If your project is opensource, you can use BitRock's Install Builder for free. And this page on the wxWidgets site lists alot of different platform installers, describing various issues with each. A: You should take a look at InstallJammer. Free, open source, and very easy to use while being powerful enough to make just about anything you need. Supports most platforms out-of-the-box. A: I also suggest http://packjacket.sourceforge.net/ A: Here's a list of some: Open Source Installer Generators in Java.
{ "language": "en", "url": "https://stackoverflow.com/questions/137723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do I upload a HTML form with a username, password, multiple file uploads and then process it with PHP? How to post a username, password and multiple binary files from a single html form and process it using php? I'm not allowed to use ajax. A: first off check out these pages on PHP.net * *file upload info *move_uploaded_file But to get you started here's a couple stub files. uploadForm.html <html> <body> <form action="processStuff.php" enctype="multipart/form-data" method="POST"> username: <input type="text" name="username" /> password: <input type="password" name="password" /> <p> <input type="file" name="uploadFile[]" /><br /> <input type="file" name="uploadFile[]" /><br /> <input type="file" name="uploadFile[]" /><br /> <!-- Add as many of these as you want --> </p> <p> <input type="submit" /> </p> </form> </body> </html> processStuff.php <pre> <?php echo '<h2>Username & password</h2>' echo "Username: {$_POST['username']}\nPassword: {$_POST['password']}"; echo '<hr />'; echo '<h2>Uploaded files</h2>' foreach($_FILES['uploadFile']['tmp_name'] as $i => $tempUploadPath) { if (empty($tempUploadPath)) { // this <input type="file" /> was "blank"... no file selected } else { // a file was uploaded echo '<strong>A file named "', $_FILES['uploadFile']['name'][$i], "\" was uploaded</strong>\n"; echo "\ttemporarily stored at: ", $tempUploadPath, "\n"; echo "\tmime type: ", $_FILES['uploadFile']['type'][$i], "\n"; echo "\tsize: ", $_FILES['uploadFile']['size'][$i], " bytes\n"; echo "\terror code", ((empty($_FILES['uploadFile']['size'][$i]) ? '<em>no errror</em>' : $_FILES['uploadFile']['size'][$i])), "\n\n"; // do something useful with the uploaded file // access it via $tempUploadPath and use move_uploaded_file() to move // it out of the temp path before you manipulate it in any way!!!!! // see http://us3.php.net/features.file-upload // and http://us3.php.net/manual/en/function.move-uploaded-file.php } } ?> </pre> The HTML file shows how to set the enctype of the <form> & the second form show you how to access the submitted username & password & finally how to loop thru every uploaded file. As noted you MUST move the file(s) ASAP. They're uploaded to a temp location and the system will delete them unless you deal with them. So move 'em somewhere first then do whatever you need w/ them. Hoep this helps Arin A: You should use the $_FILES superglobal and move_uploaded_file() function to see which files were uploaded successfully and move them to their final location in case they were. The $_POST superglobal will contain the submitted username and password.
{ "language": "en", "url": "https://stackoverflow.com/questions/137730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to use POP3 over SSL in C I would like to know and understand the steps involved in fetching mail from pop3 server using plain c language A: Steps: * *Connect to the server's port (usually 995) using OpenSSL *Verify the certificate *Send regular pop3 commands over the SSL socket you just opened. (LIST, RETR and so on) *Retrieve the responses *Close the socket Or use a library that does all of the above for you A: Use one of the thousands of libraries that already exist such as libspopc. A: Use a library such as tinymail, which uses the OpenSSL library.
{ "language": "en", "url": "https://stackoverflow.com/questions/137741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MDIParent Tiling children Is there any way to tile all of the form children of an mdi parent easily? I'm looking for most of the functionality that windows offers, tile cascade. Anyone know of an easy way? A: try these... // Tile all child forms horizontally. this.LayoutMdi( MdiLayout.TileHorizontal ); // Tile all child forms vertically. this.LayoutMdi( MdiLayout.TileVertical ); // Cascade all MDI child windows. this.LayoutMdi( MdiLayout.Cascade );
{ "language": "en", "url": "https://stackoverflow.com/questions/137743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Can i update a signed jar using an ANT Task? Hi I am trying to deploy an application using webstart. I have a requirement to update a jar which is signed before i actually deploy( basically to update the IP/Port info). I am trying to use ANT to update the jar. Is there are way to achive this? A: I can't speak specifically to ANT or to JAR files. But generally speaking, one of the purposes of signing is to prevent tampering with the code. Once the code has been modified, the signature is no longer valid and this is by design. You'd have to re-sign the JAR file after making the updates.
{ "language": "en", "url": "https://stackoverflow.com/questions/137745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best data structure in .NET for look-up by string key or numeric index? I'm looking for the most ideal data structure (for performance and ease of use) from which values can be retrieved by string key or index. Dictionary doesn't work because you can't really retrieve by index. Any ideas? A: You want the OrderedDictionary class. You will need to include the System.Collections.Specialized namespace: OrderedDictionary od = new OrderedDictionary(); od.Add("abc", 1); od.Add("def", 2); od.Add("ghi", 3); od.Add("jkl", 4); // Can access via index or key value: Console.WriteLine(od[1]); Console.WriteLine(od["def"]); A: There's System.Collections.ObjectModel.KeyedCollection< string,TItem>, which derives from Collection< TItem>. Retrieval is O(1). class IndexableDictionary<TItem> : KeyedCollection<string, TItem> { Dictionary<TItem, string> keys = new Dictionary<TItem, string>(); protected override string GetKeyForItem(TItem item) { return keys[item];} public void Add(string key, TItem item) { keys[item] = key; this.Add(item); } } A: One word of warning. The OrderedDictionary has really bad performance characteristics for most operations except insertion and lookup: Both removal and modification of a value may require a linear search of the whole list, resulting in runtime O(n). (For modification, this depends on whether access occurred by index or by key.) For most operations with reasonable amounts of data, this is completely inacceptable. Furthermore, the data structure stores elements both in a linear vector and in a hash table, resulting in some memory overhead. If retrieval by index doesn't happen too often, a SortedList or SortedDictionary will have much better performance characteristics (access by index can be achieved through the ElementAt extension method). If, on the other hand, access by index is the norm, then stop using dictionary data structures alltogether and simply store your values in a List<KeyValuePair<TKey, TValue>>. Although this means a linear search for access by key, all other operations are very cheap and overall performance is hard to beat in practice. /EDIT: Of course, the latter is also a dictionary data structure in the theoretical sense. You could even encapsulate it in a class implementing the appropriate interface. A: Hash based collections (Dictionary, Hashtable, HashSet) are out because you won't have an index, since you want an index, I'd use a nested generic: List<KeyValuePair<K,V>> Of course, you lose the O(1) Key lookup that you get with hashes. A: A Dictionary could work with linq. Although i dont know about possible performance issues. Dictionary.ElementAt(index); A: I recommend using SortedDictionary<string, TValue> or SortedList<string, TValue>. Both have O(log n) search performance. The differences are, as quoted from the MSDN library: SortedList<(Of <(TKey, TValue>)>) uses less memory than SortedDictionary<(Of <(TKey, TValue>)>). SortedDictionary<(Of <(TKey, TValue>)>) has faster insertion and removal operations for unsorted data: O(log n) as opposed to O(n) for SortedList<(Of <(TKey, TValue>)>). If the list is populated all at once from sorted data, SortedList<(Of <(TKey, TValue>)>) is faster than SortedDictionary<(Of <(TKey, TValue>)>). In my experience SortedDictionary is more adequate for most typical business scenarios, since the data is usually initially unsorted when using structures like this, and the memory overhead of SortedDictionary is seldom critical. But if performance is key for you, I suggest you implement both and do measurements. A: You are looking for something like the SortedList class (here's the generic version as well).
{ "language": "en", "url": "https://stackoverflow.com/questions/137753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How is a real-world simulation designed? I am fascinated by the performance of applications such as "Rollercoaster Tycoon" and "The Sims" and FPS games. I would like to know more about the basic application architecture. (Not so concerned with the UI - I assume MVC/MVP piriciples apply here. Nor am I concerned with the math and physics at this point.) My main question deals with the tens or hundreds of individual objects in the simulation (people, vehicles, items, etc.) that all move, make decisions, and raise & respond to events - seeming all a the same time, and how they are designed for such good performance. Q: Primarily, are these objects being processed in a giant loop, one at a time - or is each object processing in it's own thread? How many threads are practical in a simulation like this? (Ballpark figure of course, 10, 100, 1000) I'm not looking to write a game, I just want the design theory because I'm wondering if such design can apply to other applications where several decisions are being made seemingly at the same time. A: There are two basic ways of doing this kind of simulation Agent Based and System Dynamics. In and agent based simulation each entity in the game would be represented by an instance of a class with properties and behaviors, all the interactions between the entities would have to be explicitly defined and when you want these entities to interact a function gets called the properties of the interacting entities gets changed. System Dynamics is completely different, it only deals with sums and totals, there is no representation of a single entity in the system. The easiest example of that is the Predator and Prey model. Both of these have advantages and disadvantages, the System Dynamics approach scales better to large number of entitities while keeping runtime short. While there are multiple formulas that you have to calculate, the time to calculate is independent of the values in the formula. But there is no way to look at an individual entity in this approach. The Agent based approach lets you put entities in specific locations and lets you interact with specific entities in your simulation. FSMs and Celular automata are other ways in how to simulate systems in a game. E.g. in the agent based approach you might model the behavior of one agent with a FSM. Simcity used Celular automata to do some of the simulation work. In general you will probably not have one big huge model that does everything but multiple systems that do specific tasks, some of these will not need to be updated very often e.g. something that determines the weather, others might need constant updates. Even if you put them in separate threads you will want to pause or start them when you need them. You might want to split work over multiple frames, e.g. calculate only updates on a certain number of agents. A: The source code to the original Simcity has been open sourced as Micropolis. It might be an interesting study. A: Until very recently, the game's logic and management was in a single thread in a big finite state machine. Now, though, you tend to see the different pieces of the game (audio, graphics, physics, 'simulation' logic, etc) being split into their own FSMs in threads. Edit: Btw, threads are a very bad way of having things in a simulation happening at the 'same time' -- it leads to race conditions. It's common that when you want to have things going on at the 'same time', you simply figure out what needs to happen as you iterate over your data and store it separately, then apply it once all the data is processed. Rince, repeat. A: @Cody Brocious This CodeProject uses Linq to demonstrate this practice. (Linq to Life) A: In addition to the suggestions posted I would recommend browsing the simulation tag at sourceforge. There are a variety of simulation project at varying levels of complexity. Sourceforge Also I recommend the following book for a basic overview, While it is focused on physics it deals with issues of simulation. Physics for Game Developers
{ "language": "en", "url": "https://stackoverflow.com/questions/137755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: What does the "no version information available" error from linux dynamic linker mean? In our product we ship some linux binaries that dynamically link to system libraries like "libpam". On some customer systems we get the following error on stderr when the program runs: ./authpam: /lib/libpam.so.0: no version information available (required by authpam) The application runs fine and executes code from the dynamic library. So this is not a fatal error, it's really just a warning. I figure that this is error comes from the dynamic linker when the system installed library is missing something our executable expects. I don't know much about the internals of the dynamic linking process ... and googling the topic doesn't help much. :( Anyone know what causes this error? ... how I can diagnose the cause? ... and how we could change our executables to avoid this problem? Update: The customer upgraded to the latest version of debian "testing" and the same error occurred. So it's not an out of date libpam library. I guess I'd like to understand what the linker is complaining about? How can I investigate the underlying cause, etc? A: The "no version information available" means that the library version number is lower on the shared object. For example, if your major.minor.patch number is 7.15.5 on the machine where you build the binary, and the major.minor.patch number is 7.12.1 on the installation machine, ld will print the warning. You can fix this by compiling with a library (headers and shared objects) that matches the shared object version shipped with your target OS. E.g., if you are going to install to RedHat 3.4.6-9 you don't want to compile on Debian 4.1.1-21. This is one of the reasons that most distributions ship for specific linux distro numbers. Otherwise, you can statically link. However, you don't want to do this with something like PAM, so you want to actually install a development environment that matches your client's production environment (or at least install and link against the correct library versions.) Advice you get to rename the .so files (padding them with version numbers,) stems from a time when shared object libraries did not use versioned symbols. So don't expect that playing with the .so.n.n.n naming scheme is going to help (much - it might help if you system has been trashed.) You last option will be compiling with a library with a different minor version number, using a custom linking script: http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gnu-linker/scripts.html To do this, you'll need to write a custom script, and you'll need a custom installer that runs ld against your client's shared objects, using the custom script. This requires that your client have gcc or ld on their production system. A: Fwiw, I had this problem when running check_nrpe on a system that had the zenoss monitoring system installed. To add to the confusion, it worked fine as root user but not as zenoss user. I found out that the zenoss user had an LD_LIBRARY_PATH that caused it to use zenoss libraries, which issue these warnings. Ie: root@monitoring:$ echo $LD_LIBRARY_PATH su - zenoss zenoss@monitoring:/root$ echo $LD_LIBRARY_PATH /usr/local/zenoss/python/lib:/usr/local/zenoss/mysql/lib:/usr/local/zenoss/zenoss/lib:/usr/local/zenoss/common/lib:: zenoss@monitoring:/root$ /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq /usr/lib/nagios/plugins/check_nrpe: /usr/local/zenoss/common/lib/libcrypto.so.0.9.8: no version information available (required by /usr/lib/libssl.so.0.9.8) (...) zenoss@monitoring:/root$ LD_LIBRARY_PATH= /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq (...) So anyway, what I'm trying to say: check your variables like LD_LIBRARY_PATH, LD_PRELOAD etc as well. A: What this message from the glibc dynamic linker actually means is that the library mentioned (/lib/libpam.so.0 in your case) doesn't have the VERDEF ELF section while the binary (authpam in your case) has some version definitions in VERNEED section for this library (presumably, libpam.so.0). You can easily see it with readelf, just look at .gnu.version_d and .gnu.version_r sections (or lack thereof). So it's not a symbol version mismatch, because if the binary wanted to get some specific version via VERNEED and the library didn't provide it in its actual VERDEF, that would be a hard linker error and the binary wouldn't run at all (like this compared to this or that). It's that the binary wants some versions, but the library doesn't provide any information about its versions. What does it mean in practice? Usually, exactly what is seen in this example — nothing, things just work ignoring versioning. Could things break? Of course, yes, so the other answers are correct in the fact that one should use the same libraries at runtime as the ones the binary was linked to at build time. More information could be found in Ulrich Dreppers "ELF Symbol Versioning". A: How are you compiling your app? What compiler flags? In my experience, when targeting the vast realm of Linux systems out there, build your packages on the oldest version you are willing to support, and because more systems tend to be backwards compatible, your app will continue to work. Actually this is the whole reason for library versioning - ensuring backward compatibility. A: Have you seen this already? The cause seems to be a very old libpam on one of the sides, probably on that customer. Or the links for the version might be missing : http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html
{ "language": "en", "url": "https://stackoverflow.com/questions/137773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "103" }
Q: Should extension properties be added to C# 4.0? I've wanted this for fluent interfaces. See, for example this Channel9 discussion. Would probably require also adding indexed properties. What are your thoughts? Would the advantages outweigh the "language clutter"? A: It's about databinding, let's say I have an object for binding to my UI and I want to hide show it based on other properties of the object. I could add an extension property for IsVisible or Visibility and bind that property to the UI. You can't bind extension methods, but being able to add properties for databinding to existing types you can't extend could be very useful. A: In my book the #1 most substantial reason for extension properties is implementing fluent interface patterns around unowned code. I built a wrapper around the NHibernate session to make it more intitutive to work with so I can do logic similar to public bool IsInTransaction { get { return _session.Is().Not.Null && _session.Is().InTransaction; } } Which looks very stupid that Is must be a method as there is no way for me to insert the Is as a property unless I directly modify the source on the session object. A: I don't know why not. Properties are just getter/setter methods with differant syntax. A: Since properties are just syntactic sugar for methods, I don't see why C# should have extension methods without extension properties. A: I don't think extension properties would be nearly as useful. I find myself mostly using properties to encapsulate fields (classic get; set;) or to provide read only goodness (just a get on a private, readonly, contructor-set field). Since extensions can't access private members, I don't really see the point, especially for "set;". To do anything, "set;" would just have to call other methods anyway. Then you run into the issue of properties throwing exceptions. Since extensions are limited to using public properties and methods, I find it cleaner and easier to read code that uses a utility class. When it comes down to it, we are using extension methods to make LINQ look pretty. To keep developers from doing the wrong thing, I can deal with an extra () here and there in my LINQ and stick to just extension methods. A: I guess it would be great, as long as there's no or minimal performance penalty in using them. A: Seems like it could be easily misused. As others have mentioned, C# properties are just syntactic sugar for methods. However, implementing those as properties has certain connotations: accessing won't have side effects and modifying a property should be very inexpensive. The latter point is crucial as it seems like extension properties will almost always be more expensive than conventional properties. A: Would be a nice thing to have, but I see many people saying they want it for data binding which isn't possible since it's using reflection. A: Would definately add to the repertoire of tools at our disposal. Now as for my opinion, yes they should, but like anything, developers need to use it properly and when needed. Like most new features, a lot of dev's use them without fully understanding them and when/how/where/how best to use them. I know I get sucked into this sometimes too. But ya, sure, bring it on. I could see myself using it in certain scenarios A: I'm guessing indexed properties will be a mere stocking stuffer among a large bag of of significant enhancements we'll be seeing in 4.0. A: Developers should use properties to organize hierarchy of names and avoid name concatenation with camel casing or underscores. For example, instead of HttpUtility.UrlDecode they should extend string class to use something like "some str".decode.url Currently the only way to do it in C# is this: "some str".decode().url A: Yes, please. And also add indexed properties and STATIC extension stuff, because I SERIOUSLY want that for System.Console (this is not meant as a joke!). A: No, a property is just a way to hide what has really been generated for the code. If you look at the reflected code or the IL you can determine what you're really getting and it is the following: public string MyProperty { get; set; } becomes public string get_MyProperty(){ return <some generated variable>; } public string set_MyProperty(string value) { <some generated variable> = value; } It's just 2 methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/137775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Expand a random range from 1–5 to 1–7 Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7. A: Why not do it simple? int random7() { return random5() + (random5() % 3); } The chances of getting 1 and 7 in this solution is lower due to the modulo, however, if you just want a quick and readable solution, this is the way to go. A: Assuming that rand(n) here means "random integer in a uniform distribution from 0 to n-1", here's a code sample using Python's randint, which has that effect. It uses only randint(5), and constants, to produce the effect of randint(7). A little silly, actually from random import randint sum = 7 while sum >= 7: first = randint(0,5) toadd = 9999 while toadd>1: toadd = randint(0,5) if toadd: sum = first+5 else: sum = first assert 7>sum>=0 print sum A: The premise behind Adam Rosenfield's correct answer is: * *x = 5^n (in his case: n=2) *manipulate n rand5 calls to get a number y within range [1, x] *z = ((int)(x / 7)) * 7 *if y > z, try again. else return y % 7 + 1 When n equals 2, you have 4 throw-away possibilities: y = {22, 23, 24, 25}. If you use n equals 6, you only have 1 throw-away: y = {15625}. 5^6 = 15625 7 * 2232 = 15624 You call rand5 more times. However, you have a much lower chance of getting a throw-away value (or an infinite loop). If there is a way to get no possible throw-away value for y, I haven't found it yet. A: Here's my answer: static struct rand_buffer { unsigned v, count; } buf2, buf3; void push (struct rand_buffer *buf, unsigned n, unsigned v) { buf->v = buf->v * n + v; ++buf->count; } #define PUSH(n, v) push (&buf##n, n, v) int rand16 (void) { int v = buf2.v & 0xf; buf2.v >>= 4; buf2.count -= 4; return v; } int rand9 (void) { int v = buf3.v % 9; buf3.v /= 9; buf3.count -= 2; return v; } int rand7 (void) { if (buf3.count >= 2) { int v = rand9 (); if (v < 7) return v % 7 + 1; PUSH (2, v - 7); } for (;;) { if (buf2.count >= 4) { int v = rand16 (); if (v < 14) { PUSH (2, v / 7); return v % 7 + 1; } PUSH (2, v - 14); } // Get a number between 0 & 25 int v = 5 * (rand5 () - 1) + rand5 () - 1; if (v < 21) { PUSH (3, v / 7); return v % 7 + 1; } v -= 21; PUSH (2, v & 1); PUSH (2, v >> 1); } } It's a little more complicated than others, but I believe it minimises the calls to rand5. As with other solutions, there's a small probability that it could loop for a long time. A: Simple and efficient: int rand7 ( void ) { return 4; // this number has been calculated using // rand5() and is in the range 1..7 } (Inspired by What's your favorite "programmer" cartoon?). A: This is equivalent to Adam Rosenfield's solution, but may be a bit more clear for some readers. It assumes rand5() is a function that returns a statistically random integer in the range 1 through 5 inclusive. int rand7() { int vals[5][5] = { { 1, 2, 3, 4, 5 }, { 6, 7, 1, 2, 3 }, { 4, 5, 6, 7, 1 }, { 2, 3, 4, 5, 6 }, { 7, 0, 0, 0, 0 } }; int result = 0; while (result == 0) { int i = rand5(); int j = rand5(); result = vals[i-1][j-1]; } return result; } How does it work? Think of it like this: imagine printing out this double-dimension array on paper, tacking it up to a dart board and randomly throwing darts at it. If you hit a non-zero value, it's a statistically random value between 1 and 7, since there are an equal number of non-zero values to choose from. If you hit a zero, just keep throwing the dart until you hit a non-zero. That's what this code is doing: the i and j indexes randomly select a location on the dart board, and if we don't get a good result, we keep throwing darts. Like Adam said, this can run forever in the worst case, but statistically the worst case never happens. :) A: As long as there aren't seven possibilities left to choose from, draw another random number, which multiplies the number of possibilities by five. In Perl: $num = 0; $possibilities = 1; sub rand7 { while( $possibilities < 7 ) { $num = $num * 5 + int(rand(5)); $possibilities *= 5; } my $result = $num % 7; $num = int( $num / 7 ); $possibilities /= 7; return $result; } A: I don't like ranges starting from 1, so I'll start from 0 :-) unsigned rand5() { return rand() % 5; } unsigned rand7() { int r; do { r = rand5(); r = r * 5 + rand5(); r = r * 5 + rand5(); r = r * 5 + rand5(); r = r * 5 + rand5(); r = r * 5 + rand5(); } while (r > 15623); return r / 2232; } A: I know it has been answered, but is this seems to work ok, but I can not tell you if it has a bias. My 'testing' suggests it is, at least, reasonable. Perhaps Adam Rosenfield would be kind enough to comment? My (naive?) idea is this: Accumulate rand5's until there is enough random bits to make a rand7. This takes at most 2 rand5's. To get the rand7 number I use the accumulated value mod 7. To avoid the accumulator overflowing, and since the accumulator is mod 7 then I take the mod 7 of the accumulator: (5a + rand5) % 7 = (k*7 + (5a%7) + rand5) % 7 = ( (5a%7) + rand5) % 7 The rand7() function follows: (I let the range of rand5 be 0-4 and rand7 is likewise 0-6.) int rand7(){ static int a=0; static int e=0; int r; a = a * 5 + rand5(); e = e + 5; // added 5/7ths of a rand7 number if ( e<7 ){ a = a * 5 + rand5(); e = e + 5; // another 5/7ths } r = a % 7; e = e - 7; // removed a rand7 number a = a % 7; return r; } Edit: Added results for 100 million trials. 'Real' rand functions mod 5 or 7 rand5 : avg=1.999802 0:20003944 1:19999889 2:20003690 3:19996938 4:19995539 rand7 : avg=3.000111 0:14282851 1:14282879 2:14284554 3:14288546 4:14292388 5:14288736 6:14280046 My rand7 Average looks ok and number distributions look ok too. randt : avg=3.000080 0:14288793 1:14280135 2:14287848 3:14285277 4:14286341 5:14278663 6:14292943 A: There are elegant algorithms cited above, but here's one way to approach it, although it might be roundabout. I am assuming values generated from 0. R2 = random number generator giving values less than 2 (sample space = {0, 1}) R8 = random number generator giving values less than 8 (sample space = {0, 1, 2, 3, 4, 5, 6, 7}) In order to generate R8 from R2, you will run R2 thrice, and use the combined result of all 3 runs as a binary number with 3 digits. Here are the range of values when R2 is ran thrice: 0 0 0 --> 0 . . 1 1 1 --> 7 Now to generate R7 from R8, we simply run R7 again if it returns 7: int R7() { do { x = R8(); } while (x > 6) return x; } The roundabout solution is to generate R2 from R5 (just like we generated R7 from R8), then R8 from R2 and then R7 from R8. A: There you go, uniform distribution and zero rand5 calls. def rand7: seed += 1 if seed >= 7: seed = 0 yield seed Need to set seed beforehand. A: Here's a solution that fits entirely within integers and is within about 4% of optimal (i.e. uses 1.26 random numbers in {0..4} for every one in {0..6}). The code's in Scala, but the math should be reasonably clear in any language: you take advantage of the fact that 7^9 + 7^8 is very close to 5^11. So you pick an 11 digit number in base 5, and then interpret it as a 9 digit number in base 7 if it's in range (giving 9 base 7 numbers), or as an 8 digit number if it's over the 9 digit number, etc.: abstract class RNG { def apply(): Int } class Random5 extends RNG { val rng = new scala.util.Random var count = 0 def apply() = { count += 1 ; rng.nextInt(5) } } class FiveSevener(five: RNG) { val sevens = new Array[Int](9) var nsevens = 0 val to9 = 40353607; val to8 = 5764801; val to7 = 823543; def loadSevens(value: Int, count: Int) { nsevens = 0; var remaining = value; while (nsevens < count) { sevens(nsevens) = remaining % 7 remaining /= 7 nsevens += 1 } } def loadSevens { var fivepow11 = 0; var i=0 while (i<11) { i+=1 ; fivepow11 = five() + fivepow11*5 } if (fivepow11 < to9) { loadSevens(fivepow11 , 9) ; return } fivepow11 -= to9 if (fivepow11 < to8) { loadSevens(fivepow11 , 8) ; return } fivepow11 -= to8 if (fivepow11 < 3*to7) loadSevens(fivepow11 % to7 , 7) else loadSevens } def apply() = { if (nsevens==0) loadSevens nsevens -= 1 sevens(nsevens) } } If you paste a test into the interpreter (REPL actually), you get: scala> val five = new Random5 five: Random5 = Random5@e9c592 scala> val seven = new FiveSevener(five) seven: FiveSevener = FiveSevener@143c423 scala> val counts = new Array[Int](7) counts: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0) scala> var i=0 ; while (i < 100000000) { counts( seven() ) += 1 ; i += 1 } i: Int = 100000000 scala> counts res0: Array[Int] = Array(14280662, 14293012, 14281286, 14284836, 14287188, 14289332, 14283684) scala> five.count res1: Int = 125902876 The distribution is nice and flat (within about 10k of 1/7 of 10^8 in each bin, as expected from an approximately-Gaussian distribution). A: (I have stolen Adam Rosenfeld's answer and made it run about 7% faster.) Assume that rand5() returns one of {0,1,2,3,4} with equal distribution and the goal is return {0,1,2,3,4,5,6} with equal distribution. int rand7() { i = 5 * rand5() + rand5(); max = 25; //i is uniform among {0 ... max-1} while(i < max%7) { //i is uniform among {0 ... (max%7 - 1)} i *= 5; i += rand5(); //i is uniform {0 ... (((max%7)*5) - 1)} max %= 7; max *= 5; //once again, i is uniform among {0 ... max-1} } return(i%7); } We're keeping track of the largest value that the loop can make in the variable max. If the reult so far is between max%7 and max-1 then the result will be uniformly distrubuted in that range. If not, we use the remainder, which is random between 0 and max%7-1, and another call to rand() to make a new number and a new max. Then we start again. Edit: Expect number of times to call rand5() is x in this equation: x = 2 * 21/25 + 3 * 4/25 * 14/20 + 4 * 4/25 * 6/20 * 28/30 + 5 * 4/25 * 6/20 * 2/30 * 7/10 + 6 * 4/25 * 6/20 * 2/30 * 3/10 * 14/15 + (6+x) * 4/25 * 6/20 * 2/30 * 3/10 * 1/15 x = about 2.21 calls to rand5() A: There is no (exactly correct) solution which will run in a constant amount of time, since 1/7 is an infinite decimal in base 5. One simple solution would be to use rejection sampling, e.g.: int i; do { i = 5 * (rand5() - 1) + rand5(); // i is now uniformly random between 1 and 25 } while(i > 21); // i is now uniformly random between 1 and 21 return i % 7 + 1; // result is now uniformly random between 1 and 7 This has an expected runtime of 25/21 = 1.19 iterations of the loop, but there is an infinitesimally small probability of looping forever. A: Algorithm: 7 can be represented in a sequence of 3 bits Use rand(5) to randomly fill each bit with 0 or 1. For e.g: call rand(5) and if the result is 1 or 2, fill the bit with 0 if the result is 4 or 5, fill the bit with 1 if the result is 3 , then ignore and do it again (rejection) This way we can fill 3 bits randomly with 0/1 and thus get a number from 1-7. EDIT: This seems like the simplest and most efficient answer, so here's some code for it: public static int random_7() { int returnValue = 0; while (returnValue == 0) { for (int i = 1; i <= 3; i++) { returnValue = (returnValue << 1) + random_5_output_2(); } } return returnValue; } private static int random_5_output_2() { while (true) { int flip = random_5(); if (flip < 3) { return 0; } else if (flip > 3) { return 1; } } } A: By using a rolling total, you can both * *maintain an equal distribution; and *not have to sacrifice any element in the random sequence. Both these problems are an issue with the simplistic rand(5)+rand(5)...-type solutions. The following Python code shows how to implement it (most of this is proving the distribution). import random x = [] for i in range (0,7): x.append (0) t = 0 tt = 0 for i in range (0,700000): ######################################## ##### qq.py ##### r = int (random.random () * 5) t = (t + r) % 7 ######################################## ##### qq_notsogood.py ##### #r = 20 #while r > 6: #r = int (random.random () * 5) #r = r + int (random.random () * 5) #t = r ######################################## x[t] = x[t] + 1 tt = tt + 1 high = x[0] low = x[0] for i in range (0,7): print "%d: %7d %.5f" % (i, x[i], 100.0 * x[i] / tt) if x[i] < low: low = x[i] if x[i] > high: high = x[i] diff = high - low print "Variation = %d (%.5f%%)" % (diff, 100.0 * diff / tt) And this output shows the results: pax$ python qq.py 0: 99908 14.27257 1: 100029 14.28986 2: 100327 14.33243 3: 100395 14.34214 4: 99104 14.15771 5: 99829 14.26129 6: 100408 14.34400 Variation = 1304 (0.18629%) pax$ python qq.py 0: 99547 14.22100 1: 100229 14.31843 2: 100078 14.29686 3: 99451 14.20729 4: 100284 14.32629 5: 100038 14.29114 6: 100373 14.33900 Variation = 922 (0.13171%) pax$ python qq.py 0: 100481 14.35443 1: 99188 14.16971 2: 100284 14.32629 3: 100222 14.31743 4: 99960 14.28000 5: 99426 14.20371 6: 100439 14.34843 Variation = 1293 (0.18471%) A simplistic rand(5)+rand(5), ignoring those cases where this returns more than 6 has a typical variation of 18%, 100 times that of the method shown above: pax$ python qq_notsogood.py 0: 31756 4.53657 1: 63304 9.04343 2: 95507 13.64386 3: 127825 18.26071 4: 158851 22.69300 5: 127567 18.22386 6: 95190 13.59857 Variation = 127095 (18.15643%) pax$ python qq_notsogood.py 0: 31792 4.54171 1: 63637 9.09100 2: 95641 13.66300 3: 127627 18.23243 4: 158751 22.67871 5: 126782 18.11171 6: 95770 13.68143 Variation = 126959 (18.13700%) pax$ python qq_notsogood.py 0: 31955 4.56500 1: 63485 9.06929 2: 94849 13.54986 3: 127737 18.24814 4: 159687 22.81243 5: 127391 18.19871 6: 94896 13.55657 Variation = 127732 (18.24743%) And, on the advice of Nixuz, I've cleaned the script up so you can just extract and use the rand7... stuff: import random # rand5() returns 0 through 4 inclusive. def rand5(): return int (random.random () * 5) # rand7() generator returns 0 through 6 inclusive (using rand5()). def rand7(): rand7ret = 0 while True: rand7ret = (rand7ret + rand5()) % 7 yield rand7ret # Number of test runs. count = 700000 # Work out distribution. distrib = [0,0,0,0,0,0,0] rgen =rand7() for i in range (0,count): r = rgen.next() distrib[r] = distrib[r] + 1 # Print distributions and calculate variation. high = distrib[0] low = distrib[0] for i in range (0,7): print "%d: %7d %.5f" % (i, distrib[i], 100.0 * distrib[i] / count) if distrib[i] < low: low = distrib[i] if distrib[i] > high: high = distrib[i] diff = high - low print "Variation = %d (%.5f%%)" % (diff, 100.0 * diff / count) A: This answer is more an experiment in obtaining the most entropy possible from the Rand5 function. t is therefore somewhat unclear and almost certainly a lot slower than other implementations. Assuming the uniform distribution from 0-4 and resulting uniform distribution from 0-6: public class SevenFromFive { public SevenFromFive() { // this outputs a uniform ditribution but for some reason including it // screws up the output distribution // open question Why? this.fifth = new ProbabilityCondensor(5, b => {}); this.eigth = new ProbabilityCondensor(8, AddEntropy); } private static Random r = new Random(); private static uint Rand5() { return (uint)r.Next(0,5); } private class ProbabilityCondensor { private readonly int samples; private int counter; private int store; private readonly Action<bool> output; public ProbabilityCondensor(int chanceOfTrueReciprocal, Action<bool> output) { this.output = output; this.samples = chanceOfTrueReciprocal - 1; } public void Add(bool bit) { this.counter++; if (bit) this.store++; if (counter == samples) { bool? e; if (store == 0) e = false; else if (store == 1) e = true; else e = null;// discard for now counter = 0; store = 0; if (e.HasValue) output(e.Value); } } } ulong buffer = 0; const ulong Mask = 7UL; int bitsAvail = 0; private readonly ProbabilityCondensor fifth; private readonly ProbabilityCondensor eigth; private void AddEntropy(bool bit) { buffer <<= 1; if (bit) buffer |= 1; bitsAvail++; } private void AddTwoBitsEntropy(uint u) { buffer <<= 2; buffer |= (u & 3UL); bitsAvail += 2; } public uint Rand7() { uint selection; do { while (bitsAvail < 3) { var x = Rand5(); if (x < 4) { // put the two low order bits straight in AddTwoBitsEntropy(x); fifth.Add(false); } else { fifth.Add(true); } } // read 3 bits selection = (uint)((buffer & Mask)); bitsAvail -= 3; buffer >>= 3; if (selection == 7) eigth.Add(true); else eigth.Add(false); } while (selection == 7); return selection; } } The number of bits added to the buffer per call to Rand5 is currently 4/5 * 2 so 1.6. If the 1/5 probability value is included that increases by 0.05 so 1.65 but see the comment in the code where I have had to disable this. Bits consumed by call to Rand7 = 3 + 1/8 * (3 + 1/8 * (3 + 1/8 * (... This is 3 + 3/8 + 3/64 + 3/512 ... so approx 3.42 By extracting information from the sevens I reclaim 1/8*1/7 bits per call so about 0.018 This gives a net consumption 3.4 bits per call which means the ratio is 2.125 calls to Rand5 for every Rand7. The optimum should be 2.1. I would imagine this approach is significantly slower than many of the other ones here unless the cost of the call to Rand5 is extremely expensive (say calling out to some external source of entropy). A: just scale your output from your first function 0) you have a number in range 1-5 1) subtract 1 to make it in range 0-4 2) multiply by (7-1)/(5-1) to make it in range 0-6 3) add 1 to increment the range: Now your result is in between 1-7 A: extern int r5(); int r7() { return ((r5() & 0x01) << 2 ) | ((r5() & 0x01) << 1 ) | (r5() & 0x01); } A: in php function rand1to7() { do { $output_value = 0; for ($i = 0; $i < 28; $i++) { $output_value += rand1to5(); } while ($output_value != 140); $output_value -= 12; return floor($output_value / 16); } loops to produce a random number between 16 and 127, divides by sixteen to create a float between 1 and 7.9375, then rounds down to get an int between 1 and 7. if I am not mistaken, there is a 16/112 chance of getting any one of the 7 outcomes. A: I think I have four answers, two giving exact solutions like that of @Adam Rosenfield but without the infinite loop problem, and other two with almost perfect solution but faster implementation than first one. The best exact solution requires 7 calls to rand5, but lets proceed in order to understand. Method 1 - Exact Strength of Adam's answer is that it gives a perfect uniform distribution, and there is very high probability (21/25) that only two calls to rand5() will be needed. However, worst case is infinite loop. The first solution below also gives a perfect uniform distribution, but requires a total of 42 calls to rand5. No infinite loops. Here is an R implementation: rand5 <- function() sample(1:5,1) rand7 <- function() (sum(sapply(0:6, function(i) i + rand5() + rand5()*2 + rand5()*3 + rand5()*4 + rand5()*5 + rand5()*6)) %% 7) + 1 For people not familiar with R, here is a simplified version: rand7 = function(){ r = 0 for(i in 0:6){ r = r + i + rand5() + rand5()*2 + rand5()*3 + rand5()*4 + rand5()*5 + rand5()*6 } return r %% 7 + 1 } The distribution of rand5 will be preserved. If we do the math, each of the 7 iterations of the loop has 5^6 possible combinations, thus total number of possible combinations are (7 * 5^6) %% 7 = 0. Thus we can divide the random numbers generated in equal groups of 7. See method two for more discussion on this. Here are all the possible combinations: table(apply(expand.grid(c(outer(1:5,0:6,"+")),(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6),1,sum) %% 7 + 1) 1 2 3 4 5 6 7 15625 15625 15625 15625 15625 15625 15625 I think it's straight forward to show that Adam's method will run much much faster. The probability that there are 42 or more calls to rand5 in Adam's solution is very small ((4/25)^21 ~ 10^(-17)). Method 2 - Not Exact Now the second method, which is almost uniform, but requires 6 calls to rand5: rand7 <- function() (sum(sapply(1:6,function(i) i*rand5())) %% 7) + 1 Here is a simplified version: rand7 = function(){ r = 0 for(i in 1:6){ r = r + i*rand5() } return r %% 7 + 1 } This is essentially one iteration of method 1. If we generate all possible combinations, here is resulting counts: table(apply(expand.grid(1:5,(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6),1,sum) %% 7 + 1) 1 2 3 4 5 6 7 2233 2232 2232 2232 2232 2232 2232 One number will appear once more in 5^6 = 15625 trials. Now, in Method 1, by adding 1 to 6, we move the number 2233 to each of the successive point. Thus the total number of combinations will match up. This works because 5^6 %% 7 = 1, and then we do 7 appropriate variations, so (7 * 5^6 %% 7 = 0). Method 3 - Exact If the argument of method 1 and 2 is understood, method 3 follows, and requires only 7 calls to rand5. At this point, I feel this is the minimum number of calls needed for an exact solution. Here is an R implementation: rand5 <- function() sample(1:5,1) rand7 <- function() (sum(sapply(1:7, function(i) i * rand5())) %% 7) + 1 For people not familiar with R, here is a simplified version: rand7 = function(){ r = 0 for(i in 1:7){ r = r + i * rand5() } return r %% 7 + 1 } The distribution of rand5 will be preserved. If we do the math, each of the 7 iterations of the loop has 5 possible outcomes, thus total number of possible combinations are (7 * 5) %% 7 = 0. Thus we can divide the random numbers generated in equal groups of 7. See method one and two for more discussion on this. Here are all the possible combinations: table(apply(expand.grid(0:6,(1:5)),1,sum) %% 7 + 1) 1 2 3 4 5 6 7 5 5 5 5 5 5 5 I think it's straight forward to show that Adam's method will still run faster. The probability that there are 7 or more calls to rand5 in Adam's solution is still small ((4/25)^3 ~ 0.004). Method 4 - Not Exact This is a minor variation of the the second method. It is almost uniform, but requires 7 calls to rand5, that is one additional to method 2: rand7 <- function() (rand5() + sum(sapply(1:6,function(i) i*rand5())) %% 7) + 1 Here is a simplified version: rand7 = function(){ r = 0 for(i in 1:6){ r = r + i*rand5() } return (r+rand5()) %% 7 + 1 } If we generate all possible combinations, here is resulting counts: table(apply(expand.grid(1:5,(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6,1:5),1,sum) %% 7 + 1) 1 2 3 4 5 6 7 11160 11161 11161 11161 11161 11161 11160 Two numbers will appear once less in 5^7 = 78125 trials. For most purposes, I can live with that. A: The function you need is rand1_7(), I wrote rand1_5() so that you can test it and plot it. import numpy def rand1_5(): return numpy.random.randint(5)+1 def rand1_7(): q = 0 for i in xrange(7): q+= rand1_5() return q%7 + 1 A: function Rand7 put 200 into x repeat while x > 118 put ((random(5)-1) * 25) + ((random(5)-1) * 5) + (random(5)-1) into x end repeat return (x mod 7) + 1 end Rand7 Three calls to Rand5, which only repeats 6 times out of 125, on average. Think of it as a 3D array, 5x5x5, filled with 1 to 7 over and over, and 6 blanks. Re-roll on the blanks. The rand5 calls create a three digit base-5 index into that array. There would be fewer repeats with a 4D, or higher N-dimensional arrays, but this means more calls to the rand5 function become standard. You'll start to get diminishing efficiency returns at higher dimensions. Three seems to me to be a good compromise, but I haven't tested them against each other to be sure. And it would be rand5-implementation specific. A: int getOneToSeven(){ int added = 0; for(int i = 1; i<=7; i++){ added += getOneToFive(); } return (added)%7+1; } A: This is the simplest answer I could create after reviewing others' answers: def r5tor7(): while True: cand = (5 * r5()) + r5() if cand < 27: return cand cand is in the range [6, 27] and the possible outcomes are evenly distributed if the possible outcomes from r5() are evenly distributed. You can test my answer with this code: from collections import defaultdict def r5_outcome(n): if not n: yield [] else: for i in range(1, 6): for j in r5_outcome(n-1): yield [i] + j def test_r7(): d = defaultdict(int) for x in r5_outcome(2): s = sum([x[i] * 5**i for i in range(len(x))]) if s < 27: d[s] += 1 print len(d), d r5_outcome(2) generates all possible combinations of r5() results. I use the same filter to test as in my solution code. You can see that all of the outcomes are equally probably because they have the same value. A: package CareerCup; public class RangeTransform { static int counter = (int)(Math.random() * 5 + 1); private int func() { return (int) (Math.random() * 5 + 1); } private int getMultiplier() { return counter % 5 + 1; } public int rangeTransform() { counter++; int count = getMultiplier(); int mult = func() + 5 * count; System.out.println("Mult is : " + 5 * count); return (mult) % 7 + 1; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub RangeTransform rangeTransform = new RangeTransform(); for (int i = 0; i < 35; i++) System.out.println("Val is : " + rangeTransform.rangeTransform()); } } A: Why won't this work? Other then the one extra call to rand5()? i = rand5() + rand5() + (rand5() - 1) //Random number between 1 and 14 i = i % 7 + 1; A: For values 0-7 you have the following: 0 000 1 001 2 010 3 011 4 100 5 101 6 110 7 111 From bitwise from left to right Rand5() has p(1) = {2/5, 2/5, 3/5}. So if we complement those probability distributions (~Rand5()) we should be able to use that to produce our number. I'll try to report back later with a solution. Anyone have any thoughts? R A: rand25() =5*(rand5()-1) + rand5() rand7() { while(true) { int r = rand25(); if (r < 21) return r%3; } } Why this works: probability that the loop will run forever is 0. A: Assuming rand gives equal weighting to all bits, then masks with the upper bound. int i = rand(5) ^ (rand(5) & 2); rand(5) can only return: 1b, 10b, 11b, 100b, 101b. You only need to concern yourself with sometimes setting the 2 bit. A: Here's what I've found: * *Random5 produces a range from 1~5, randomly distributed *If we run it 3 times and add them together we'll get a range of 3~15, randomly distributed *Perform arithmetic on the 3~15 range * *(3~15) - 1 = (2~14) *(2~14)/2 = (1~7) Then we get a range of 1~7, which is the Random7 we're looking for. A: We are using the convention rand(n) -> [0, n - 1] here From many of the answer I read, they provide either uniformity or halt guarantee, but not both (adam rosenfeld second answer might). It is, however, possible to do so. We basically have this distribution: This leaves us a hole in the distribution over [0-6]: 5 and 6 have no probability of ocurrence. Imagine now we try to fill the hole it by shifting the probability distribution and summing. Indeed, we can the initial distribution with itself shifted by one, and repeating by summing the obtained distribution with the initial one shifted by two, then three and so on, until 7, not included (we covered the whole range). This is shown on the following figure. The order of the colors, corresponding to the steps, is blue -> green -> cyan -> white -> magenta -> yellow -> red. Because each slot is covered by 5 of the 7 shifted distributions (shift varies from 0 to 6), and because we assume the random numbers are independent from one ran5() call to another, we obtain p(x) = 5 / 35 = 1 / 7 for all x in [0, 6] This means that, given 7 independent random numbers from ran5(), we can compute a random number with uniform probability in the [0-6] range. In fact, the ran5() probability distribution does not even need to be uniform, as long as the samples are independent (so the distribution stays the same from trial to trial). Also, this is valid for other numbers than 5 and 7. This gives us the following python function: def rand_range_transform(rands): """ returns a uniform random number in [0, len(rands) - 1] if all r in rands are independent random numbers from the same uniform distribution """ return sum((x + i) for i, x in enumerate(rands)) % len(rands) # a single modulo outside the sum is enough in modulo arithmetic This can be used like this: rand5 = lambda : random.randrange(5) def rand7(): return rand_range_transform([rand5() for _ in range(7)]) If we call rand7() 70000 times, we can get: max: 6 min: 0 mean: 2.99711428571 std: 2.00194697049 0: 10019 1: 10016 2: 10071 3: 10044 4: 9775 5: 10042 6: 10033 This is good, although far from perfect. The fact is, one of our assumption is most likely false in this implementation: we use a PRNG, and as such, the result of the next call is dependent from the last result. That said, using a truly random source of numbers, the output should also be truly random. And this algorithm terminates in every case. But this comes with a cost: we need 7 calls to rand5() for a single rand7() call. A: This solution doesn't waste any entropy and gives the first available truly random number in range. With each iteration the probability of not getting an answer is provably decreased. The probability of getting an answer in N iterations is the probability that a random number between 0 and max (5^N) will be smaller than the largest multiple of seven in that range (max-max%7). Must iterate at least twice. But that's necessarily true for all solutions. int random7() { range = 1; remainder = 0; while (1) { remainder = remainder * 5 + random5() - 1; range = range * 5; limit = range - (range % 7); if (remainder < limit) return (remainder % 7) + 1; remainder = remainder % 7; range = range % 7; } } Numerically equivalent to: r5=5; num=random5()-1; while (1) { num=num*5+random5()-1; r5=r5*5; r7=r5-r5%7; if (num<r7) return num%7+1; } The first code calculates it in modulo form. The second code is just plain math. Or I made a mistake somewhere. :-) A: Another answer which appears to have not been covered here: int rand7() { int r = 7 / 2; for (int i = 0; i < 28; i++) r = ((rand5() - 1) * 7 + r) / 5; return r + 1; } On every iteration r is a random value between 0 and 6 inclusive. This is appended (base 7) to a random value between 0 and 4 inclusive, and the result is divided by 5, giving a new random value in the range of 0 to 6 inclusive. r starts with a substantial bias (r = 3 is very biased!) but each iteration divides that bias by 5. This method is not perfectly uniform; however, the bias is vanishingly small. Something in the order of 1/(2**64). What's important about this approach is that it has constant execution time (assuming rand5() also has constant execution time). No theoretical concerns that an unlucky call could iterate forever picking bad values. Also, a sarcastic answer for good measure (deliberately or not, it has been covered): 1-5 is already within the range 1-7, therefore the following is a valid implementation: int rand7() { return rand5(); } Question did not ask for uniform distribution. A: int randbit( void ) { while( 1 ) { int r = rand5(); if( r <= 4 ) return(r & 1); } } int randint( int nbits ) { int result = 0; while( nbits-- ) { result = (result<<1) | randbit(); } return( result ); } int rand7( void ) { while( 1 ) { int r = randint( 3 ) + 1; if( r <= 7 ) return( r ); } } A: rand7() = (rand5()+rand5()+rand5()+rand5()+rand5()+rand5()+rand5())%7+1 Edit: That doesn't quite work. It's off by about 2 parts in 1000 (assuming a perfect rand5). The buckets get: value Count Error% 1 11158 -0.0035 2 11144 -0.0214 3 11144 -0.0214 4 11158 -0.0035 5 11172 +0.0144 6 11177 +0.0208 7 11172 +0.0144 By switching to a sum of n Error% 10 +/- 1e-3, 12 +/- 1e-4, 14 +/- 1e-5, 16 +/- 1e-6, ... 28 +/- 3e-11 seems to gain an order of magnitude for every 2 added BTW: the table of errors above was not generated via sampling but by the following recurrence relation: p[x,n] is the number ways output=x can happen given n calls to rand5. p[1,1] ... p[5,1] = 1 p[6,1] ... p[7,1] = 0 p[1,n] = p[7,n-1] + p[6,n-1] + p[5,n-1] + p[4,n-1] + p[3,n-1] p[2,n] = p[1,n-1] + p[7,n-1] + p[6,n-1] + p[5,n-1] + p[4,n-1] p[3,n] = p[2,n-1] + p[1,n-1] + p[7,n-1] + p[6,n-1] + p[5,n-1] p[4,n] = p[3,n-1] + p[2,n-1] + p[1,n-1] + p[7,n-1] + p[6,n-1] p[5,n] = p[4,n-1] + p[3,n-1] + p[2,n-1] + p[1,n-1] + p[7,n-1] p[6,n] = p[5,n-1] + p[4,n-1] + p[3,n-1] + p[2,n-1] + p[1,n-1] p[7,n] = p[6,n-1] + p[5,n-1] + p[4,n-1] + p[3,n-1] + p[2,n-1] A: int ans = 0; while (ans == 0) { for (int i=0; i<3; i++) { while ((r = rand5()) == 3){}; ans += (r < 3) >> i } } A: I'd like to add another answer, in addition to my first answer. This answer attempts to minimize the number of calls to rand5() per call to rand7(), to maximize the usage of randomness. That is, if you consider randomness to be a precious resource, we want to use as much of it as possible, without throwing away any random bits. This answer also has some similarities with the logic presented in Ivan's answer. The entropy of a random variable is a well-defined quantity. For a random variable which takes on N states with equal probabilities (a uniform distribution), the entropy is log2 N. Thus, rand5() has approximately 2.32193 bits of entropy, and rand7() has about 2.80735 bits of entropy. If we hope to maximize our use of randomness, we need to use all 2.32193 bits of entropy from each call to rand5(), and apply them to generating 2.80735 bits of entropy needed for each call to rand7(). The fundamental limit, then, is that we can do no better than log(7)/log(5) = 1.20906 calls to rand5() per call to rand7(). Side notes: all logarithms in this answer will be base 2 unless specified otherwise. rand5() will be assumed to return numbers in the range [0, 4], and rand7() will be assumed to return numbers in the range [0, 6]. Adjusting the ranges to [1, 5] and [1, 7] respectively is trivial. So how do we do it? We generate an infinitely precise random real number between 0 and 1 (pretend for the moment that we could actually compute and store such an infinitely precise number -- we'll fix this later). We can generate such a number by generating its digits in base 5: we pick the random number 0.a1a2a3..., where each digit ai is chosen by a call to rand5(). For example, if our RNG chose ai = 1 for all i, then ignoring the fact that that isn't very random, that would correspond to the real number 1/5 + 1/52 + 1/53 + ... = 1/4 (sum of a geometric series). Ok, so we've picked a random real number between 0 and 1. I now claim that such a random number is uniformly distributed. Intuitively, this is easy to understand, since each digit was picked uniformly, and the number is infinitely precise. However, a formal proof of this is somewhat more involved, since now we're dealing with a continuous distribution instead of a discrete distribution, so we need to prove that the probability that our number lies in an interval [a, b] equals the length of that interval, b - a. The proof is left as an exercise for the reader =). Now that we have a random real number selected uniformly from the range [0, 1], we need to convert it to a series of uniformly random numbers in the range [0, 6] to generate the output of rand7(). How do we do this? Just the reverse of what we just did -- we convert it to an infinitely precise decimal in base 7, and then each base 7 digit will correspond to one output of rand7(). Taking the example from earlier, if our rand5() produces an infinite stream of 1's, then our random real number will be 1/4. Converting 1/4 to base 7, we get the infinite decimal 0.15151515..., so we will produce as output 1, 5, 1, 5, 1, 5, etc. Ok, so we have the main idea, but we have two problems left: we can't actually compute or store an infinitely precise real number, so how do we deal with only a finite portion of it? Secondly, how do we actually convert it to base 7? One way we can convert a number between 0 and 1 to base 7 is as follows: * *Multiply by 7 *The integral part of the result is the next base 7 digit *Subtract off the integral part, leaving only the fractional part *Goto step 1 To deal with the problem of infinite precision, we compute a partial result, and we also store an upper bound on what the result could be. That is, suppose we've called rand5() twice and it returned 1 both times. The number we've generated so far is 0.11 (base 5). Whatever the rest of the infinite series of calls to rand5() produce, the random real number we're generating will never be larger than 0.12: it is always true that 0.11 ≤ 0.11xyz... < 0.12. So, keeping track of the current number so far, and the maximum value it could ever take, we convert both numbers to base 7. If they agree on the first k digits, then we can safely output the next k digits -- regardless of what the infinite stream of base 5 digits are, they will never affect the next k digits of the base 7 representation! And that's the algorithm -- to generate the next output of rand7(), we generate only as many digits of rand5() as we need to ensure that we know with certainty the value of the next digit in the conversion of the random real number to base 7. Here is a Python implementation, with a test harness: import random rand5_calls = 0 def rand5(): global rand5_calls rand5_calls += 1 return random.randint(0, 4) def rand7_gen(): state = 0 pow5 = 1 pow7 = 7 while True: if state / pow5 == (state + pow7) / pow5: result = state / pow5 state = (state - result * pow5) * 7 pow7 *= 7 yield result else: state = 5 * state + pow7 * rand5() pow5 *= 5 if __name__ == '__main__': r7 = rand7_gen() N = 10000 x = list(next(r7) for i in range(N)) distr = [x.count(i) for i in range(7)] expmean = N / 7.0 expstddev = math.sqrt(N * (1.0/7.0) * (6.0/7.0)) print '%d TRIALS' % N print 'Expected mean: %.1f' % expmean print 'Expected standard deviation: %.1f' % expstddev print print 'DISTRIBUTION:' for i in range(7): print '%d: %d (%+.3f stddevs)' % (i, distr[i], (distr[i] - expmean) / expstddev) print print 'Calls to rand5: %d (average of %f per call to rand7)' % (rand5_calls, float(rand5_calls) / N) Note that rand7_gen() returns a generator, since it has internal state involving the conversion of the number to base 7. The test harness calls next(r7) 10000 times to produce 10000 random numbers, and then it measures their distribution. Only integer math is used, so the results are exactly correct. Also note that the numbers here get very big, very fast. Powers of 5 and 7 grow quickly. Hence, performance will start to degrade noticeably after generating lots of random numbers, due to bignum arithmetic. But remember here, my goal was to maximize the usage of random bits, not to maximize performance (although that is a secondary goal). In one run of this, I made 12091 calls to rand5() for 10000 calls to rand7(), achieving the minimum of log(7)/log(5) calls on average to 4 significant figures, and the resulting output was uniform. In order to port this code to a language that doesn't have arbitrarily large integers built-in, you'll have to cap the values of pow5 and pow7 to the maximum value of your native integral type -- if they get too big, then reset everything and start over. This will increase the average number of calls to rand5() per call to rand7() very slightly, but hopefully it shouldn't increase too much even for 32- or 64-bit integers. A: The following produces a uniform distribution on {1, 2, 3, 4, 5, 6, 7} using a random number generator producing a uniform distribution on {1, 2, 3, 4, 5}. The code is messy, but the logic is clear. public static int random_7(Random rg) { int returnValue = 0; while (returnValue == 0) { for (int i = 1; i <= 3; i++) { returnValue = (returnValue << 1) + SimulateFairCoin(rg); } } return returnValue; } private static int SimulateFairCoin(Random rg) { while (true) { int flipOne = random_5_mod_2(rg); int flipTwo = random_5_mod_2(rg); if (flipOne == 0 && flipTwo == 1) { return 0; } else if (flipOne == 1 && flipTwo == 0) { return 1; } } } private static int random_5_mod_2(Random rg) { return random_5(rg) % 2; } private static int random_5(Random rg) { return rg.Next(5) + 1; } A: int rand7() { int value = rand5() + rand5() * 2 + rand5() * 3 + rand5() * 4 + rand5() * 5 + rand5() * 6; return value%7; } Unlike the chosen solution, the algorithm will run in constant time. It does however make 2 more calls to rand5 than the average run time of the chosen solution. Note that this generator is not perfect (the number 0 has 0.0064% more chance than any other number), but for most practical purposes the guarantee of constant time probably outweighs this inaccuracy. Explanation This solution is derived from the fact that the number 15,624 is divisible by 7 and thus if we can randomly and uniformly generate numbers from 0 to 15,624 and then take mod 7 we can get a near-uniform rand7 generator. Numbers from 0 to 15,624 can be uniformly generated by rolling rand5 6 times and using them to form the digits of a base 5 number as follows: rand5 * 5^5 + rand5 * 5^4 + rand5 * 5^3 + rand5 * 5^2 + rand5 * 5 + rand5 Properties of mod 7 however allow us to simplify the equation a bit: 5^5 = 3 mod 7 5^4 = 2 mod 7 5^3 = 6 mod 7 5^2 = 4 mod 7 5^1 = 5 mod 7 So rand5 * 5^5 + rand5 * 5^4 + rand5 * 5^3 + rand5 * 5^2 + rand5 * 5 + rand5 becomes rand5 * 3 + rand5 * 2 + rand5 * 6 + rand5 * 4 + rand5 * 5 + rand5 Theory The number 15,624 was not chosen randomly, but can be discovered using fermat's little theorem, which states that if p is a prime number then a^(p-1) = 1 mod p So this gives us, (5^6)-1 = 0 mod 7 (5^6)-1 is equal to 4 * 5^5 + 4 * 5^4 + 4 * 5^3 + 4 * 5^2 + 4 * 5 + 4 This is a number in base 5 form and thus we can see that this method can be used to go from any random number generator to any other random number generator. Though a small bias towards 0 is always introduced when using the exponent p-1. To generalize this approach and to be more accurate we can have a function like this: def getRandomconverted(frm, to): s = 0 for i in range(to): s += getRandomUniform(frm)*frm**i mx = 0 for i in range(to): mx = (to-1)*frm**i mx = int(mx/to)*to # maximum value till which we can take mod if s < mx: return s%to else: return getRandomconverted(frm, to) A: Are homework problems allowed here? This function does crude "base 5" math to generate a number between 0 and 6. function rnd7() { do { r1 = rnd5() - 1; do { r2=rnd5() - 1; } while (r2 > 1); result = r2 * 5 + r1; } while (result > 6); return result + 1; } A: If we consider the additional constraint of trying to give the most efficient answer i.e one that given an input stream, I, of uniformly distributed integers of length m from 1-5 outputs a stream O, of uniformly distributed integers from 1-7 of the longest length relative to m, say L(m). The simplest way to analyse this is to treat the streams I and O as 5-ary and 7-ary numbers respectively. This is achieved by the main answer's idea of taking the stream a1, a2, a3,... -> a1+5*a2+5^2*a3+.. and similarly for stream O. Then if we take a section of the input stream of length m choose n s.t. 5^m-7^n=c where c>0 and is as small as possible. Then there is a uniform map from the input stream of length m to integers from 1 to 5^m and another uniform map from integers from 1 to 7^n to the output stream of length n where we may have to lose a few cases from the input stream when the mapped integer exceeds 7^n. So this gives a value for L(m) of around m (log5/log7) which is approximately .82m. The difficulty with the above analysis is the equation 5^m-7^n=c which is not easy to solve exactly and the case where the uniform value from 1 to 5^m exceeds 7^n and we lose efficiency. The question is how close to the best possible value of m (log5/log7) can be attain. For example when this number approaches close to an integer can we find a way to achieve this exact integral number of output values? If 5^m-7^n=c then from the input stream we effectively generate a uniform random number from 0 to (5^m)-1 and don't use any values higher than 7^n. However these values can be rescued and used again. They effectively generate a uniform sequence of numbers from 1 to 5^m-7^n. So we can then try to use these and convert them into 7-ary numbers so that we can create more output values. If we let T7(X) to be the average length of the output sequence of random(1-7) integers derived from a uniform input of size X, and assuming that 5^m=7^n0+7^n1+7^n2+...+7^nr+s, s<7. Then T7(5^m)=n0x7^n0/5^m + ((5^m-7^n0)/5^m) T7(5^m-7^n0) since we have a length no sequence with probability 7^n0/5^m with a residual of length 5^m-7^n0 with probability (5^m-7^n0)/5^m). If we just keep substituting we obtain: T7(5^m) = n0x7^n0/5^m + n1x7^n1/5^m + ... + nrx7^nr/5^m = (n0x7^n0 + n1x7^n1 + ... + nrx7^nr)/5^m Hence L(m)=T7(5^m)=(n0x7^n0 + n1x7^n1 + ... + nrx7^nr)/(7^n0+7^n1+7^n2+...+7^nr+s) Another way of putting this is: If 5^m has 7-ary representation `a0+a1*7 + a2*7^2 + a3*7^3+...+ar*7^r Then L(m) = (a1*7 + 2a2*7^2 + 3a3*7^3+...+rar*7^r)/(a0+a1*7 + a2*7^2 + a3*7^3+...+ar*7^r) The best possible case is my original one above where 5^m=7^n+s, where s<7. Then T7(5^m) = nx(7^n)/(7^n+s) = n+o(1) = m (Log5/Log7)+o(1) as before. The worst case is when we can only find k and s.t 5^m = kx7+s. Then T7(5^m) = 1x(k.7)/(k.7+s) = 1+o(1) Other cases are somewhere inbetween. It would be interesting to see how well we can do for very large m, i.e. how good can we get the error term: T7(5^m) = m (Log5/Log7)+e(m) It seems impossible to achieve e(m) = o(1) in general but hopefully we can prove e(m)=o(m). The whole thing then rests on the distribution of the 7-ary digits of 5^m for various values of m. I'm sure there is a lot of theory out there that covers this I may have a look and report back at some point. A: Here is a working Python implementation of Adam's answer. import random def rand5(): return random.randint(1, 5) def rand7(): while True: r = 5 * (rand5() - 1) + rand5() #r is now uniformly random between 1 and 25 if (r <= 21): break #result is now uniformly random between 1 and 7 return r % 7 + 1 I like to throw algorithms I'm looking at into Python so I can play around with them, thought I'd post it here in the hopes that it is useful to someone out there, not that it took long to throw together. A: how about this rand5()%2+rand5()%2+rand5()%2+rand5()%2+rand5()%2+rand5()%2 Not sure this is uniform distributed. Any suggestions? A: I thought of an interesting solution to this problem and wanted to share it. function rand7() { var returnVal = 4; for (var n=0; n<3; n++) { var rand = rand5(); if (rand==1||rand==2){ returnVal+=1; } else if (rand==3||rand==4) { returnVal-=1; } } return returnVal; } I built a test function that loops through rand7() 10,000 times, sums up all of the return values, and divides it by 10,000. If rand7() is working correctly, our calculated average should be 4 - for example, (1+2+3+4+5+6+7 / 7) = 4. After doing multiple tests, the average is indeed right at 4 :) A: First thing came on my mind is this. But i have no idea whether its uniformly distributed. Implemented in python import random def rand5(): return random.randint(1,5) def rand7(): return ( ( (rand5() -1) * rand5() ) %7 )+1 A: Here's my general implementation, to generate a uniform in the range [0,N-1] given a uniform generator in the range [0,B-1]. public class RandomUnif { public static final int BASE_NUMBER = 5; private static Random rand = new Random(); /** given generator, returns uniform integer in the range 0.. BASE_NUMBER-1 public static int randomBASE() { return rand.nextInt(BASE_NUMBER); } /** returns uniform integer in the range 0..n-1 using randomBASE() */ public static int randomUnif(int n) { int rand, factor; if( n <= 1 ) return 0; else if( n == BASE_NUMBER ) return randomBASE(); if( n < BASE_NUMBER ) { factor = BASE_NUMBER / n; do rand = randomBASE() / factor; while(rand >= n); return rand; } else { factor = (n - 1) / BASE_NUMBER + 1; do { rand = factor * randomBASE() + randomUnif(factor); } while(rand >= n); return rand; } } } Not spectaculary efficient, but general and compact. Mean calls to base generator: n calls 2 1.250 3 1.644 4 1.252 5 1.000 6 3.763 7 3.185 8 2.821 9 2.495 10 2.250 11 3.646 12 3.316 13 3.060 14 2.853 15 2.650 16 2.814 17 2.644 18 2.502 19 2.361 20 2.248 21 2.382 22 2.277 23 2.175 24 2.082 25 2.000 26 5.472 27 5.280 28 5.119 29 4.899 A: There are a lot of solutions here that do not produce a uniform distribution and many comments pointing that out, but the the question does not state that as a requirement. The simplest solution is: int rand_7() { return rand_5(); } A random integer in the range 1 - 5 is clearly in the range 1 - 7. Well, technically, the simplest solution is to return a constant, but that's too trivial. However, I think the existence of the rand_5 function is a red herring. Suppose the question was asked as "produce a uniformly distributed pseudo-random number generator with integer output in the range 1 - 7". That's a simple problem (not technically simple, but already solved, so you can look it up.) On the other hand, if the question is interpreted to mean that you actually have a truly random number generator for integers in the range 1 - 5 (not pseudo random), then the solution is: 1) examine the rand_5 function 2) understand how it works 3) profit A: function rand7() { while (true) { //lowest base 5 random number > 7 reduces memory int num = (rand5()-1)*5 + rand5()-1; if (num < 21) // improves performance return 1 + num%7; } } Python code: from random import randint def rand7(): while(True): num = (randint(1, 5)-1)*5 + randint(1, 5)-1 if num < 21: return 1 + num%7 Test distribution for 100000 runs: >>> rnums = [] >>> for _ in range(100000): rnums.append(rand7()) >>> {n:rnums.count(n) for n in set(rnums)} {1: 15648, 2: 15741, 3: 15681, 4: 15847, 5: 15642, 6: 15806, 7: 15635} A: This is similiarly to @RobMcAfee except that I use magic number instead of 2 dimensional array. int rand7() { int m = 1203068; int r = (m >> (rand5() - 1) * 5 + rand5() - 1) & 7; return (r > 0) ? r : rand7(); } A: This solution was inspired by Rob McAfee. However it doesn't need a loop and the result is a uniform distribution: // Returns 1-5 var rnd5 = function(){ return parseInt(Math.random() * 5, 10) + 1; } // Helper var lastEdge = 0; // Returns 1-7 var rnd7 = function () { var map = [ [ 1, 2, 3, 4, 5 ], [ 6, 7, 1, 2, 3 ], [ 4, 5, 6, 7, 1 ], [ 2, 3, 4, 5, 6 ], [ 7, 0, 0, 0, 0 ] ]; var result = map[rnd5() - 1][rnd5() - 1]; if (result > 0) { return result; } lastEdge++; if (lastEdge > 7 ) { lastEdge = 1; } return lastEdge; }; // Test the a uniform distribution results = {}; for(i=0; i < 700000;i++) { var rand = rnd7(); results[rand] = results[rand] ? results[rand] + 1 : 1;} console.log(results) Result: [1: 99560, 2: 99932, 3: 100355, 4: 100262, 5: 99603, 6: 100062, 7: 100226] jsFiddle A: I think y'all are overthinking this. Doesn't this simple solution work? int rand7(void) { static int startpos = 0; startpos = (startpos+5) % (5*7); return (((startpos + rand5()-1)%7)+1); } A: Given a function which produces a random integer in the range 1 to 5 rand5(), write a function which produces a random integer in the range 1 to 7 rand7() In my proposed solution, I only call rand5 once only Real Solution float rand7() { return (rand5() * 7.0) / 5.0 ; } The distribution here is scaled, so it depends directly on the distribution of rand5 Integer Solution int rand7() { static int prev = 1; int cur = rand5(); int r = cur * prev; // 1-25 float f = r / 4.0; // 0.25-6.25 f = f - 0.25; // 0-6 f = f + 1.0; // 1-7 prev = cur; return (int)f; } The distribution here depends on the series rand7(i) ~ rand5(i) * rand5(i-1) with rand7(0) ~ rand5(0) * 1 A: Here is an answer taking advantage of features in C++ 11 #include <functional> #include <iostream> #include <ostream> #include <random> int main() { std::random_device rd; unsigned long seed = rd(); std::cout << "seed = " << seed << std::endl; std::mt19937 engine(seed); std::uniform_int_distribution<> dist(1, 5); auto rand5 = std::bind(dist, engine); const int n = 20; for (int i = 0; i != n; ++i) { std::cout << rand5() << " "; } std::cout << std::endl; // Use a lambda expression to define rand7 auto rand7 = [&rand5]()->int { for (int result = 0; ; result = 0) { // Take advantage of the fact that // 5**6 = 15625 = 15624 + 1 = 7 * (2232) + 1. // So we only have to discard one out of every 15625 numbers generated. // Generate a 6-digit number in base 5 for (int i = 0; i != 6; ++i) { result = 5 * result + (rand5() - 1); } // result is in the range [0, 15625) if (result == 15625 - 1) { // Discard this number continue; } // We now know that result is in the range [0, 15624), a range that can // be divided evenly into 7 buckets guaranteeing uniformity result /= 2232; return 1 + result; } }; for (int i = 0; i != n; ++i) { std::cout << rand7() << " "; } std::cout << std::endl; return 0; } A: Would be cool if someone could give me feedback on this one, I used the JUNIT without assert Pattern because it's easy and fast to get it running in Eclipse, I could also have just defined a main method. By the way, I am assuming rand5 gives values 0-4, adding 1 would make it 1-5, same with rand7... So the discussion should be on the solution, it's distribution, not on wether it goes from 0-4 or 1-5... package random; import java.util.Random; import org.junit.Test; public class RandomTest { @Test public void testName() throws Exception { long times = 100000000; int indexes[] = new int[7]; for(int i = 0; i < times; i++) { int rand7 = rand7(); indexes[rand7]++; } for(int i = 0; i < 7; i++) System.out.println("Value " + i + ": " + indexes[i]); } public int rand7() { return (rand5() + rand5() + rand5() + rand5() + rand5() + rand5() + rand5()) % 7; } public int rand5() { return new Random().nextInt(5); } } When I run it, I get this result: Value 0: 14308087 Value 1: 14298303 Value 2: 14279731 Value 3: 14262533 Value 4: 14269749 Value 5: 14277560 Value 6: 14304037 This seems like a very fair distribution, doesn't it? If I add rand5() less or more times (where the amount of times is not divisible by 7), the distribution clearly shows offsets. For instance, adding rand5() 3 times: Value 0: 15199685 Value 1: 14402429 Value 2: 12795649 Value 3: 12796957 Value 4: 14402252 Value 5: 15202778 Value 6: 15200250 So, this would lead to the following: public int rand(int range) { int randomValue = 0; for(int i = 0; i < range; i++) { randomValue += rand5(); } return randomValue % range; } And then, I could go further: public static final int ORIGN_RANGE = 5; public static final int DEST_RANGE = 7; @Test public void testName() throws Exception { long times = 100000000; int indexes[] = new int[DEST_RANGE]; for(int i = 0; i < times; i++) { int rand7 = convertRand(DEST_RANGE, ORIGN_RANGE); indexes[rand7]++; } for(int i = 0; i < DEST_RANGE; i++) System.out.println("Value " + i + ": " + indexes[i]); } public int convertRand(int destRange, int originRange) { int randomValue = 0; for(int i = 0; i < destRange; i++) { randomValue += rand(originRange); } return randomValue % destRange; } public int rand(int range) { return new Random().nextInt(range); } I tried this replacing the destRange and originRange with various values (even 7 for ORIGIN and 13 for DEST), and I get this distribution: Value 0: 7713763 Value 1: 7706552 Value 2: 7694697 Value 3: 7695319 Value 4: 7688617 Value 5: 7681691 Value 6: 7674798 Value 7: 7680348 Value 8: 7685286 Value 9: 7683943 Value 10: 7690283 Value 11: 7699142 Value 12: 7705561 What I can conclude from here is that you can change any random to anyother by suming the origin random "destination" times. This will get a kind of gaussian distribution (being the middle values more likely, and the edge values more uncommon). However, the modulus of destination seems to distribute itself evenly across this gaussian distribution... It would be great to have feedback from a mathematician... What is cool is that the cost is 100% predictable and constant, whereas other solutions cause a small probability of infinite loop... A: Similar to Martin's answer, but resorts to throwing entropy away much less frequently: int rand7(void) { static int m = 1; static int r = 0; for (;;) { while (m <= INT_MAX / 5) { r = r + m * (rand5() - 1); m = m * 5; } int q = m / 7; if (r < q * 7) { int i = r % 7; r = r / 7; m = q; return i + 1; } r = r - q * 7; m = m - q * 7; } } Here we build up a random value between 0 and m-1, and try to maximise m by adding as much state as will fit without overflow (INT_MAX being the largest value that will fit in an int in C, or you can replace that with any large value that makes sense in your language and architecture). Then; if r falls within the largest possible interval evenly divisible by 7 then it contains a viable result and we can divide that interval by 7 and take the remainder as our result and return the rest of the value to our entropy pool. Otherwise r is in the other interval which doesn't divide evenly and we have to discard and restart our entropy pool from that ill-fitting interval. Compared with the popular answers in here, it calls rand5() about half as often on average. The divides can be factored out into trivial bit-twiddles and LUTs for performance. A: * *What is a simple solution? (rand5() + rand5()) % 7 + 1 *What is an effective solution to reduce memory usage or run on a slower CPU? Yes, this is effective as it calls rand5() only twice and have O(1) space complexity Consider rand5() gives out random numbers from 1 to 5(inclusive). (1 + 1) % 7 + 1 = 3 (1 + 2) % 7 + 1 = 4 (1 + 3) % 7 + 1 = 5 (1 + 4) % 7 + 1 = 6 (1 + 5) % 7 + 1 = 7 (2 + 1) % 7 + 1 = 4 (2 + 2) % 7 + 1 = 5 (2 + 3) % 7 + 1 = 6 (2 + 4) % 7 + 1 = 7 (2 + 5) % 7 + 1 = 1 ... (5 + 1) % 7 + 1 = 7 (5 + 2) % 7 + 1 = 1 (5 + 3) % 7 + 1 = 2 (5 + 4) % 7 + 1 = 3 (5 + 5) % 7 + 1 = 4 ... and so on A: Came here from a link from expanding a float range. This one is more fun. Instead of how I got to the conclusion, it occurred to me that for a given random integer generating function f with "base" b (4 in this case,i'll tell why), it can be expanded like below: (b^0 * f() + b^1 * f() + b^2 * f() .... b^p * f()) / (b^(p+1) - 1) * (b-1) This will convert a random generator to a FLOAT generator. I will define 2 parameters here the b and the p. Although the "base" here is 4, b can in fact be anything, it can also be an irrational number etc. p, i call precision is a degree of how well grained you want your float generator to be. Think of this as the number of calls made to rand5 for each call of rand7. But I realized if you set b to base+1 (which is 4+1 = 5 in this case), it's a sweet spot and you'll get a uniform distribution. First get rid of this 1-5 generator, it is in truth rand4() + 1: function rand4(){ return Math.random() * 5 | 0; } To get there, you can substitute rand4 with rand5()-1 Next is to convert rand4 from an integer generator to a float generator function toFloat(f,b,p){ b = b || 2; p = p || 3; return (Array.apply(null,Array(p)) .map(function(d,i){return f()}) .map(function(d,i){return Math.pow(b,i)*d}) .reduce(function(ac,d,i){return ac += d;})) / ( (Math.pow(b,p) - 1) /(b-1) ) } This will apply the first function I wrote to a given rand function. Try it: toFloat(rand4) //1.4285714285714286 base = 2, precision = 3 toFloat(rand4,3,4) //0.75 base = 3, precision = 4 toFloat(rand4,4,5) //3.7507331378299122 base = 4, precision = 5 toFloat(rand4,5,6) //0.2012288786482335 base = 5, precision =6 ... Now you can convert this float range (0-4 INCLUSIVE) to any other float range and then downgrade it to be an integer. Here our base is 4 because we are dealing with rand4, therefore a value b=5 will give you a uniform distribution. As the b grows past 4, you will start introducing periodic gaps in the distribution. I tested for b values ranging from 2 to 8 with 3000 points each and compared to native Math.random of javascript, looks to me even better than the native one itself: http://jsfiddle.net/ibowankenobi/r57v432t/ For the above link, click on the "bin" button on the top side of the distributions to decrease the binning size. The last graph is native Math.random, the 4th one where d=5 is uniform. After you get your float range either multiply with 7 and throw the decimal part or multiply with 7, subtract 0.5 and round: ((toFloat(rand4,5,6)/4 * 7) | 0) + 1 ---> occasionally you'll get 8 with 1/4^6 probability. Math.round((toFloat(rand4,5,6)/4 * 7) - 0.5) + 1 --> between 1 and 7 A: Why don't you just divide by 5 and multiply by 7, and then round? (Granted, you would have to use floating-point no.s) It's much easier and more reliable (really?) than the other solutions. E.g. in Python: def ranndomNo7(): import random rand5 = random.randint(4) # Produces range: [0, 4] rand7 = int(rand5 / 5 * 7) # /5, *7, +0.5 and floor() return rand7 Wasn't that easy? A: int rand7() { return ( rand5() + (rand5()%3) ); } * *rand5() - Returns values from 1-5 *rand5()%3 - Returns values from 0-2 *So, when summing up the total value will be between 1-7 A: This expression is sufficient to get random integers between 1 - 7 int j = ( rand5()*2 + 4 ) % 7 + 1; A: The simple solution has been well covered: take two random5 samples for one random7 result and do it over if the result is outside the range that generates a uniform distribution. If your goal is to reduce the number of calls to random5 this is extremely wasteful - the average number of calls to random5 for each random7 output is 2.38 rather than 2 due to the number of thrown away samples. You can do better by using more random5 inputs to generate more than one random7 output at a time. For results calculated with a 31-bit integer, the optimum comes when using 12 calls to random5 to generate 9 random7 outputs, taking an average of 1.34 calls per output. It's efficient because only 2018983 out of 244140625 results need to be scrapped, or less than 1%. Demo in Python: def random5(): return random.randint(1, 5) def random7gen(n): count = 0 while n > 0: samples = 6 * 7**9 while samples >= 6 * 7**9: samples = 0 for i in range(12): samples = samples * 5 + random5() - 1 count += 1 samples //= 6 for outputs in range(9): yield samples % 7 + 1, count samples //= 7 count = 0 n -= 1 if n == 0: break >>> from collections import Counter >>> Counter(x for x,i in random7gen(10000000)) Counter({2: 1430293, 4: 1429298, 1: 1428832, 7: 1428571, 3: 1428204, 5: 1428134, 6: 1426668}) >>> sum(i for x,i in random7gen(10000000)) / 10000000.0 1.344606 A: First, I move ramdom5() on the 1 point 6 times, to get 7 random numbers. Second, I add 7 numbers to obtain common sum. Third, I get remainder of the division at 7. Last, I add 1 to get results from 1 till 7. This method gives an equal probability of getting numbers in the range from 1 to 7, with the exception of 1. 1 has a slightly higher probability. public int random7(){ Random random = new Random(); //function (1 + random.nextInt(5)) is given int random1_5 = 1 + random.nextInt(5); // 1,2,3,4,5 int random2_6 = 2 + random.nextInt(5); // 2,3,4,5,6 int random3_7 = 3 + random.nextInt(5); // 3,4,5,6,7 int random4_8 = 4 + random.nextInt(5); // 4,5,6,7,8 int random5_9 = 5 + random.nextInt(5); // 5,6,7,8,9 int random6_10 = 6 + random.nextInt(5); //6,7,8,9,10 int random7_11 = 7 + random.nextInt(5); //7,8,9,10,11 //sumOfRandoms is between 28 and 56 int sumOfRandoms = random1_5 + random2_6 + random3_7 + random4_8 + random5_9 + random6_10 + random7_11; //result is number between 0 and 6, and //equals 0 if sumOfRandoms = 28 or 35 or 42 or 49 or 56 , 5 options //equals 1 if sumOfRandoms = 29 or 36 or 43 or 50, 4 options //equals 2 if sumOfRandoms = 30 or 37 or 44 or 51, 4 options //equals 3 if sumOfRandoms = 31 or 38 or 45 or 52, 4 options //equals 4 if sumOfRandoms = 32 or 39 or 46 or 53, 4 options //equals 5 if sumOfRandoms = 33 or 40 or 47 or 54, 4 options //equals 6 if sumOfRandoms = 34 or 41 or 48 or 55, 4 options //It means that the probabilities of getting numbers between 0 and 6 are almost equal. int result = sumOfRandoms % 7; //we should add 1 to move the interval [0,6] to the interval [1,7] return 1 + result; } A: Here's mine, this attempts to recreate Math.random() from multiple rand5() function calls, reconstructing a unit interval (the output range of Math.random()) by re-constructing it with "weighted fractions"(?). Then using this random unit interval to produce a random integer between 1 and 7: function rand5(){ return Math.floor(Math.random()*5)+1; } function rand7(){ var uiRandom=0; var div=1; for(var i=0; i<7; i++){ div*=5; var term=(rand5()-1)/div; uiRandom+=term; } //return uiRandom; return Math.floor(uiRandom*7)+1; } To paraphrase: We take a random integers between 0-4 (just rand5()-1) and multiply each result with 1/5, 1/25, 1/125, ... and then sum them together. It's similar to how binary weighted fractions work; I suppose instead, we'll call it a quinary (base-5) weighted fraction: Producing a number from 0 -- 0.999999 as a series of (1/5)^n terms. Modifying the function to take any input/output random integer range should be trivial. And the code above can be optimized when rewritten as a closure. Alternatively, we can also do this: function rand5(){ return Math.floor(Math.random()*5)+1; } function rand7(){ var buffer=[]; var div=1; for (var i=0; i<7; i++){ buffer.push((rand5()-1).toString(5)); div*=5; } var n=parseInt(buffer.join(""),5); var uiRandom=n/div; //return uiRandom; return Math.floor(uiRandom*7)+1; } Instead of fiddling with constructing a quinary (base-5) weighted fractions, we'll actually make a quinary number and turn it into a fraction (0--0.9999... as before), then compute our random 1--7 digit from there. Results for above (code snippet #2: 3 runs of 100,000 calls each): 1: 14263; 2: 14414; 3: 14249; 4: 14109; 5: 14217; 6: 14361; 7: 14387 1: 14205; 2: 14394; 3: 14238; 4: 14187; 5: 14384; 6: 14224; 7: 14368 1: 14425; 2: 14236; 3: 14334; 4: 14232; 5: 14160; 6: 14320; 7: 14293 A: the main conception of this problem is about normal distribution, here provided a simple and recursive solution to this problem presume we already have rand5() in our scope: def rand7(): # twoway = 0 or 1 in the same probability twoway = None while not twoway in (1, 2): twoway = rand5() twoway -= 1 ans = rand5() + twoway * 5 return ans if ans in range(1,8) else rand7() Explanation We can divide this program into 2 parts: * *looping rand5() until we found 1 or 2, that means we have 1/2 probability to have 1 or 2 in the variable twoway *composite ans by rand5() + twoway * 5, this is exactly the result of rand10(), if this did not match our need (1~7), then we run rand7 again. P.S. we cannot directly run a while loop in the second part due to each probability of twoway need to be individual. But there is a trade-off, because of the while loop in the first section and the recursion in the return statement, this function doesn't guarantee the execution time, it is actually not effective. Result I've made a simple test for observing the distribution to my answer. result = [ rand7() for x in xrange(777777) ] ans = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, } for i in result: ans[i] += 1 print ans It gave {1: 111170, 2: 110693, 3: 110651, 4: 111260, 5: 111197, 6: 111502, 7: 111304} Therefore we could know this answer is in a normal distribution. Simplified Answer If you don't care about the execution time of this function, here's a simplified answer based on the above answer I gave: def rand7(): ans = rand5() + (rand5()-1) * 5 return ans if ans < 8 else rand7() This augments the probability of value which is greater than 8 but probably will be the shortest answer to this problem. A: This algorithm reduces the number of calls of rand5 to the theoretical minimum of 7/5. Calling it 7 times by produce the next 5 rand7 numbers. There are no rejection of any random bit, and there are NO possibility to keep waiting the result for always. #!/usr/bin/env ruby # random integer from 1 to 5 def rand5 STDERR.putc '.' 1 + rand( 5 ) end @bucket = 0 @bucket_size = 0 # random integer from 1 to 7 def rand7 if @bucket_size == 0 @bucket = 7.times.collect{ |d| rand5 * 5**d }.reduce( &:+ ) @bucket_size = 5 end next_rand7 = @bucket%7 + 1 @bucket /= 7 @bucket_size -= 1 return next_rand7 end 35.times.each{ putc rand7.to_s } A: Here is a solution that tries to minimize the number of calls to rand5() while keeping the implementation simple and efficient; in particular, it does not require arbitrary large integers unlike Adam Rosenfield’s second answer. It exploits the fact that 23/19 = 1.21052... is a good rational approximation to log(7)/log(5) = 1.20906..., thus we can generate 19 random elements of {1,...,7} out of 23 random elements of {1,...,5} by rejection sampling with only a small rejection probability. On average, the algorithm below takes about 1.266 calls to rand5() for each call to rand7(). If the distribution of rand5() is uniform, so is rand7(). uint_fast64_t pool; int capacity = 0; void new_batch (void) { uint_fast64_t r; int i; do { r = 0; for (i = 0; i < 23; i++) r = 5 * r + (rand5() - 1); } while (r >= 11398895185373143ULL); /* 7**19, a bit less than 5**23 */ pool = r; capacity = 19; } int rand7 (void) { int r; if (capacity == 0) new_batch(); r = pool % 7; pool /= 7; capacity--; return r + 1; } A: For the range [1, 5] to [1, 7], this is equivalent to rolling a 7-sided die with a 5-sided one. However, this can't be done without "wasting" randomness (or running forever in the worst case), since all the prime factors of 7 (namely 7) don't divide 5. Thus, the best that can be done is to use rejection sampling to get arbitrarily close to no "waste" of randomness (such as by batching multiple rolls of the 5-sided die until 5^n is "close enough" to a power of 7). Solutions to this problem were already given in other answers. More generally, an algorithm to roll a k-sided die with a p-sided die will inevitably "waste" randomness (and run forever in the worst case) unless "every prime number dividing k also divides p", according to Lemma 3 in "Simulating a dice with a dice" by B. Kloeckner. For example, take the much more practical case that p is a power of 2 and k is arbitrary. In this case, this "waste" and indefinite running time are inevitable unless k is also a power of 2. A: Python: There's a simple two line answer that uses a combination of spatial algebra and modulus. This is not intuitive. My explanation of it is confusing, but is correct. Knowing that 5*7=35 and 7/5 = 1 remainder 2. How to guarantee that sum of remainders is always 0? 5*[7/5 = 1 remainder 2] --> 35/5 = 7 remainder 0 Imagine we had a ribbon that was wrapped around a pole with a perimeter=7. The ribbon would need to be 35 units to wrap evenly. Select 7 random ribbon pieces len=[1...5]. The effective length ignoring the wrap around is the same as this method of converting rand5() into rand7(). import numpy as np import pandas as pd # display is a notebook function FYI def rand5(): ## random uniform int [1...5] return np.random.randint(1,6) n_trials = 1000 samples = [rand5() for _ in range(n_trials)] display(pd.Series(samples).value_counts(normalize=True)) # 4 0.2042 # 5 0.2041 # 2 0.2010 # 1 0.1981 # 3 0.1926 # dtype: float64 def rand7(): # magic algebra x = sum(rand5() for _ in range(7)) return x%7 + 1 samples = [rand7() for _ in range(n_trials)] display(pd.Series(samples).value_counts(normalize=False)) # 6 1475 # 2 1475 # 3 1456 # 1 1423 # 7 1419 # 4 1393 # 5 1359 # dtype: int64 df = pd.DataFrame([ pd.Series([rand7() for _ in range(n_trials)]).value_counts(normalize=True) for _ in range(1000) ]) df.describe() # 1 2 3 4 5 6 7 # count 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000 # mean 0.142885 0.142928 0.142523 0.142266 0.142704 0.143048 0.143646 # std 0.010807 0.011526 0.010966 0.011223 0.011052 0.010983 0.011153 # min 0.112000 0.108000 0.101000 0.110000 0.100000 0.109000 0.110000 # 25% 0.135000 0.135000 0.135000 0.135000 0.135000 0.135000 0.136000 # 50% 0.143000 0.142000 0.143000 0.142000 0.143000 0.142000 0.143000 # 75% 0.151000 0.151000 0.150000 0.150000 0.150000 0.150000 0.151000 # max 0.174000 0.181000 0.175000 0.178000 0.189000 0.176000 0.179000 A: solution in php <?php function random_5(){ return rand(1,5); } function random_7(){ $total = 0; for($i=0;$i<7;$i++){ $total += random_5(); } return ($total%7)+1; } echo random_7(); ?> A: I have played around and I write "testing environment" for this Rand(7) algorithm. For example if you want to try what distribution gives your algorithm or how much iterations takes to generate all distinct random values (for Rand(7) 1-7), you can use it. My core algorithm is this: return (Rand5() + Rand5()) % 7 + 1; Well is no less uniformly distributed then Adam Rosenfield's one. (which I included in my snippet code) private static int Rand7WithRand5() { //PUT YOU FAVOURITE ALGORITHM HERE// //1. Stackoverflow winner int i; do { i = 5 * (Rand5() - 1) + Rand5(); // i is now uniformly random between 1 and 25 } while (i > 21); // i is now uniformly random between 1 and 21 return i % 7 + 1; //My 2 cents //return (Rand5() + Rand5()) % 7 + 1; } This "testing environment" can take any Rand(n) algorithm and test and evaluate it (distribution and speed). Just put your code into the "Rand7WithRand5" method and run the snippet. Few observations: * *Adam Rosenfield's algorithm is no better distributed then, for example, mine. Anyway, both algorithms distribution is horrible. *Native Rand7 (random.Next(1, 8)) is completed as it generated all members in given interval in around 200+ iterations, Rand7WithRand5 algorithms take order of 10k (around 30-70k) *Real challenge is not to write a method to generate Rand(7) from Rand(5), but it generate values more or less uniformly distributed. A: This is the answer I came up with but these complicated answers are making me think this is completely off/ :)) import random def rand5(): return float(random.randint(0,5)) def rand7(): random_val = rand5() return float(random.randint((random_val-random_val),7)) print rand7() A: int rand7() { int zero_one_or_two = ( rand5() + rand5() - 1 ) % 3 ; return rand5() + zero_one_or_two ; } A: #!/usr/bin/env ruby class Integer def rand7 rand(6)+1 end end def rand5 rand(4)+1 end x = rand5() # x => int between 1 and 5 y = x.rand7() # y => int between 1 and 7 ..although that may possibly be considered cheating.. A: A constant time solution that produces approximately uniform distribution. The trick is 625 happens to be cleanly divisible by 7 and you can get uniform distributions as you build up to that range. Edit: My bad, I miscalculated, but instead of pulling it I'll leave it in case someone finds it useful/entertaining. It does actually work after all... :) int rand5() { return (rand() % 5) + 1; } int rand25() { return (5 * (rand5() - 1) + rand5()); } int rand625() { return (25 * (rand25() - 1) + rand25()); } int rand7() { return ((625 * (rand625() - 1) + rand625()) - 1) % 7 + 1; } A: def rand5(): return random.randint(1,5) #return random integers from 1 to 5 def rand7(): rand = rand5()+rand5()-1 if rand > 7: #if numbers > 7, call rand7() again return rand7() print rand%7 + 1 I guess this will the easiest solution but everywhere people have suggested 5*rand5() + rand5() - 5 like in http://www.geeksforgeeks.org/generate-integer-from-1-to-7-with-equal-probability/. Can someone explain what is wrong with rand5()+rand5()-1 A: // returns random number between 0-5 with equal probability function rand5() { return Math.floor(Math.random() * 6); } // returns random number between 0-7 with equal probability function rand7() { if(rand5() % 2 == 0 && rand5() % 2 == 0) { return 6 + rand5() % 2; } else { return rand5(); } } console.log(rand7()); A: I feel stupid in front of all this complicated answsers. Why can't it be : int random1_to_7() { return (random1_to_5() * 7) / 5; } ?
{ "language": "en", "url": "https://stackoverflow.com/questions/137783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "715" }
Q: SSRS: Change SQL Statement Dynamically I have a report in SSRS 2005 that's based on a query that's similar to this one: SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND col2 LIKE '%XYZ%' I need to be able to dynamically include the AND part of the WHERE clause in the query based on whether the user has checked a checkbox. Basically, this is a dynamic SQL statement and that's the problem. I tried several approaches to no avail. Is this possible? Does SSRS 2005 supports dynamic SQL? Thanks! A: How about this. @checked is your bit variable. SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND (@checked <> 0 and col2 LIKE '%XYZ%') Edit: Also, if you aren't using a stored proc, then use one. A: Charles almost had the correct answer. It should be: SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND (@checked = 0 OR col2 LIKE '%XYZ%') This is a classic "pattern" in SQL for conditional predicates. If @checked = 0, then it will return all rows matching the remainder of the predicate (col1 = 'ABC'). SQL Server won't even process the second half of the OR. If @checked = 1 then it will evaluate the second part of the OR and return rows matching col1 = 'ABC' AND col2 LIKE '%XYZ%' If you have multiple conditional predicates they can be chained together using this method (while the IF and CASE methods would quickly become unmanageable). For example: SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND (@checked1 = 0 OR col2 LIKE '%XYZ%') AND (@checked2 = 0 OR col3 LIKE '%MNO%') Don't use dynamic SQL, don't use IF or CASE. A: Perhaps this would work for you: if @checked = 1 select * from mytable (nolock) where col = 'ABC' else select * from mytable (nolock) where col = 'ABC' AND colw Like '%XYZ%' I'm sorry I don't use SSRS much, but if you can get the value of the checkbox into the @checked parameter this should work. Alternately you could use a CASE WHEN statement. A: SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND col2 LIKE CASE @checked WHEN 1 THEN '%XYZ%' ELSE col2 END A: This would work in SSRS 2000 but used as a last resort. (bad) PSEUDOCODE ="SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC'"+ iff(condition,true,"AND col2 LIKE '%XYZ%'","") Check out Executing "Dynamic" SQL Queries. from the Hitchhiker's Guide to SQL Server 2000 Reporting Services A: One way to do this is by generating the SSRS query as an expression. In the BIDS report designer, set your query up like so: ="SELECT * FROM MyTable WITH (NOLOCK) WHERE col1 = 'ABC'" + Iif(Parameters!Checked.Value = true," AND col2 LIKE '%XYZ%'","") A: You can also take another approach and use the Exec function: DECLARE @CommonSelectText varchar(2000) DECLARE @CompleteSelectText varchar(2000) SELECT @CommonSelectText = 'SELECT * FROM MyTable (nolock) Where Col = ''ABC'' ' IF @checked = 1 SELECT @CompleteSelectText = @CommonSelectText + ' AND ColW LIKE ''%XYZ%'' ' ELSE SELECT @CompleteSelectText = @CommonSelectText EXEC (@CompleteSelectText) GO Note the use of two apostrophes ' to mark the quoted text. A: if you can use stored procedures, its probably easier to do it there. pass in your params. Create a SQL String based on your conditions and do an EXEC on the sql string, your stored proc will return the results you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/137784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Suggestions on using Flex with WCF and Linq to Entities So I am working on a project that uses a ASP.NET server and we have entities being passed over WCF from LINQ-to-Entity queries. I have already overcome the cyclic reference issue with WCF. Now that I am looking toward the next step, the Flex UI, I am wondering what things people have already faced either with dealing with WCF from Flex or using Entities with Flex (Entities from the entity framework)? And Flex suggestions, libraries, patterns and tips would help. Thanks. Things that would help: * *How to "persist" or dupe entities on the UI side. *Security, how to secure communication from the UI to the service. *How to generate/pass new entities from the UI to the service and have then interprete as .NET entities A: I would check out Fluorine FX. It is a very mature and stable AMF implementation for .NET and it does provide WCF integration. A colleague of mine has posted some information here: http://jimdonaghy.com/?p=11 A: You have several options for communicating between Flex application and your WCF service. Flex supports both SOAP web services and REST-like web services so you can choose which approach fits you best. When you receive data on the client, you will need to extract the entities from the response and build the UI accordingly. Similar with updating or creating new entities - you will need to construct a web service request from your user interface controls and send it over the wire. Also look into AMF which is a binary format for communicating between Flex/Flash and a server. There are .NET implementations out there (AMF.NET for instance) so it may be possible to somehow make it work with WCF - you need to explore this area yourself, I have no direct experience here. A: http://jimdonaghy.com?p=11 seems to be broken but here is a link to FluorineFX if you lazy to google. http://www.fluorinefx.com/ I recommend AMF over REST or SOAP because AMF is a bianry protocol which has great performance gains. On the other hand if you do plan on opening your services to other types of ui clients then by all means use REST.
{ "language": "en", "url": "https://stackoverflow.com/questions/137793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL SERVER, SELECT statement with auto generate row id Does anyone happen to remember the function name used to generate sequential row number built-in SQL Server 2000. A: If you are making use of GUIDs this should be nice and easy, if you are looking for an integer ID, you will have to wait for another answer. SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1 The newId() will generate a new GUID for you that you can use as your automatically generated id column. A: Here is a simple method which ranks the rows after however they are ordered, i.e. inserted in your table. In your SELECT statement simply add the field ROW_NUMBER() OVER (ORDER BY CAST(GETDATE() AS TIMESTAMP)) AS RowNumber. A: This will work in SQL Server 2008. select top 100 ROW_NUMBER() OVER (ORDER BY tmp.FirstName) ,* from tmp Cheers A: IDENTITY(int, 1, 1) should do it if you are doing a select into. In SQL 2000, I use to just put the results in a temp table and query that afterwords. A: Do you want an incrementing integer column returned with your recordset? If so: - --Check for existance if exists (select * from dbo.sysobjects where [id] = object_id(N'dbo.t') AND objectproperty(id, N'IsUserTable') = 1) drop table dbo.t go --create dummy table and insert data create table dbo.t(x char(1) not null primary key, y char(1) not null) go set nocount on insert dbo.t (x,y) values ('A','B') insert dbo.t (x,y) values ('C','D') insert dbo.t (x,y) values ('E','F') --create temp table to add an identity column create table dbo.#TempWithIdentity(i int not null identity(1,1) primary key,x char(1) not null unique,y char(1) not null) --populate the temporary table insert into dbo.#TempWithIdentity(x,y) select x,y from dbo.t --return the data select i,x,y from dbo.#TempWithIdentity --clean up drop table dbo.#TempWithIdentity A: Is this perhaps what you are looking for? select NEWID() * from TABLE A: You can do this directly in SQL2000, as per Microsoft's page: http://support.microsoft.com/default.aspx?scid=kb;en-us;186133 select rank=count(*), a1.au_lname, a1.au_fname from authors a1, authors a2 where a1.au_lname + a1.au_fname >= a2.au_lname + a2.au_fname group by a1.au_lname, a1.au_fname order by rank The only problem with this approach is that (As Jeff says on SQL Server Central) it's a triangular join. So, if you have ten records this will be quick, if you have a thousand records it will be slow, and with a million records it may never complete! See here for a better explanation of triangular joins: http://www.sqlservercentral.com/articles/T-SQL/61539/ A: Select (Select count(y.au_lname) from dbo.authors y where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid, x.au_lname,x.au_fname from authors x group by au_lname,au_fname order by Counterid --Alternatively that can be done which is equivalent as above.. A: If you are looking for an integer id This has worked for me: SELECT ROW_NUMBER() OVER (ORDER BY newId()) FROM anyTbl
{ "language": "en", "url": "https://stackoverflow.com/questions/137803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: What's your favorite C++0x feature? As many of us know (and many, many more don't), C++ is currently undergoing final drafting for the next revision of the International Standard, expected to be published in about 2 years. Drafts and papers are currently available from the committee website. All sorts of new features are being added, the biggest being concepts and lambdas. There is a very comprehensive Wikipedia article with many of the new features. GCC 4.3 and later implement some C++0x features. As far as new features go, I really like type traits (and the appropriate concepts), but my definite leader is variadic templates. Until 0x, long template lists have involved Boost Preprocessor usually, and are very unpleasant to write. This makes things a lot easier and allows C++0x templates to be treated like a perfectly functional language using variadic templates. I've already written some very cool code with them already, and I can't wait to use them more often! So what features are you most eagerly anticipating? A: It's not big, but I'm loving the idea of a true nullptr. Should have been a keyword right from the git-go. A: Closures for me. A: auto keyword A: auto keyword for variable type inferencing A: Lambdas and Concepts A: The for (auto x : collection) iteration syntax is way cool I think... it literally cuts down the size of many loop headers by a factor of 4 or more (iterator types are often ... verbose)! It also means you don't have to dereference the iterator in the body of the loop (with a traditional iterator loop, you always have to use *i or i->... to get the value of the element, but here you can just use x), which in some cases makes the code look much nicer. A: unicode, multithreading, hash_tables, smart pointers and regular expressions. ps : Wonder why they just cant do a gr8 code review and accept all the boost and tr1 libs into the standards and make life easier for everyone. All they would then have to solve is agreeing on a working optional garbage collection model. A: Angle bracket in nested template declarations. So I will be able to write std::vector<std::vector<int>> a; instead of the horrible std::vector<std::vector<int> > a; A: Lambdas and initializer lists. Also, the changes to make it easier to eventually bring C++ into a garbage collected model, those seem pretty interesting. Perhaps C++1x will actually bring in garbage collection, but 0x/10 just set things up for the eventuality. A: The syntax going from bad to worse. Variadic templates and lambdas are nice, though the syntax of both is unfortunately pretty objectionable. A: Smart pointers. It really makes a world of difference not having to explicitly memory-manage heap-allocated objects. Obviously you still need to "know what you're doing", but in my experience it has decreased the number of memory-related bugs at least one order of magnitude in software I've worked with. A: I want Rvalues references. All the other new features are stuff that we could easily live without(alas features). However the lack of Rvalues in C++ so far has caused hundreds of template library authors to have to "hack" around the broken Rvalue ref issue. A: Variadic templates! (Which combined with r-value references gives us perfect forwarding!) A: I like constexpr especially in conjunction with variadic templates and user defined literals we can finally have binary literals and lots of other goodies. obj.bitmask |= 00001010B; A: decltype :-) and lambdas A: Threads and atomics. With multicore processors now the norm C++0x should have been C++07. G. A: Strongly Typed enums get my vote. Pascal has only had these for around 40 years, so it's good to see C++ finally catching up. However, the publication of the standard is really a non-event. What's much more important is when the features you want to use are actually fully and reliably supported with real-world toolchains. There are folk that seem to actually enjoy writing standards-compliant code that fails to compile on any known compiler. Good luck to them. A: * *It has to be the incorporation of some of the Boost libraries (shared_ptr<> and bind top the list) *Control over template instatntiation should finally solve the issue of the enormous compile times and make it actually feasible to use modern template code in large projects. *Template typedefs Lots of other small but important things, but they do matter in production code. A: Hands down concepts for me. But initializer lists, lambdas, and variadic templates are a close second. A: I can't decide between Null Pointer Type, Tuple Types, or Regex. 'Foreach' is up there too. 'Smart Pointers' goes without saying... :-) Basically, I'm really looking forward to the update. Personally I think heavy use of the null pointer type is going to catch a lot of bugs. Tuples are great for dealing with relational data. Lots of cool stuff. A: REGEX!! and parallel programming librarys though I don't know the features of them all yet. A: Raw string literals! I thought that python-like string blocks were awesome, but I was wrong! In C++0x raw string literals are incredibly useful for text formatting. Markup languages can be wrote directly in your source! A: for the moment I have liked much of C++0x that I have played with: * *nullptr *static_assert *lambdas *shared_ptr and weak_ptr *unique_ptr *decltype and auto I havent tried <regexp>... I thought it was a huge idea... but I didn't even take the time to look at it.
{ "language": "en", "url": "https://stackoverflow.com/questions/137812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: Can Windows PE 2.0 support the .NET framework? I'm interested in building a PC for a car that will boot off of a USB flash drive. I'm planning on using Windows PE 2.0 for it with the GUI being written in C# or VB.NET. Obviously, for this to work, I'd need to have .NET 2.0 or later installed. Understanding that .NET is not included by default, is there a way to package .NET 2.0 with Windows PE 2.0 in such a way as to allow my GUI application to work? A: Windows PE does not support the Microsoft .NET Framework or the Common Language Runtime (CLR). Source: What is Windows PE? (MSDN). A: Not sure if this will help you, but here's a .NET 2.0 plug-in which requires "PE Builder 3.x or Microsoft Windows PE 2004 or 2005".
{ "language": "en", "url": "https://stackoverflow.com/questions/137817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: newline character(s) Does your software handle newline characters from other systems? Linux/BSD linefeed ^J 10 x0A Windows/IBM return linefeed ^M^J 13 10 x0D x0A old Macs return ^M 13 x0D others? For reasons of insanity, I am going with using the Linux version of the newline character in my text files. But, when I bring my text files over to say Windows, some programs do not play nicely with newline characters in my text. How would you deal with this? A: As they say, be strict in what you write and liberal in what you read. Your application should be able to work properly reading both line endings. If you want to use linefeeds, and potentially upset Windows users, that's fine. But save for Notepad, most programs I play with seem to be happy with both methods. (And I use Cygwin on Windows, which just makes everything interesting) A: The standard Python distribution comes with two command-line scripts (in Tools/scripts) called crlf.py and lfcr.py that can convert between Windows and Unix/Linux line endings. [Source] A: In .NET, new lines are denoted by Environment.NewLine, so the framework is designed in such a way as to take whatever the system's new line is (CR+LF or CR only or LF only) to use at runtime. Of course this is ultimately useful in Mono. A: I suspect you will find that most modern Windows programs (with the notable exception of Notepad) handle newline-only files just fine. However, files generated with windows programs still tend to have crlf endings. Most of the time, the line endings will automatically be handled in a platform-specific way by the runtime library. For example, a C program that opens a file with fopen(..., "r") will see the lines in a consistent way (linefeed only) on any platform regardless of the actual line endings. A: As far as I know, it's only Notepad that has a problem with line separators. Virtually ever other piece of software in the world accepts any of those three types of separator, and possibility others as well. Unfortunately, Notepad is the editor of first resort for most computer users these days. I think it's extremely irresponsible of Microsoft to let this situation continue. I've never played with Vista, but I believe the problem still exists there, as it does in XP. Any body know about the next version? A: As others said, there are lot of (quite trivial) converters around, should the need arise. Note that if you do the transfer with FTP in Ascii mode, it will do the conversion automatically... Indeed, Notepad is the most proeminent program having an issue with LF ending... The most annoying I saw is text files with mixed line ending, done essentially by people editing a Windows file on Unix, or utilities adding stuff without checking the proper format. A: To be happy, just follow recommendation from the standard. http://unicode.org/standard/reports/tr13/tr13-5.html And offer options for special cases like old MacOS. Or handle the case automatically if you can detect them reliably. I recommend formatting your text in Unix style. Forget about Windows users. Because no Windows users use plain-text for document or data. They will be upset if you pass plain-text. They always expect Word or Excel document. Even they use plain-text file, the only problem they will get is just weirdly displaying text. But Unix users will experience their all tools will work incorrectly. Especially for Unix, follow the standard strictly. PS. Oh, if your Windows user is a developer, just format with text in Unix, and tell them that's the file from Unix. A: Not sure what you mean when you say 'deal' with, but basically you can just say something like: string convertLineBreaks(String line, String lineBreakYouWant) { replace all ^M^J or ^M or ^J in line with lineBreakYouWant return line } Edit: I suspect after re-reading your question you mean how do you deal with other peoples programs that can't handle incorrect (for the target system) line breaks. I would suggest either 1) using a program that can deal or 2) running your files through a script that finds line breaks of any type and then converts them into whatever type is right for your system.
{ "language": "en", "url": "https://stackoverflow.com/questions/137837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Moving WCF service from IIS to a Windows service We have an existing WCF service that makes use of wsDualHttpBinding to enable callbacks to the client. I am considering moving it to netTcpBinding for better performance, but I'm quite wary of moving away from the IIS-hosted service (a "comfort zone" we currently enjoy) into having our own Windows service to host it. I was hoping we could still host this on IIS 7 but Win2K8 won't be reality for us for some time. What things should I watch out for when creating our own Windows service to host our WCF service? Things like lifetime management and request throttling are features that come free with IIS hosting so I'd also like to know how we can effectively host our service on our own without the convenience of having IIS do the hard work for us. Thanks! :) A: Hosting in a Windows Service Application (http://msdn.microsoft.com/en-us/library/ms734781.aspx) is a good start. If you can host your service on Vista, you can also benefit from Windows Process Activation Service (WAS). WAS is a generalization of the IIS process activation, which can be used to activate processes over non-HTTP endpoints (TCP, Named Pipe, MSMQ). To learn more about WCF hosted in WAS, read http://msdn.microsoft.com/en-us/library/ms733109.aspx. To learn how to install and configure WAS, read http://msdn.microsoft.com/en-us/library/ms731053.aspx. A: So as you cannot host using WAS there are a couple of things to realise. * *If the service crashes it doesn't restart by default (although you can change this in service properties) *IIS will recycle the application pool if it hangs or grows too big; you must do this yourself if you want the same sort of reliability. *You must create an account for the service to run under, or use one of the default services. Resit the temptation to run the service as SYSTEM or under an administrator account; if you want to use a built in account use NETWORK SERVICE. *It becomes harder to debug in situ. *Consider using a error logger such as log4net Having said that I deployed a WCF/Windows service combination for a customer 9 months ago; it's heavily used and hasn't died once. You can request throttle in a Windows service, it's part of the WCF configuration. Note the defaults are very low, it is likely you will have to increase these.
{ "language": "en", "url": "https://stackoverflow.com/questions/137840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Determining whether an object is a member of a collection in VBA How do I determine whether an object is a member of a collection in VBA? Specifically, I need to find out whether a table definition is a member of the TableDefs collection. A: Isn't it good enough? Public Function Contains(col As Collection, key As Variant) As Boolean Dim obj As Variant On Error GoTo err Contains = True obj = col(key) Exit Function err: Contains = False End Function A: Not exactly elegant, but the best (and quickest) solution i could find was using OnError. This will be significantly faster than iteration for any medium to large collection. Public Function InCollection(col As Collection, key As String) As Boolean Dim var As Variant Dim errNumber As Long InCollection = False Set var = Nothing Err.Clear On Error Resume Next var = col.Item(key) errNumber = CLng(Err.Number) On Error GoTo 0 '5 is not in, 0 and 438 represent incollection If errNumber = 5 Then ' it is 5 if not in collection InCollection = False Else InCollection = True End If End Function A: You can shorten the suggested code for this as well as generalize for unexpected errors. Here you go: Public Function InCollection(col As Collection, key As String) As Boolean On Error GoTo incol col.Item key incol: InCollection = (Err.Number = 0) End Function A: Your best bet is to iterate over the members of the collection and see if any match what you are looking for. Trust me I have had to do this many times. The second solution (which is much worse) is to catch the "Item not in collection" error and then set a flag to say the item does not exist. A: This is an old question. I have carefully reviewed all the answers and comments, tested the solutions for performance. I came up with the fastest option for my environment which does not fail when a collection has objects as well as primitives. Public Function ExistsInCollection(col As Collection, key As Variant) As Boolean On Error GoTo err ExistsInCollection = True IsObject(col.item(key)) Exit Function err: ExistsInCollection = False End Function In addition, this solution does not depend on hard-coded error values. So the parameter col As Collection can be substituted by some other collection type variable, and the function must still work. E.g., on my current project, I will have it as col As ListColumns. A: In your specific case (TableDefs) iterating over the collection and checking the Name is a good approach. This is OK because the key for the collection (Name) is a property of the class in the collection. But in the general case of VBA collections, the key will not necessarily be part of the object in the collection (e.g. you could be using a Collection as a dictionary, with a key that has nothing to do with the object in the collection). In this case, you have no choice but to try accessing the item and catching the error. A: I created this solution from the above suggestions mixed with microsofts solution of for iterating through a collection. Public Function InCollection(col As Collection, Optional vItem, Optional vKey) As Boolean On Error Resume Next Dim vColItem As Variant InCollection = False If Not IsMissing(vKey) Then col.item vKey '5 if not in collection, it is 91 if no collection exists If Err.Number <> 5 And Err.Number <> 91 Then InCollection = True End If ElseIf Not IsMissing(vItem) Then For Each vColItem In col If vColItem = vItem Then InCollection = True GoTo Exit_Proc End If Next vColItem End If Exit_Proc: Exit Function Err_Handle: Resume Exit_Proc End Function A: I have some edit, best working for collections: Public Function Contains(col As collection, key As Variant) As Boolean Dim obj As Object On Error GoTo err Contains = True Set obj = col.Item(key) Exit Function err: Contains = False End Function A: For the case when key is unused for collection: Public Function Contains(col As Collection, thisItem As Variant) As Boolean Dim item As Variant Contains = False For Each item In col If item = thisItem Then Contains = True Exit Function End If Next End Function A: It requires some additional adjustments in case the items in the collection are not Objects, but Arrays. Other than that it worked fine for me. Public Function CheckExists(vntIndexKey As Variant) As Boolean On Error Resume Next Dim cObj As Object ' just get the object Set cObj = mCol(vntIndexKey) ' here's the key! Trap the Error Code ' when the error code is 5 then the Object is Not Exists CheckExists = (Err <> 5) ' just to clear the error If Err <> 0 Then Call Err.Clear Set cObj = Nothing End Function Source: http://coderstalk.blogspot.com/2007/09/visual-basic-programming-how-to-check.html A: this version works for primitive types and for classes (short test-method included) ' TODO: change this to the name of your module Private Const sMODULE As String = "MVbaUtils" Public Function ExistsInCollection(oCollection As Collection, sKey As String) As Boolean Const scSOURCE As String = "ExistsInCollection" Dim lErrNumber As Long Dim sErrDescription As String lErrNumber = 0 sErrDescription = "unknown error occurred" Err.Clear On Error Resume Next ' note: just access the item - no need to assign it to a dummy value ' and this would not be so easy, because we would need different ' code depending on the type of object ' e.g. ' Dim vItem as Variant ' If VarType(oCollection.Item(sKey)) = vbObject Then ' Set vItem = oCollection.Item(sKey) ' Else ' vItem = oCollection.Item(sKey) ' End If oCollection.Item sKey lErrNumber = CLng(Err.Number) sErrDescription = Err.Description On Error GoTo 0 If lErrNumber = 5 Then ' 5 = not in collection ExistsInCollection = False ElseIf (lErrNumber = 0) Then ExistsInCollection = True Else ' Re-raise error Err.Raise lErrNumber, mscMODULE & ":" & scSOURCE, sErrDescription End If End Function Private Sub Test_ExistsInCollection() Dim asTest As New Collection Debug.Assert Not ExistsInCollection(asTest, "") Debug.Assert Not ExistsInCollection(asTest, "xx") asTest.Add "item1", "key1" asTest.Add "item2", "key2" asTest.Add New Collection, "key3" asTest.Add Nothing, "key4" Debug.Assert ExistsInCollection(asTest, "key1") Debug.Assert ExistsInCollection(asTest, "key2") Debug.Assert ExistsInCollection(asTest, "key3") Debug.Assert ExistsInCollection(asTest, "key4") Debug.Assert Not ExistsInCollection(asTest, "abcx") Debug.Print "ExistsInCollection is okay" End Sub A: It works for me Public Function contains(col As Collection, key As Variant) As Boolean For Each element In col If (element = key) Then contains = True Exit Function End If Next contains = False End Function A: Not my code, but I think it's pretty nicely written. It allows to check by the key as well as by the Object element itself and handles both the On Error method and iterating through all Collection elements. https://danwagner.co/how-to-check-if-a-collection-contains-an-object/ I'll not copy the full explanation since it is available on the linked page. Solution itself copied in case the page eventually becomes unavailable in the future. The doubt I have about the code is the overusage of GoTo in the first If block but that's easy to fix for anyone so I'm leaving the original code as it is. ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 'INPUT : Kollection, the collection we would like to examine ' : (Optional) Key, the Key we want to find in the collection ' : (Optional) Item, the Item we want to find in the collection 'OUTPUT : True if Key or Item is found, False if not 'SPECIAL CASE: If both Key and Item are missing, return False Option Explicit Public Function CollectionContains(Kollection As Collection, Optional Key As Variant, Optional Item As Variant) As Boolean Dim strKey As String Dim var As Variant 'First, investigate assuming a Key was provided If Not IsMissing(Key) Then strKey = CStr(Key) 'Handling errors is the strategy here On Error Resume Next CollectionContains = True var = Kollection(strKey) '<~ this is where our (potential) error will occur If Err.Number = 91 Then GoTo CheckForObject If Err.Number = 5 Then GoTo NotFound On Error GoTo 0 Exit Function CheckForObject: If IsObject(Kollection(strKey)) Then CollectionContains = True On Error GoTo 0 Exit Function End If NotFound: CollectionContains = False On Error GoTo 0 Exit Function 'If the Item was provided but the Key was not, then... ElseIf Not IsMissing(Item) Then CollectionContains = False '<~ assume that we will not find the item 'We have to loop through the collection and check each item against the passed-in Item For Each var In Kollection If var = Item Then CollectionContains = True Exit Function End If Next var 'Otherwise, no Key OR Item was provided, so we default to False Else CollectionContains = False End If End Function A: i used this code to convert array to collection and back to array to remove duplicates, assembled from various posts here (sorry for not giving properly credit). Function ArrayRemoveDups(MyArray As Variant) As Variant Dim nFirst As Long, nLast As Long, i As Long Dim item As Variant, outputArray() As Variant Dim Coll As New Collection 'Get First and Last Array Positions nFirst = LBound(MyArray) nLast = UBound(MyArray) ReDim arrTemp(nFirst To nLast) i = nFirst 'convert to collection For Each item In MyArray skipitem = False For Each key In Coll If key = item Then skipitem = True Next If skipitem = False Then Coll.Add (item) Next item 'convert back to array ReDim outputArray(0 To Coll.Count - 1) For i = 1 To Coll.Count outputArray(i - 1) = Coll.item(i) Next ArrayRemoveDups = outputArray End Function A: I did it like this, a variation on Vadims code but to me a bit more readable: ' Returns TRUE if item is already contained in collection, otherwise FALSE Public Function Contains(col As Collection, item As String) As Boolean Dim i As Integer For i = 1 To col.Count If col.item(i) = item Then Contains = True Exit Function End If Next i Contains = False End Function A: I wrote this code. I guess it can help someone... Public Function VerifyCollection() For i = 1 To 10 Step 1 MyKey = "A" On Error GoTo KillError: Dispersao.Add 1, MyKey GoTo KeepInForLoop KillError: 'If My collection already has the key A Then... count = Dispersao(MyKey) Dispersao.Remove (MyKey) Dispersao.Add count + 1, MyKey 'Increase the amount in relationship with my Key count = Dispersao(MyKey) 'count = new amount On Error GoTo -1 KeepInForLoop: Next End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/137845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "71" }
Q: Running Apache without explicitly declaring listening on ports such as :3000 or :6600 Using Ruby and Thin as a web service. Apache is also loaded. Can't access the web service because listing ports, such as :3000 or :6600, in the GET url is not allowed. How is the port requirement removed? A: Use Apache ProxyPass. cd /etc/apache2/sites-enabled/ sudo vi 000-default Edit Lines: ServerAdmin webmaster@localhost ProxyPass /breakfast http://localhost:4567/breakfast DocumentRoot /var/www sudo /etc/init.d/apache2 restart A: If you're talking about Apache HTTPD, either leave off the port, or specify "80" for the port. If you're talking about Apache Tomcat, you'll need to set up an HTTP Connector with port=80, but Tomcat will need to be launched as root.
{ "language": "en", "url": "https://stackoverflow.com/questions/137849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using the "final" modifier whenever applicable in Java In Java, there is a practice of declaring every variable (local or class), parameter final if they really are. Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked. What are your thoughts on this and what do you follow? A: Final should always be used for constants. It's even useful for short-lived variables (within a single method) when the rules for defining the variable are complicated. For example: final int foo; if (a) foo = 1; else if (b) foo = 2; else if (c) foo = 3; if (d) // Compile error: forgot the 'else' foo = 4; else foo = -1; A: Sounds like one of the biggest argument against using the final keyword is that "it's unnecessary", and it "wastes space". If we acknowledge the many benefits of "final" as pointed out by many great posts here, while admitting it takes more typing and space, I would argue that Java should have made variables "final" by default, and require that things be marked "mutable" if the coder wants it to be. A: I use final all the time for object attributes. The final keyword has visibility semantics when used on object attributes. Basically, setting the value of a final object attribute happens-before the constructor returns. This means that as long as you don't let the this reference escape the constructor and you use final for all you attributes, your object is (under Java 5 semantics) guarenteed to be properly constructed, and since it is also immutable it can be safely published to other threads. Immutable objects is not just about thread-safety. They also make it a lot easier to reason about the state transitions in your program, because the space of what can change is deliberately and, if used consistently, thoroughly limited to only the things that should change. I sometimes also make methods final, but not as often. I seldomly make classes final. I generally do this because I have little need to. I generally don't use inheritance much. I prefer to use interfaces and object composition instead - this also lends itself to a design that I find is often easier to test. When you code to interfaces instead of concrete classes, then you don't need to use inheritance when you test, as it is, with frameworks such as jMock, much easier to create mock-objects with interfaces than it is with concrete classes. I guess I should make the majority of my classes final, but I just haven't gotten into the habbit yet. A: I have to read a lot of code for my job. Missing final on instance variables is one of the top things to annoy me and makes understanding the code unnecessarily difficult. For my money, final on local variables causes more clutter than clarity. The language should have been designed to make that the default, but we have to live with the mistake. Sometimes it is useful particularly with loops and definite assignment with an if-else tree, but mostly it tends to indicate your method is too complicated. A: You really need to understand the full use of the final keyword before using it. It can apply to and has differing affects on variables, fields, methods and classes I’d recommend checking out the article linked to below for more details. Final Word On the final Keyword A: final should obviously be used on constants, and to enforce immutability, but there is another important use on methods. Effective Java has a whole item on this (Item 15) pointing out the pitfalls of unintended inheritance. Effectively if you didn't design and document your class for inheritance, inheriting from it can give unexpected problems (the item gives a good example). The recommendation therefore is that you use final on any class and/or method that wasn't intended to be inherited from. That may seem draconian, but it makes sense. If you are writing a class library for use by others then you don't want them inheriting from things that weren't designed for it - you will be locking yourself into a particular implementation of the class for back compatibility. If you are coding in a team there is nothing to stop another member of the team from removing the final if they really have to. But the keyword makes them think about what they are doing, and warns them that the class they are inheriting from wasn't designed for it, so they should be extra careful. A: Another caveat is that many people confuse final to mean that the contents of the instance variable cannot change, rather than that the reference cannot change. A: The final modifier, especially for variables, is a means to have the compiler enforce a convention that is generally sensible: make sure a (local or instance) variable is assigned exactly once (no more no less). By making sure a variable is definitely assigned before it is used, you can avoid common cases of a NullPointerException: final FileInputStream in; if(test) in = new FileInputStream("foo.txt"); else System.out.println("test failed"); in.read(); // Compiler error because variable 'in' might be unassigned By preventing a variable from being assigned more than once, you discourage overbroad scoping. Instead of this: String msg = null; for(int i = 0; i < 10; i++) { msg = "We are at position " + i; System.out.println(msg); } msg = null; You are encouraged to use this: for(int i = 0; i < 10; i++) { final String msg = "We are at position " + i; System.out.println(msg); } Some links: * *The final story (free chapter of the book "Hardcore Java") *Some final patterns *Definite assignment A: I'm pretty dogmatic about declaring every possible variable final. This includes method parameters, local variables, and rarely, value object fields. I've got three main reasons for declaring final variables everywhere: * *Declaring Intention: By declaring a final variable, I am stating that this variable is meant to be written to only once. It's a subtle hint to other developers, and a big hint to the compiler. *Enforcing Single-use Variables: I believe in the idea that each variable should have only one purpose in life. By giving each variable only one purpose, you reduce the time it takes to grok the purpose of that particular variable while debugging. *Allows for Optimization: I know that the compiler used to have performance enhancement tricks which relied specifically on the immutability of a variable reference. I like to think some of these old performance tricks (or new ones) will be used by the compiler. However, I do think that final classes and methods are not nearly as useful as final variable references. The final keyword, when used with these declarations simply provide roadblocks to automated testing and the use of your code in ways that you could have never anticipated. A: I think it all has to do with good coding style. Of course you can write good, robust programs without using a lot of final modifiers anywhere, but when you think about it... Adding final to all things which should not change simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code. At least it should ring some bells when they now want to change your previously immutable thing. At first, it kind of looks awkward to see a lot of final keywords in your code, but pretty soon you'll stop noticing the word itself and will simply think, that-thing-will-never-change-from-this-point-on (you can take it from me ;-) I think it's good practice. I am not using it all the time, but when I can and it makes sense to label something final I'll do it. A: Obsess over: * *Final fields - Marking fields as final forces them to be set by end of construction, making that field reference immutable. This allows safe publication of fields and can avoid the need for synchronization on later reads. (Note that for an object reference, only the field reference is immutable - things that object reference refers to can still change and that affects the immutability.) *Final static fields - Although I use enums now for many of the cases where I used to use static final fields. Consider but use judiciously: * *Final classes - Framework/API design is the only case where I consider it. *Final methods - Basically same as final classes. If you're using template method patterns like crazy and marking stuff final, you're probably relying too much on inheritance and not enough on delegation. Ignore unless feeling anal: * *Method parameters and local variables - I RARELY do this largely because I'm lazy and I find it clutters the code. I will fully admit that marking parameters and local variables that I'm not going to modify is "righter". I wish it was the default. But it isn't and I find the code more difficult to understand with finals all over. If I'm in someone else's code, I'm not going to pull them out but if I'm writing new code I won't put them in. One exception is the case where you have to mark something final so you can access it from within an anonymous inner class. A: Even for local variables, knowing that it is declared final means that I don't need to worry about the reference being changed later on. This means that when debugging and I see that variable later on, I am confident that it is referring to the same object. That is one less thing I need to worry about when looking for a bug. A bonus is that if 99% of variables are declared final, then the few variables which really are variable stand out better. Also, the final lets the compiler find some more possible stupid mistakes that might otherwise go unnoticed. A: Choosing to type final for each parameter in each method will produce so much irritation both for coders and code readers. Once irritation goes beyond reasonable switch to Scala where arguments are final by default. Or, you can always use code styling tools that will do that automatically for you. All IDEs have them implemented or as plugins. A: Effective Java has an item that says "Favour immutable objects". Declaring fields as final helps you take some small steps towards this, but there is of course much more to truly immutable objects than that. If you know that objects are immutable they can be shared for reading among many threads/clients without synchronization worries, and it is easier to reason about how the program runs. A: I have never been in a situation where having a final keyword on a variable has stopped me from making a mistake, so for the moment I think it's a giant waste of time. Unless there is a real reason for doing it (as in you want to make a specific point about that variable being final) I would rather not do it since I find it makes the code less readable. If, however, you don't find it makes the code harder to read or longer to write then by all means go for it. Edit: As a clarification (and an attempt to win back down-votes), I'm not saying don't mark constants as final, I'm saying don't do stuff like: public String doSomething() { final String first = someReallyComplicatedExpressionToGetTheString(); final String second = anotherReallyComplicatedExpressionToGetAnother(); return first+second; } It just makes code (in my opinion) harder to read. It's also worth remembering that all final does is prevent you from reassigning a variable, it doesn't make it immutable or anything like that. A: Final when used with variables in Java provides a substitute for constant in C++. So when final and static is used for a variable it becomes immutable. At the same time makes migrated C++ programmers pretty happy ;-) When used with reference variables it does not allow you to re-reference the object, though the object can be manipulated. When final is used with a method, it does not allow the method to be over-ridden by the subclasses. Once the usage is very clear it should be used with care. It mainly depends on the design as using final on the method would not help polymorphism. One should only use it for variables when you are damn sure that the value of the variable will/should never be changed. Also ensure that you follow the coding convention encouraged by SUN.for eg: final int COLOR_RED = 1; (Upper case seperated by underscore) With a reference variable, use it only when we need a an immutable reference to a particular object. Regarding the readability part, ensue that comments play a very important role when using the final modifier. A: I never use them on local variables, there is little point for the added verbosity. Even if you don't think the variable should be reassigned, that will make little difference to the next person altering that code that thinks otherwise, and since the code is being changed, any original purpose for making it final may no longer be valid. If it is just for clarity, I believe it fails due to the negative effects of the verbosity. Pretty much the same applies to member variables as well, as they provide little benefit, except for the case of constants. It also has no bearing on immutability, as the best indicator of something being immutable is that it is documented as such and/or has no methods that can alter the object (this, along with making the class final is the only way to guarantee that it is immutable). But hey, that's just my opinion :-) A: I set up Eclipse to add final on all fields and attributes which are not modified. This works great using the Eclipse "save actions" which adds these final modifiers (among other things) when saving the file. Highly recommended. Check out my blog post of Eclipse Save Actions. A: For arguments I'm think they're not needed. Mostley they just hurt readabillity. Rreassigning an argument variable is so insanely stupid that I should be pretty confident that they can be treated as constants anyway. The fact that Eclipse colors final red makes it easier to spot variable declarations in the code which I think improves readbillity most of the time. I try to enforce the rule that any and all variables should be final it there isn't an extremley valid reason not to. It's so much easier to answer the "what is this variable?" question if you just have to find the initilization and be confident that that is it. I actually get rather nervous around non-final variables now a days. It's like the differnce between having a knife hanging in a thread abouve your head, or just having it you kitchen drawer... A final variable is just a nice way to lable values. A non-final variable is bound to part of some bug-prone algorithm. One nice feature is that when the option to use a variable in out of the question for an algorithm most of the time the sollution is to write a method instead, which usually improves the code significantly. A: I've been coding for a while now and using final whenever I can. After doing this for a while (for variables, method parameters and class attributes), I can say that 90% (or more) of my variables are actually final. I think the benefit of NOT having variables modified when you don't want to (I saw that before and it's a pain sometimes) pays for the extra typing and the extra "final" keywords in your code. That being said, if I would design a language, I would make every variable final unless modified by some other keyword. I don't use final a lot for classes and methods, thought. This is a more or less complicated design choice, unless your class is a utility class (in which case you should have only one private constructor). I also use Collections.unmodifiable... to create unmodifiable lists when I need to. A: I hardly use final on methods or classes because I like allowing people to override them. Otherwise, I only use finally if it is a public/private static final type SOME_CONSTANT; A: Using anonymous local classes for event listeners and such is a common pattern in Java. The most common use of the final keyword is to make sure that variables in scope are accessible to the even listener. However, if you find yourself being required to put a lot of final statements in your code. That might be a good hint you're doing something wrong. The article posted above gives this example: public void doSomething(int i, int j) { final int n = i + j; // must be declared final Comparator comp = new Comparator() { public int compare(Object left, Object right) { return n; // return copy of a local variable } }; } A: I use it for constants inside and outside methods. I only sometimes use it for methods because I don't know if a subclass would NOT want to override a given method(for whatever reasons). As far as classes, only for some infrastructure classes, have I used final class. IntelliJ IDEA warns you if a function parameter is written to inside a function. So, I've stopped using final for function arguments. I don't see them inside java Runtime library as well. A: Marking the class final can also make some method bindings happen at compile time instead of runtime. Consider "v2.foo()" below - the compiler knows that B cannot have a subclass, so foo() cannot be overridden so the implementation to call is known at compile time. If class B is NOT marked final, then it's possible that the actual type of v2 is some class that extends B and overrides foo(). class A { void foo() { //do something } } final class B extends A { void foo() { } } class Test { public void t(A v1, B v2) { v1.foo(); v2.foo(); } } A: Using final for constants is strongly encouraged. However, I wouldn't use it for methods or classes (or at least think about it for a while), because it makes testing harder, if not impossible. If you absolutely must make a class or method final, make sure this class implements some interface, so you can have a mock implementing the same interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/137868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "209" }
Q: How to change directory security attributes using InstallShield? I'd like to change the security attribute of a directory that InstallShield creates under the CSIDL_COMMON_APPDATA - can someone please advise on how to do that during the installation process? It's a script-defined folder. Thank you. A: Under InstallShield 2008 it's Installation Designer > Components > [somecomponent] > Destination Permissions Note that the directory properties are attached to the component, while individual File permissions are set under the 'Files' node This assumes you are letting InstallShield / Windows Installer handle directory creation. If you're creating the directory in a script then things start getting tricky if you need to ensure a clean uninstall. A: I think I found the answer for this - on this page: http://www.installsite.org/pages/en/isp_os.htm there's an ntperm.zip archive which contains a script that seems to do what I need. A: I don't know whether a Installshield builtin function exists for that. The simple solution is to create a DLL that does the real work of manipulating the security attributes and call it once the directory is created. Typically, one might want to change the access so that everyone is able to read/write to the whole directory or file(s) within it. A: you can also just easily call Windows commands "CACLS.EXE" or "ICACLS.EXE" -both are easy command line tool, e.g. icacls file /grant Administrator:(D,WDAC) - Will grant the user Administrator Delete and Write DAC permissions to file
{ "language": "en", "url": "https://stackoverflow.com/questions/137870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can JQuery.Validate plugin prevent submission of an Ajax form I am using the JQuery form plugin (http://malsup.com/jquery/form/) to handle the ajax submission of a form. I also have JQuery.Validate (http://docs.jquery.com/Plugins/Validation) plugged in for my client side validation. What I am seeing is that the validation fails when I expect it to however it does not stop the form from submitting. When I was using a traditional form (i.e. non-ajax) the validation failing prevented the form for submitting at all.... which is my desired behaviour. I know that the validation is hooked up correctly as the validation messages still appear after the ajax submit has happened. So what I am I missing that is preventing my desired behaviour? Sample code below.... <form id="searchForm" method="post" action="/User/GetDetails"> <input id="username" name="username" type="text" value="user.name" /> <input id="submit" name="submit" type="submit" value="Search" /> </form> <div id="detailsView"> </div> <script type="text/javascript"> var options = { target: '#detailsView' }; $('#searchForm').ajaxForm(options); $('#searchForm').validate({ rules: { username: {required:true}}, messages: { username: {required:"Username is a required field."}} }); </script> A: ... well it's been a while so my situation has changed a little. Currently I have a submitHandler option passed to the Validate() plugin. In that handler I manually use ajaxSubmit. More a workaround than an answer I guess. Hope that helps. http://jquery.bassistance.de/validate/demo/ajaxSubmit-intergration-demo.html var v = jQuery("#form").validate({ submitHandler: function(form) { jQuery(form).ajaxSubmit({target: "#result"}); } }); A: $('#contactform').ajaxForm({ success : FormSendResponse, beforeSubmit: function(){ return $("#contactform").valid(); } }); $("#contactform").validate(); Above code worked fine for me. A: You need to add a callback function for use with the beforeSubmit event when initializing the ajaxForm(): var options = { beforeSubmit: function() { return $('#searchForm').validate().form(); }, target: '#detailsView' }; Now it knows to check the result of the validation before it will submit the page. A: Just as a first pass, I'm wondering why the line $("form").validate({ doesn't refer to $("searchform"). I haven't looked this up, or tried it, but that just seems to be a mismatch. Wouldn't you want to call validate on the appropriate form? Anyway, if this is completely wrong, then the error isn't immediately obvious. :) A: Also make sure all of your input fields have a "name" attribute as well as an "id" attribute. I noticed the jquery validation plugin doesn't function correctly without these. A: ok, this is an old question but i will put our solution here for posterity. i personally classify this one as a hack-trocity, but at least it's not a hack-tacu-manjaro <script type="text/javascript"> var options = { target: '#detailsView' }; // -- "solution" -- $('#searchForm').submit(function(event) { this.preventDefault(event); // our env actually monkey patches preventDefault // impl your own prevent default here // basically the idea is to bind a prevent default // stopper on the form's submit event }); // -- end -- $('#searchForm').ajaxForm(options); $('#searchForm').validate({ rules: { username: {required:true}}, messages: { username: {required:"Username is a required field."}} }); </script> A: May be a return false; on the form will help? :) I mean: <form id="searchForm" method="post" action="/User/GetDetails" onSubmit="return false;">
{ "language": "en", "url": "https://stackoverflow.com/questions/137872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: How can you automate Firefox from C# application? Start with the simplest task of capturing the URL in Firefox from a C# application. It appears using user32.dll Windows API functions will not work as is the approach for capturing the URL within IE. A: Should I need to do a capture of the URL with AutoHotkey, for example, I would send Ctrl+L (put focus in address bar and highlight content) and Ctrl+C (copy selection to clipboard). Then you just read the clipboard to get the info. For more complex tasks, I would use Greasemonkey or iMacros extensions, perhaps triggered by similar keyboard shortcuts. A: WatiN has support for Firefox. A: WebAii can automate FireFox, including setting and retrieving the URL A: It appears to be very beta-ey, but someone built a .net connector for mozrepl. Actually, the mozrepl codebase just moved to github. But mozrepl lets you issue commands to the Firefox's XUL environment. A: Try Selenium (the Google testing engine - http://seleniumhq.org/) You can record task (Webpages UI related) done in Firefox and the convert the recording into a C# source :) A: You can use Selenium WebDriver for C #. This is a cross-platform API that allows you to control various browsers using APIs for Java, C#, among others. Attachment of a code C # with Selenium WebDriver tests. using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenQA.Selenium.Firefox; using OpenQA.Selenium; using OpenQA.Selenium.Interactions; using OpenQA.Selenium.Interactions.Internal; using OpenQA.Selenium.Support.UI; using OpenQA.Selenium.IE; using NUnit.Framework; using System.Text.RegularExpressions; namespace sae_test { class Program { private static string baseURL; private static StringBuilder verificationErrors; static void Main(string[] args) { // test with firefox IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver(); // test with IE //InternetExplorerOptions options = new InternetExplorerOptions(); //options.IntroduceInstabilityByIgnoringProtectedModeSettings = true; //IWebDriver driver = new OpenQA.Selenium.IE.InternetExplorerDriver(options); SetupTest(); driver.Navigate().GoToUrl(baseURL + "Account/Login.aspx"); IWebElement inputTextUser = driver.FindElement(By.Id("MainContent_LoginUser_UserName")); inputTextUser.Clear(); driver.FindElement(By.Id("MainContent_LoginUser_UserName")).Clear(); driver.FindElement(By.Id("MainContent_LoginUser_UserName")).SendKeys("usuario"); driver.FindElement(By.Id("MainContent_LoginUser_Password")).Clear(); driver.FindElement(By.Id("MainContent_LoginUser_Password")).SendKeys("123"); driver.FindElement(By.Id("MainContent_LoginUser_LoginButton")).Click(); driver.Navigate().GoToUrl(baseURL + "finanzas/consulta.aspx"); // view combo element IWebElement comboBoxSistema = driver.FindElement(By.Id("MainContent_rcbSistema_Arrow")); //Then click when menu option is visible comboBoxSistema.Click(); System.Threading.Thread.Sleep(500); // container of elements systems combo IWebElement listaDesplegableComboSistemas = driver.FindElement(By.Id("MainContent_rcbSistema_DropDown")); listaDesplegableComboSistemas.FindElement(By.XPath("//li[text()='BOMBEO MECANICO']")).Click(); System.Threading.Thread.Sleep(500); IWebElement comboBoxEquipo = driver.FindElement(By.Id("MainContent_rcbEquipo_Arrow")); //Then click when menu option is visible comboBoxEquipo.Click(); System.Threading.Thread.Sleep(500); // container of elements equipment combo IWebElement listaDesplegableComboEquipos = driver.FindElement(By.Id("MainContent_rcbEquipo_DropDown")); listaDesplegableComboEquipos.FindElement(By.XPath("//li[text()='MINI-V']")).Click(); System.Threading.Thread.Sleep(500); driver.FindElement(By.Id("MainContent_Button1")).Click(); try { Assert.AreEqual("BOMBEO MECANICO_22", driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_LabelSistema\"]")).Text); } catch (AssertionException e) { verificationErrors.Append(e.Message); } // verify coin format $1,234,567.89 usd try { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelInversionInicial\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd")); } catch (AssertionException e) { verificationErrors.Append(e.Message); } try { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoOpMantto\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd")); } catch (AssertionException e) { verificationErrors.Append(e.Message); } try { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd")); } catch (AssertionException e) { verificationErrors.Append(e.Message); } try { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelcostoUnitarioEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd")); } catch (AssertionException e) { verificationErrors.Append(e.Message); } // verify number format 1,234,567.89 try { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelConsumo\"]")).Text, "((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})?")); } catch (AssertionException e) { verificationErrors.Append(e.Message); } System.Console.WriteLine("errores: " + verificationErrors); System.Threading.Thread.Sleep(20000); driver.Quit(); } public static void SetupTest() { baseURL = "http://127.0.0.1:8081/ver.rel.1.2/"; verificationErrors = new StringBuilder(); } protected static void mouseOver(IWebDriver driver, IWebElement element) { Actions builder = new Actions(driver); builder.MoveToElement(element); builder.Perform(); } public static void highlightElement(IWebDriver driver, IWebElement element) { for (int i = 0; i < 2; i++) { IJavaScriptExecutor js = (IJavaScriptExecutor)driver; js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow; border: 2px solid yellow;"); js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);", element, ""); } } } } A: One Microsoft tool I ran into: UI Automation, as part of .NET 3.5 http://msdn.microsoft.com/en-us/library/aa348551.aspx Here's an example: http://msdn.microsoft.com/en-us/library/ms771286.aspx I don't have UI Spy on my pc to interrogate Firefox, so I don't know if this will help out with your user32.dll problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/137880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: C# Mono - Low Level Keyboard Hook I'm using code that I found on the CodeProject.com for a low-level keyboard hook. The only problem is it uses external DLL calls that don't work in mono. I was wondering if anyone knew of a way to accomplish the same thing as that code, but will run in both Windows using .net, and Linux using mono? Edit: Clarifying what I'm trying to do: I'm making a Dashboard like application. The program sits in the system tray and when the user presses the hot-key, it will pop up all the gadgets. So the program doesn't have focus, so typically it won't catch any keystrokes, so I'm using the low-level keyboard hook and I hook the two keys that the user defines as the hot-keys. But I'm using a Windows DLL call for that, which doesn't work in Linux using mono. So I'm wondering if there's a way to do the same thing, but will run in Linux using mono? A: Without knowing what you are trying to capture, it's hard to be sure what will work for you. You may want to look at using Application.AddMessageFilter. An example is here: http://dn.codegear.com/article/30129 A: It's not possible to get this behavior using only .Net. You have to use a binary driver for each platform you run on (Windows, Linux, Mac OS). It might be possible to use only P/Invoke (detect what OS you are running on, call appropriate system libraries) so that you won't have to distribute any "extra" dll/so/dylib.
{ "language": "en", "url": "https://stackoverflow.com/questions/137893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What's the best way to add tags to the head in Plone? I want to add the link tags to redirect my web-site to my OpenID provider. These tags should go in the head element. What's the best way to add them in Plone? I understand that filling the head_slot is a way to do it, but that can only happen when you are adding a template to the page and that template is being rendered. In my case I'm not adding any template. Which template should I modify (that is not main_template.pt, which is my current solution, with it's huge drawbacks). A: You need fill the head_slot defined in main_template.pt In your base plone template, add the following: <head> <metal:block metal:fill-slot="head_slot"> <link rel="openid.server" href="http://your.provider"> <link rel="openid.delegate" href="http://your.url"> </metal:block> </head> A: In the end, you have to either place them directly in the main_template or you have to insert them in one of the slots in the mail_template. What I have puts them in the style slot, next to the rest of the css/javascript links: <metal:myopenid fill-slot="style_slot"> <link rel="openid.server" href="http://www.myopenid.com/server" /> <link rel="openid.delegate" href="http://reinout.myopenid.com/" /> </metal:myopenid> You have to put this in a template somewhere. I put it in a separate homepage.pt as I was customizing the homepage anyway. This puts the openid headers just on the homepage. If you don't want a custom template, you can customize the document_view template (assuming your homepage is a document) and enter above snippet of code into it. It would be best if there's an option for this in plone itself, similar to the "add javascript for statistics here" option. A: I couldn't understand how to fill a slot without a product or anything. I understand that you can fill a slot from a template, but if Plone is not picking up that template, then the filling code would never be run. I ended up modifying main_template and putting my code directly in the . This is bad because different skins will have different main_templates and indeed it bit me because I've modified it for one template when I was using the other. That is not a harmless-nothing-happens experience but a nasty problem because main_template in on custom and it gets picked up so you have one skin working with the main_template of the other. End result: UI broken with a hard-to-find problem. This is the code I added: <head> ... <link rel="openid.server" href="http://www.myopenid.com/server" /> <link rel="openid.delegate" href="http://pupeno.myopenid.com/" /> <link rel="openid2.local_id" href="http://pupeno.myopenid.com" /> <link rel="openid2.provider" href="http://www.myopenid.com/server" /> <meta http-equiv="X-XRDS-Location" content="http://www.myopenid.com/xrds?username=pupeno.myopenid.com" /> </head> I will probably mark this answer as accepted because it's what I'm currently using (and that's my policy, I mark solutions I end up using as accepted, nothing else is marked as accepted), but if any of the other questions become clear in how to inject this new template, I will use that and revert the acceptance (if StackOverflow allows it). A: Plone documentation on supporting OpenID can be found here. http://plone.org/documentation/how-to/openid-support/view?searchterm=openid Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/137911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is Firebug on Firefox 3 stable yet? I really should upgrade to Firefox 3, but I'm very dependent on Firebug working properly. I know there is a version of Firebug that is supposed to work with Firefox 3, but last time I looked, there seemed to be problems with it. So, for those that have made the jump, is Firebug on Firefox 3 ready for prime time? A: Yes, I've been using Firebug heavily and it's been rock-steady. What problems were you having in particular? We could test and report the results. A: Firebug is stable on Firefox 3, but you have to upgrade to version 1.2.1, since previous version no longer work. For some reason, I had to do this update manually: uninstalling the previous version and installing the new one. A: We've been using FF3 with Firebug 1.2.1 for a while now and not encountered any problems. A: You don't have to "jump" to FF3. Install it alongside Firefox 2 and try it out yourself. A: The network monitoring still breaks HTTP headers, and consequently caching. A: I am using Firefox now its very user friendly and ease of use but the thing is its consuming more memory A: Firebug 1.2.x (the only version that works with Firefox 3) no longer appears to have the option to disable Firebug for only certain webpages and sites. If you use this feature you may prefer to stay with FF 2. A: Not only it works fine, but it has great improvements over the FF2 version, like allowing to disable Console, Script, Network and Cookies (if you have Firecookies) to use less resources (a big problem in FF2 if you don't have much memory and have lot of tabs), and allowing/disallowing them per site. Among other improvements... A: When doing "console.log" calls on jQuery objects, in Firefox 3 you get "Object" and you have to expand them to see what are they. In Firefox 2 you get a nice list with the names linked to the DOM nodes that is so much easier to see. As far as I've seen, when you monitor XHR calls in Firebug on Firefox 3, you have to click a button to see the server response of POST calls. The Firebug people say this is a workaround for a bug in Firefox 3 and last time I checked they were still waiting for it to be solved. A: FYI, there's a bug in firebug 1.3.3 on firefox 3.0.9 that causes it not to send an If-modified-since header so it always gets a copy from the server instead of using the cached local copy. http://code.google.com/p/fbug/issues/detail?id=1274&q=etag&colspec=ID%20Type%20Status%20Owner%20Test%20Summary
{ "language": "en", "url": "https://stackoverflow.com/questions/137926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best scripting language to embed in a C# desktop application? We are writing a complex rich desktop application and need to offer flexibility in reporting formats so we thought we would just expose our object model to a scripting langauge. Time was when that meant VBA (which is still an option), but the managed code derivative VSTA (I think) seems to have withered on the vine. What is now the best choice for an embedded scripting language on Windows .NET? A: My scripting language of choice would be Lua these days. It's small, fast, clean, fully documented, well supported, has a great community , it's used by many big companies in the industry (Adobe, Blizzard, EA Games), definetely worth a try. To use it with .NET languages the LuaInterface project will provide all you need. A: IronPython. Here's a guide on how to embed it. A: Why not try C#? Mono has a great new project especially for dynamically evaluating C# : http://tirania.org/blog/archive/2008/Sep-10.html A: I've used CSScript with amazing results. It really cut down on having to do bindings and other low level stuff in my scriptable apps. A: The PowerShell engine was designed to be easily embedded in an application to make it scriptable. In fact, the PowerShell CLI is just a text based interface to the engine. Edit: See https://devblogs.microsoft.com/powershell/making-applications-scriptable-via-powershell/ A: IronRuby as mentioned above. An interesting project to me as a C# programmer is C# Eval support in Mono. But it's not available yet (will be part of Mono 2.2). A: Another vote for IronPython. Embedding it is simple, interoperation with .Net classes is straightforward, and, well, it's Python. A: Boo language. A: Personally, I'd use C# as the scripting language. The .NET framework (and Mono, thanks Matthew Scharley) actually includes the compilers for each of the .NET languages in the framework itself. Basically, there's 2 parts to the implementation of this system. * *Allow the user to compile the code This is relatively easy, and can be done in only a few lines of code (though you might want to add an error dialog, which would probably be a couple dozen more lines of code, depending on how usable you want it to be). *Create and use classes contained within the compiled assembly This is a little more difficult than the previous step (requires a tiny bit of reflection). Basically, you should just treat the compiled assembly as a "plug-in" for the program. There are quite a few tutorials on various ways you can create a plug-in system in C# (Google is your friend). I've implemented a "quick" application to demonstrate how you can implement this system (includes 2 working scripts!). This is the complete code for the application, just create a new one and paste the code in the "program.cs" file. At this point I must apologize for the large chunk of code I'm about to paste (I didn't intend for it to be so large, but got a little carried away with my commenting) using System; using System.Windows.Forms; using System.Reflection; using System.CodeDom.Compiler; namespace ScriptingInterface { public interface IScriptType1 { string RunScript(int value); } } namespace ScriptingExample { static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { // Lets compile some code (I'm lazy, so I'll just hardcode it all, i'm sure you can work out how to read from a file/text box instead Assembly compiledScript = CompileCode( "namespace SimpleScripts" + "{" + " public class MyScriptMul5 : ScriptingInterface.IScriptType1" + " {" + " public string RunScript(int value)" + " {" + " return this.ToString() + \" just ran! Result: \" + (value*5).ToString();" + " }" + " }" + " public class MyScriptNegate : ScriptingInterface.IScriptType1" + " {" + " public string RunScript(int value)" + " {" + " return this.ToString() + \" just ran! Result: \" + (-value).ToString();" + " }" + " }" + "}"); if (compiledScript != null) { RunScript(compiledScript); } } static Assembly CompileCode(string code) { // Create a code provider // This class implements the 'CodeDomProvider' class as its base. All of the current .Net languages (at least Microsoft ones) // come with thier own implemtation, thus you can allow the user to use the language of thier choice (though i recommend that // you don't allow the use of c++, which is too volatile for scripting use - memory leaks anyone?) Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider(); // Setup our options CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; // we want a Dll (or "Class Library" as its called in .Net) options.GenerateInMemory = true; // Saves us from deleting the Dll when we are done with it, though you could set this to false and save start-up time by next time by not having to re-compile // And set any others you want, there a quite a few, take some time to look through them all and decide which fit your application best! // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows // thus they can only do the things you want them to. // (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it) // Just to avoid bloatin this example to much, we will just add THIS program to its references, that way we don't need another // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to // the "script" options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); // Compile our code CompilerResults result; result = csProvider.CompileAssemblyFromSource(options, code); if (result.Errors.HasErrors) { // TODO: report back to the user that the script has errored return null; } if (result.Errors.HasWarnings) { // TODO: tell the user about the warnings, might want to prompt them if they want to continue // runnning the "script" } return result.CompiledAssembly; } static void RunScript(Assembly script) { // Now that we have a compiled script, lets run them foreach (Type type in script.GetExportedTypes()) { foreach (Type iface in type.GetInterfaces()) { if (iface == typeof(ScriptingInterface.IScriptType1)) { // yay, we found a script interface, lets create it and run it! // Get the constructor for the current type // you can also specify what creation parameter types you want to pass to it, // so you could possibly pass in data it might need, or a class that it can use to query the host application ConstructorInfo constructor = type.GetConstructor(System.Type.EmptyTypes); if (constructor != null && constructor.IsPublic) { // lets be friendly and only do things legitimitely by only using valid constructors // we specified that we wanted a constructor that doesn't take parameters, so don't pass parameters ScriptingInterface.IScriptType1 scriptObject = constructor.Invoke(null) as ScriptingInterface.IScriptType1; if (scriptObject != null) { //Lets run our script and display its results MessageBox.Show(scriptObject.RunScript(50)); } else { // hmmm, for some reason it didn't create the object // this shouldn't happen, as we have been doing checks all along, but we should // inform the user something bad has happened, and possibly request them to send // you the script so you can debug this problem } } else { // and even more friendly and explain that there was no valid constructor // found and thats why this script object wasn't run } } } } } } } A: I may suggest S# which I currently maintain. It is an open source project, written in C# and designed for .NET applications. Initially (2007-2009) it was hosted at http://www.codeplex.com/scriptdotnet, but recently it was moved to github. A: Try Ela. This is a functional language similar to Haskell and can be embedded into any .Net application. Even it has simple but usable IDE. A: I havnt tried this yet but it looks pretty cool: http://www.codeplex.com/scriptdotnet A: I've just created a plugin for a client, allowing them to write C# code in modules that act like VBA does for Office. A: I've used Lua before; in a Delphi app but it can be embedded in lots of things. It's used in Adobe's Photoshop Lightroom. A: I like scripting with C# itself. Now, in 2013, there's quite good support for C# scripting, more and more libraries for it are becoming available. Mono has a great support to script C# code, and you can use it with .NET by just including the Mono.CSharp.dll in your application. For C# scripting application that I've made check out CShell Also check out the `ScriptEngine' in Roslyn which is from Microsoft, but this is only CTP. As some people already mentioned, CS-Script has been around for quite a while as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/137933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "99" }
Q: How to jump to an occurrence from Vim search list In Vim editor I opted ]I on a function (in C++ code). This presented a list, which says 'Press ENTER or type command to continue'. Now to jump to an occurrence say 6, I type 6 - but this is not working. What commands can I type in such a case, and how do I jump to Nth occurrence from this list? Update: Actually I tried :N (eg :6) - but the moment I type : Vim enters Insert mode, and the colon gets inserted in the code instead. Update Assuming :N approach is correct, still complete uninstall and install of Vim, without any configuration, too did not help - though now typing : does not switch Vim to insert mode. A: It should present you a list like: 1: 345 my_func (int var) 2: 4523 my_func (int var) 3: 10032 my_func (3); The second column is line numbers. Type :345 to jump to line 345. A: Do :h tselect on vim to see the complete definition If you already see the tag you want to use, you can type 'q' and enter the number. A: If you hit a jump button, and get a list of possible targets, select the number, and hit the jump again. So given 1: 345 my_func (int var) 2: 4523 my_func (int var) 3: 10032 my_func (3); If you hit '2]|', it should jump directly to that line. A: I had the same problem, and cobbling together the previous answers and experimenting I came up with this solution: [I // gives list of matches for word under cursor, potentially some matches are in headers. remember the number of the match you're interested in, eg. the 3rd q // quits the list of matches 3[Ctrl-i // (with cursor in same position) jumps to third match A: When I use vim, and I jump to a tag, by doing for instance: :tag getfirst I get presented with something that looks like: # pri kind tag file 1 F m getfirst /home/sthorne/work/.../FormData.py class:FakeFieldStorage def getfirst(self, k, default): .... 8 F m getfirst /home/sthorne/work/.../CGIForm.py class:CGIForm def getfirst(self, name): Choice number (<Enter> cancels): I type '5' to go to the 5th occurrence. If you can't get your vim to have that behaviour (it seems to be on by default for my vim), you can use g] instead of ctrl-], which is analagous to :tselect instead of :tag A: [I only lists the search results. To jump to the results use the sequence [ CTRL+I. You can see the full list of relevant jumps at: http://www.vim.org/htmldoc/tagsrch.html#include-search A: Try using 123G to go to line 123 (see :h G).
{ "language": "en", "url": "https://stackoverflow.com/questions/137935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How does cherrypy handle user threads? I'm working on a django app right and I'm using cherrypy as the server. Cherrypy creates a new thread for every page view. I'd like to be able to access all of these threads (threads responsible for talking to django) from within any of them. More specifically I'd like to be able to access the thread_data for each of these threads from within any of them. Is this possible? If so, how do I do it? A: CherryPy's wsgiserver doesn't create a new thread for every request--it uses a pool. Each of those worker threads is a subclass of threading.Thread, so all of them should be accessible via threading.enumerate(). However, if you're talking specifically about cherrypy.thread_data, that's something else: a threading.local. If you're using a recent version of Python, then all that's coded in C and you (probably rightfully) don't have cross-thread access to it from Python. If you really need it and really know what you're doing, the best technique is usually to stick an additional reference to such things in a global container at the same time that they are inserted into the thread_data structure. I recommend dicts with weakrefs as keys for those global containers--there are enough Python ORM's that use them for connection pools (see my own Geniusql, for example) that you should be able to learn how to implement them fairly easily. A: My first response to a question like this isn't to tell you how to do it but to stress that you really should reconsider before moving forward with this. I normally shy away from threaded web-servers, in favor of multi-process or asynchronous solutions. Adding explicit inter-thread communication to the mix only increases those fears. When a question like this is asked, there is a deeper goal. I suspect that what you think inter-thread communication would solve can actually be solved in some other, safer way.
{ "language": "en", "url": "https://stackoverflow.com/questions/137950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Reading all values from an ASP.NET datagrid using javascript I have an ASP.NET Datagrid with several text boxes and drop down boxes inside it. I want to read all the values in the grid using a JavaScript function. How do i go about it? A: Easily done with jQuery. I don't recall what kind of markup the Datagrid creates but basically something like this will work in Jquery $('#client_id_of_datagrid input, #client_id_of_datagrid select') .each(function() {val = this.value; /* Do Stuff */}) A: And here's an example using Microsoft AJAX framework: var txts = $get('client_id_of_datagrid').getElementsByTagName('input'); var ddls = $get('client_id_of_datagrid').getElementsByTagName('select'); for(var i=0;i<txts.length;i++){ if(txts[i].type==='text'){ /* do stuff */ } } for(var i=0;i<ddls.length;i++){ /* do stuff */ } And for no framework replace $get with document.getElementById. Really, jQuery is the best idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/137951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Vim Markdown highlighting (list items and code block conflicts) I decide to learn more about vim and its syntax highlighting. Using examples for others, I am creating my own syntax file for Markdown. I have seen mkd.vim and it has this problem too. My issue is between list items and code block highlighting. Code Block definition: * *first line is blank *second line begins with at least 4 spaces or 1 tab *block is finished with a blank line Example: Regular text this is code, monospaced and left untouched by markdown another line of code Regular Text My Vim syntax for code block: syn match mkdCodeBlock /\(\s\{4,}\|\t\{1,}\).*\n/ contained nextgroup=mkdCodeBlock hi link mkdCodeBlock comment Unorder List item definition: * *first line is blank *second line begins with a [-+*] followed by a space *the list is finished with a blank line then a normal (non-list) line *in between line items any number of blank lines can be added *a sub list is specified by indenting (4 space or 1 tab) *a line of normal text after a list item is include as a continuation of that list item Example: Regular text - item 1 - sub item 1 - sub item 2 - item 2 this is part of item 2 so is this - item 3, still in the same list - sub item 1 - sub item 2 Regular text, list ends above My Vim syntax for unorder list item definition (I only highlight [-+*]): syn region mkdListItem start=/\s*[-*+]\s\+/ matchgroup=pdcListText end=".*" contained nextgroup=mkdListItem,mkdListSkipNL contains=@Spell skipnl syn match mkdListSkipNL /\s*\n/ contained nextgroup=mkdListItem,mkdListSkipNL skipnl hi link mkdListItem operator I cannot get the highlighting to work with the last two rule for list and with a code block. This is an example that breaks my syntax highlighting: Regular text - Item 1 - Item 2 part of item 2 - these 2 line should be highlighted as a list item - but they are highlighted as a code block I currently cannot figure out how to get the highlighting to work the way I want it too Forgot to add a "global" syntax rule used in both rules listed below. It is to ensure a that they start with a blank line. syn match mkdBlankLine /^\s*\n/ nextgroup=mkdCodeBlock,mkdListItem transparent Another Note: I should have been more clear. In my syntax file, the List rules appear before the Blockquote Rules A: Just make sure that the definition of mkdListItem is after the definition of mkdCodeBlock, like this: syn match mkdCodeBlock /\(\s\{4,}\|\t\{1,}\).*\n/ contained nextgroup=mkdCodeBlock hi link mkdCodeBlock comment syn region mkdListItem start=/\s*[-*+]\s\+/ matchgroup=pdcListText end=".*" contained nextgroup=mkdListItem,mkdListSkipNL contains=@Spell skipnl syn match mkdListSkipNL /\s*\n/ contained nextgroup=mkdListItem,mkdListSkipNL skipnl hi link mkdListItem operator syn match mkdBlankLine /^\s*\n/ nextgroup=mkdCodeBlock,mkdListItem transparent Vim documentation says in :help :syn-define: "In case more than one item matches at the same position, the one that was defined LAST wins. Thus you can override previously defined syntax items by using an item that matches the same text. But a keyword always goes before a match or region. And a keyword with matching case always goes before a keyword with ignoring case." A: hcs42 was correct. I do remember reading that section now, but I forgot about it until hcs24 reminded me about it. Here is my updated syntax (few other tweaks) that works: """"""""""""""""""""""""""""""""""""""" " Code Blocks: " Indent with at least 4 space or 1 tab " This rule must appear for mkdListItem, or highlighting gets messed up syn match mkdCodeBlock /\(\s\{4,}\|\t\{1,}\).*\n/ contained nextgroup=mkdCodeBlock """"""""""""""""""""""""""""""""""""""" " Lists: " These first two rules need to be first or the highlighting will be " incorrect " Continue a list on the current line or next line syn match mkdListCont /\s*[^-+*].*/ contained nextgroup=mkdListCont,mkdListItem,mkdListSkipNL contains=@Spell skipnl transparent " Skip empty lines syn match mkdListSkipNL /\s*\n/ contained nextgroup=mkdListItem,mkdListSkipNL " Unorder list syn match mkdListItem /\s*[-*+]\s\+/ contained nextgroup=mkdListSkipNL,mkdListCont skipnl A: Tao Zhyn, that maybe covers your use cases but it doesn't cover the Markdown syntax. In Markdown a list item could contain a code block. You could take a look at my solution here TL;DR; the problem is that vim doesn't let you say something like: a block that have the same indentation as its container + 4 spaces. The only solution I found is to generate rules for each kind of blocks that could be contained in a list items for each level of indentation (actually I support 42 level of indentation but it's an arbitrary number) So I have markdownCodeBlockInListItemAtLevel1 that must be contained in a markdownListItemAtLevel1 and it needs to have at least 8 leading spaces, an then markdownCodeBlockInListItemAtLevel2 that must be contained in a markdownListItemAtLevel2 that must be contained in a markdownListItemAtLevel1 ant needs to have at least 10 leading spaces, ecc... I know that a few years have passed but maybe someone would consider this answer helpful since all syntax based on indentation suffers of the same problem
{ "language": "en", "url": "https://stackoverflow.com/questions/137952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Hudson job hangs at Runtime.exec I'm running Hudson as a windows service through Tomcat, with no slaves involved. The last build step in the job is a batch file that invokes some Java code. The code uses PostgreSQL's command line tool psql (via Runtime.exec()) to create a database on the local machine and eventually run some tests against it. The job will progress to this point, then hang indefinitely without starting to create the database. If I run the batch file from the command line, it works perfectly. I don't think http://hudson.gotdns.com/wiki/display/HUDSON/Spawning+processes+from+build applies, since the process spawned doesn't even seem to begin executing, but I'm new to this so please let me know if I'm wrong. Edit @anjanb: The batch file's only purpose is to invoke the Java code, and the only user input is being passed in as command line arguments, which I can see are going in directly via the build's console output. Process Explorer is showing that psql is being started, but it's obviously not being executed, since the first command psql is given is to create a new database, but that's not happening. Edit 2: I've gotten some tips from the Hudson users mailing list, I'll try them out on Monday and report back. Edit 3: The Java code was already consuming the output streams, I used that article when developing the code. I can't figure out what's going on, so I'm redeveloping the code to use JDBC to create the database, instead of relying on psql and Runtime.exec() A: Do you read the output of the process ? If it produces more output than the OS buffers can handle, you need to read it... Also, some processes wait until input has completed. Try to call process.getInputStream().close() after starting the process. Maybe this article is also interesting. It's called "When Runtime.exec() won't": http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=2 A: There is a possibility that the program is waiting on some user input. If the service is not configured to accept user input, it will appear to be hanging. YOu can try by configuring the service to allow USER INPUT(GUI) -- that might help. Also, you could run Sysinternals ProcessExplorer and ProcessMonitor -- they will be able to find out where the .BAT job has stopped.
{ "language": "en", "url": "https://stackoverflow.com/questions/137972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What are drawbacks or disadvantages of singleton pattern? The singleton pattern is a fully paid up member of the GoF's patterns book, but it lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for factory classes, and while you have to be a bit careful about multithreading issues (like any class actually), I fail to see why they are so awful. Stack Overflow especially seems to assume that everyone agrees that Singletons are evil. Why? Please support your answers with "facts, references, or specific expertise" A: When you write code using singletons, say, a logger or a database connection, and afterwards you discover you need more than one log or more than one database, you’re in trouble. Singletons make it very hard to move from them to regular objects. Also, it’s too easy to write a non-thread-safe singleton. Rather than using singletons, you should pass all the needed utility objects from function to function. That can be simplified if you wrap all them into a helper object, like this: void some_class::some_function(parameters, service_provider& srv) { srv.get<error_logger>().log("Hi there!"); this->another_function(some_other_parameters, srv); } A: Too many people put objects which are not thread safe in a singleton pattern. I've seen examples of a DataContext (LINQ to SQL) done in a singleton pattern, despite the fact that the DataContext is not thread safe and is purely a unit-of-work object. A: Recent article on this subject by Chris Reath at Coding Without Comments. Note: Coding Without Comments is no longer valid. However, The article being linked to has been cloned by another user. Link A: The problems with singletons is the issue of increased scope and therefore coupling. There is no denying that there are some of situations where you do need access to a single instance, and it can be accomplished other ways. I now prefer to design around an inversion of control (IoC) container and allow the the lifetimes to be controlled by the container. This gives you the benefit of the classes that depend on the instance to be unaware of the fact that there is a single instance. The lifetime of the singleton can be changed in the future. Once such example I encountered recently was an easy adjustment from single threaded to multi-threaded. FWIW, if it a PIA when you try to unit test it then it's going to PIA when you try to debug, bug fix or enhance it. A: One rather bad thing about singletons is that you can't extend them very easily. You basically have to build in some kind of decorator pattern or some such thing if you want to change their behavior. Also, if one day you want to have multiple ways of doing that one thing, it can be rather painful to change, depending on how you lay out your code. One thing to note, if you DO use singletons, try to pass them in to whoever needs them rather than have them access it directly... Otherwise if you ever choose to have multiple ways of doing the thing that singleton does, it will be rather difficult to change as each class embeds a dependency if it accesses the singleton directly. So basically: public MyConstructor(Singleton singleton) { this.singleton = singleton; } rather than: public MyConstructor() { this.singleton = Singleton.getInstance(); } I believe this sort of pattern is called dependency injection and is generally considered a good thing. Like any pattern though... Think about it and consider if its use in the given situation is inappropriate or not... Rules are made to be broken usually, and patterns should not be applied willy nilly without thought. A: The singleton pattern is not a problem in itself. The problem is that the pattern is often used by people developing software with object-oriented tools without having a solid grasp of OO concepts. When singletons are introduced in this context they tend to grow into unmanageable classes that contain helper methods for every little use. Singletons are also a problem from a testing perspective. They tend to make isolated unit-tests difficult to write. Inversion of control (IoC) and dependency injection are patterns meant to overcome this problem in an object-oriented manner that lends itself to unit testing. In a garbage collected environment singletons can quickly become an issue with regard to memory management. There is also the multi-threaded scenario where singletons can become a bottleneck as well as a synchronization issue. A: Singletons are NOT bad. It's only bad when you make something globally unique that isn't globally unique. However, there are "application scope services" (think about a messaging system that makes components interact) - this CALLS for a singleton, a "MessageQueue" - class that has a method "SendMessage(...)". You can then do the following from all over the place: MessageQueue.Current.SendMessage(new MailArrivedMessage(...)); And, of course, do: MessageQueue.Current.RegisterReceiver(this); in classes that implement IMessageReceiver. A: Here is one more thing about singletons which nobody said yet. In most cases "singletonity" is a detail of implementation for some class rather than characteristic of its interface. Inversion of Control Container may hide this characteristic from class users; you just need to mark your class as a singleton (with @Singleton annotation in Java for example) and that's it; IoCC will do the rest. You don't need to provide global access to your singleton instance because the access is already managed by IoCC. Thus there is nothing wrong with IoC Singletons. GoF Singletons in opposite to IoC Singletons are supposed to expose "singletonity" in the interface through getInstance() method, and so that they suffer from everything said above. A: Singletons aren't evil, if you use it properly & minimally. There are lot of other good design patterns which replaces the needs of singleton at some point (& also gives best results). But some programmers are unaware of those good patterns & uses the singleton for all the cases which makes the singleton evil for them. A: A singleton gets implemented using a static method. Static methods are avoided by people who do unit testing because they cannot be mocked or stubbed. Most people on this site are big proponents of unit testing. The generally most accepted convention to avoid them is using the inversion of control pattern. A: Because they are basically object oriented global variables, you can usually design your classes in such a way so that you don't need them. A: Firstly a class and its collaborators should firstly perform their intended purpose rather than focusing on dependents. Lifecycle management (when instances are created and when they go out of scope) should not be part of the classes responsibility. The accepted best practice for this is to craft or configure a new component to manage dependencies using dependency injection. Often software gets more complicated it makes sense to have multiple independent instances of the Singleton class with different state. Committing code to simply grab the singleton is wrong in such cases. Using Singleton.getInstance() might be ok for small simple systems but it doesn't work/scale when one might need a different instance of the same class. No class should be thought of as a singleton but rather that should be an application of it's usage or how it is used to configure dependents. For a quick and nasty this does not matter - just luke hard coding say file paths does not matter but for bigger applications such dependencies need to be factored out and managed in more appropriate way using DI. The problems that singleton cause in testing is a symptom of their hard coded single usage case/environment. The test suite and the many tests are each individual and separate something that is not compatible with hard coding a singleton. A: Singletons solve one (and only one) problem. Resource Contention. If you have some resource that (1) can only have a single instance, and (2) you need to manage that single instance, you need a singleton. There aren't many examples. A log file is the big one. You don't want to just abandon a single log file. You want to flush, sync and close it properly. This is an example of a single shared resource that has to be managed. It's rare that you need a singleton. The reason they're bad is that they feel like a global and they're a fully paid up member of the GoF Design Patterns book. When you think you need a global, you're probably making a terrible design mistake. A: Singletons are also bad when it comes to clustering. Because then, you do not have "exactly one singleton" in your application anymore. Consider the following situation: As a developer, you have to create a web application which accesses a database. To ensure that concurrent database calls do not conflict each other, you create a thread-save SingletonDao: public class SingletonDao { // songleton's static variable and getInstance() method etc. omitted public void writeXYZ(...){ synchronized(...){ // some database writing operations... } } } So you are sure that only one singleton in your application exists and all database go through this one and only SingletonDao. Your production environment now looks like this: Everything is fine so far. Now, consider you want to set up multiple instances of your web application in a cluster. Now, you suddenly have something like this: That sounds weird, but now you have many singletons in your application. And that is exactly what a singleton is not supposed to be: Having many objects of it. This is especially bad if you, as shown in this example, want to make synchronized calls to a database. Of course this is an example of a bad usage of a singleton. But the message of this example is: You can not rely that there is exactly one instance of a singleton in your application - especially when it comes to clustering. A: * *It is easily (ab)used as a global variable. *Classes that depend on singletons are relatively harder to unit test in isolation. A: A pattern emerges when several people (or teams) arrives at similar or identical solutions. A lot of people still use singletons in their original form or using factory templates (good discussion in Alexandrescu's Modern C++ Design). Concurrency and difficulty in managing the lifetime of the object are the main obstacles, with the former easily managed as you suggest. Like all choices, Singleton has its fair share of ups and downs. I think they can be used in moderation, especially for objects that survive the application life span. The fact that they resemble (and probably are) globals have presumably set off the purists. A: Some counterpoints from the author: You are stuck if you need to make the class not single in the future Not at all - I was in this situation with a single database connection singleton that I wanted to turn into a connection pool. Remember that every singleton is accessed through a standard method: MyClass.instance This is similar to the signature of a factory method. All I did was update the instance method to return the next connection from the pool - no other changes required. That would have been far harder if we had NOT been using a singleton. Singletons are just fancy globals Can't argue with that but so are all static fields and methods - anything that is accessed from the class rather than an instance is essentially global and I dont see so much pushback on the use of static fields? Not saying that Singletons are good, just pushing back at some of the 'conventional wisdom' here. A: Some coding snobs look down on them as just a glorified global. In the same way that many people hate the goto statement there are others that hate the idea of ever using a global. I have seen several developers go to extraordinary lengths to avoid a global because they considered using one as an admission of failure. Strange but true. In practice the Singleton pattern is just a programming technique that is a useful part of your toolkit of concepts. From time to time you might find it is the ideal solution and so use it. But using it just so you can boast about using a design pattern is just as stupid as refusing to ever use it because it is just a global. A: Monopoly is the devil and singletons with non-readonly/mutable state are the 'real' problem... After reading Singletons are Pathological Liars as suggested in jason's answer I came across this little tidbit that provides the best presented example of how singletons are often misused. Global is bad because: * *a. It causes namespace conflict *b. It exposes the state in a unwarranted fashion When it comes to Singletons * *a. The explicit OO way of calling them, prevents the conflicts, so point a. is not an issue *b. Singletons without state are (like factories) are not a problem. Singletons with state can again fall in two categories, those which are immutable or write once and read many (config/property files). These are not bad. Mutable Singletons, which are kind of reference holders are the ones which you are speaking of. In the last statement he's referring to the blog's concept of 'singletons are liars'. How does this apply to Monopoly? To start a game of monopoly, first: * *we establish the rules first so everybody is on the same page *everybody is given an equal start at the beginning of the game *only one set of rules is presented to avoid confusion *the rules aren't allowed to change throughout the game Now, for anybody who hasn't really played monopoly, these standards are ideal at best. A defeat in monopoly is hard to swallow because, monopoly is about money, if you lose you have to painstakingly watch the rest of the players finish the game, and losses are usually swift and crushing. So, the rules usually get twisted at some point to serve the self-interest of some of the players at the expense of the others. So you're playing monopoly with friends Bob, Joe, and Ed. You're swiftly building your empire and consuming market share at an exponential rate. Your opponents are weakening and you start to smell blood (figuratively). Your buddy Bob put all of his money into gridlocking as many low-value properties as possible but his isn't receiving a high return on investment the way he expected. Bob, as a stroke of bad luck, lands on your Boardwalk and is excised from the game. Now the game goes from friendly dice-rolling to serious business. Bob has been made the example of failure and Joe and Ed don't want to end up like 'that guy'. So, being the leading player you, all of a sudden, become the enemy. Joe and Ed start practicing under-the-table trades, behind-the-back money injections, undervalued house-swapping and generally anything to weaken you as a player until one of them rises to the top. Then, instead of one of them winning, the process starts all over. All of a sudden, a finite set of rules becomes a moving target and the game degenerates into the type of social interactions that would make up the foundation of every high-rated reality TV show since Survivor. Why, because the rules are changing and there's no consensus on how/why/what they're supposed to represent, and more importantly, there's no one person making the decisions. Every player in the game, at that point, is making his/her own rules and chaos ensues until two of the players are too tired to keep up the charade and slowly give up. So, if a rulebook for a game accurately represented a singleton, the monopoly rulebook would be an example of abuse. How does this apply to programming? Aside from all of the obvious thread-safety and synchronization issues that mutable singletons present... If you have one set of data, that is capable of being read/manipulated by multiple different sources concurrently and exists during the lifetime of the application execution, it's probably a good time to step back and ask "am I using the right type of data structure here". Personally, I have seen a programmer abuse a singleton by using it as some sort of twisted cross-thread database store within an application. Having worked on the code directly, I can attest that it was a slow (because of all the thread locks needed to make it thread-safe) and a nightmare to work on (because of the unpredictable/intermittent nature of synchronization bugs), and nearly impossible to test under 'production' conditions. Sure, a system could have been developed using polling/signaling to overcome some of the performance issues but that wouldn't solve the issues with testing and, why bother when a 'real' database can already accomplish the same functionality in a much more robust/scalable manner. A Singleton is only an option if you need what a singleton provides. A write-one read-only instance of an object. That same rule should cascade to the object's properties/members as well. A: Singleton is not about single instance! Unlike other answers I don't want to talk about what is wrong with Singletons but to show you how powerful and awesome they are when used right! * *Problem: Singleton can be a challenge in multi-threading environment Solution: Use a single threaded bootstrap process to initialize all the dependencies of your singleton. *Problem: It is hard to mock singletons. Solution: Use method Factory pattern for mocking You can map MyModel to TestMyModel class that inherits it, everywhere when MyModel will be injected you will get TestMyModel instread. - Problem: Singletons can cause memory leaks as they never disposed. Solution: Well, dispose them! Implement a callback in your app to properly dispose a singletons, you should remove any data linked to them and finally: remove them from the Factory. As I stated at the title singleton are not about single instance. * *Singletons improves readability: You can look at your class and see what singleton it injected to figure out what is it's dependencies. *Singletons improves maintenance: Once you removed a dependency from a class you just deleted some singleton injection, you don't need to go and edit a big link of other classes that just moved your dependency around(This is smelly code for me @Jim Burger) *Singletons improves memory and performance: When some thing happens in your application, and it takes a long chain of callbacks to deliver, you are wasting memory and performance, by using Singleton you are cutting the middle man, and improve your performance and memory usage(by avoiding unnecessary local variables allocations). A: The Singleton – the anti-pattern! by Mark Radford (Overload Journal #57 – Oct 2003) is a good read about why Singleton is regarded an anti-pattern. The article also discusses two alternatives design approaches for replacing Singleton. A: This is what I think is missing from the answers so far: If you need one instance of this object per process address space (and you are as confident as you can be that this requirement will not change), you should make it a singleton. Otherwise, it's not a singleton. This is a very odd requirement, hardly ever of interest to the user. Processes and address space isolation are an implementation detail. They only impact on the user when they want to stop your application using kill or Task Manager. Apart from building a caching system, there aren't that many reasons why you'd be so certain that there should only be on instance of something per process. How about a logging system? Might be better for that to be per-thread or more fine-grained so you can trace the origin of messages more automatically. How about the application's main window? It depends; maybe you'll want all the user's documents to be managed by the same process for some reason, in which case there would be multiple "main windows" in that process. A: See Wikipedia Singleton_pattern It is also considered an anti-pattern by some people, who feel that it is overly used, introducing unnecessary limitations in situations where a sole instance of a class is not actually required.[1][2][3][4] References (only relevant references from the article) * *^ Alex Miller. Patterns I hate #1: Singleton, July 2007 *^ Scott Densmore. Why singletons are evil, May 2004 *^ Steve Yegge. Singletons considered stupid, September 2004 *^ J.B. Rainsberger, IBM. Use your singletons wisely, July 2001 A: My answer on how Singletons are bad is always, "they are hard to do right". Many of the foundational components of languages are singletons (classes, functions, namespaces and even operators), as are components in other aspects of computing (localhost, default route, virtual filesystem, etc.), and it is not by accident. While they cause trouble and frustration from time to time, they also can make a lot of things work a LOT better. The two biggest screw ups I see are: treating it like a global & failing to define the Singleton closure. Everyone talks about Singleton's as globals, because they basically are. However, much (sadly, not all) of the badness in a global comes not intrinsically from being global, but how you use it. Same goes for Singletons. Actually more so as "single instance" really doesn't need to mean "globally accessible". It is more a natural byproduct, and given all the bad that we know comes from it, we shouldn't be in such a hurry to exploit global accessibility. Once programmers see a Singleton they seem to always access it directly through its instance method. Instead, you should navigate to it just like you would any other object. Most code shouldn't even be aware it is dealing with a Singleton (loose coupling, right?). If only a small bit of code accesses the object like it is a global, a lot of harm is undone. I recommend enforcing it by restricting access to the instance function. The Singleton context is also really important. The defining characteristic of a Singleton is that there is "only one", but the truth is it is "only one" within some kind of context/namespace. They are usually one of: one per thread, process, IP address or cluster, but can also be one per processor, machine, language namespace/class loader/whatever, subnet, Internet, etc. The other, less common, mistake is to ignore the Singleton lifestyle. Just because there is only one doesn't mean a Singleton is some omnipotent "always was and always will be", nor is it generally desirable (objects without a begin and end violate all kinds of useful assumptions in code, and should be employed only in the most desperate of circumstances. If you avoid those mistakes, Singletons can still be a PITA, bit it is ready to see a lot of the worst problems are significantly mitigated. Imagine a Java Singleton, that is explicitly defined as once per classloader (which means it needs a thread safety policy), with defined creation and destruction methods and a life cycle that dictates when and how they get invoked, and whose "instance" method has package protection so it is generally accessed through other, non-global objects. Still a potential source of trouble, but certainly much less trouble. Sadly, rather than teaching good examples of how to do Singletons. We teach bad examples, let programmers run off using them for a while, and then tell them they are a bad design pattern. A: Misko Hevery, from Google, has some interesting articles on exactly this topic... Singletons are Pathological Liars has a unit testing example that illustrates how singletons can make it difficult to figure out dependency chains and start or test an application. It is a fairly extreme example of abuse, but the point that he makes is still valid: Singletons are nothing more than global state. Global state makes it so your objects can secretly get hold of things which are not declared in their APIs, and, as a result, Singletons make your APIs into pathological liars. Where have all the Singletons Gone makes the point that dependency injection has made it easy to get instances to constructors that require them, which alleviates the underlying need behind the bad, global Singletons decried in the first article. A: It blurs the separation of concerns. Supposed that you have a singleton, you can call this instance from anywhere inside your class. Your class is no longer as pure as it should be. Your class will now no longer operate on its members and the members that it receives explicitly. This will create confusion, because the users of the class don't know what is the sufficient information the class needs. The whole idea of encapsulation is to hide the how of a method from the users, but if a singleton is used inside the method, one will have to know the state of the singleton in order to use the method correctly. This is anti-OOP. A: It's not that singletons themselves are bad but the GoF design pattern is. The only really argument that is valid is that the GoF design pattern doesn't lend itself in regards to testing, especially if tests are run in parallel. Using a single instance of an class is a valid construct as long as you apply the following means in code: * *Make sure the class that will be used as a singleton implements an interface. This allows stubs or mocks to be implemented using the same interface *Make sure that the Singleton is thread-safe. That's a given. *The singleton should be simple in nature and not overly complicated. *During the runtime of you application, where singletons need to be passed to a given object, use a class factory that builds that object and have the class factory pass the singleton instance to the class that needs it. *During testing and to ensure deterministic behavior, create the singleton class as separate instance as either the actual class itself or a stub/mock that implements its behavior and pass it as is to the class that requires it. Don't use the class factor that creates that object under test that needs the singleton during test as it will pass the single global instance of it, which defeats the purpose. We've used Singletons in our solutions with a great deal of success that are testable ensuring deterministic behavior in parallel test run streams. A: Vince Huston has these criteria, which seem reasonable to me: Singleton should be considered only if all three of the following criteria are satisfied: * *Ownership of the single instance cannot be reasonably assigned *Lazy initialization is desirable *Global access is not otherwise provided for If ownership of the single instance, when and how initialization occurs, and global access are not issues, Singleton is not sufficiently interesting. A: I'd like to address the 4 points in the accepted answer, hopefully someone can explain why I'm wrong. * *Why is hiding dependencies in your code bad? There are already dozens of hidden dependencies (C runtime calls, OS API calls, global function calls), and singleton dependencies are easy to find (search for instance()). "Making something global to avoid passing it around is a code smell." Why isn't passing something around to avoid making it a singleton a code smell? If you're passing an object through 10 functions in a call stack just to avoid a singleton, is that so great? *Single Responsibility Principle: I think this is a bit vague and depends on your definition of responsibility. A relevant question would be, why does adding this specific "responsibility" to a class matter? *Why does passing an object to a class make it more tightly coupled than using that object as a singleton from within the class? *Why does it change how long the state lasts? Singletons can be created or destroyed manually, so the control is still there, and you can make the lifetime the same as a non-singleton object's lifetime would be. Regarding unit tests: * *not all classes need to be unit tested *not all classes that need to be unit tested need to change the implementation of the singleton *if they do need be unit tested and do need to change the implementation, it's easy to change a class from using a singleton to having the singleton passed to it via dependency injection. A: I think the confusion is caused by the fact that people don't know the real application of the Singleton pattern. I can't stress this enough. Singleton is not a pattern to wrap globals. Singleton pattern should only be used to guarantee that one and only one instance of a given class exists during run time. People think Singleton is evil because they are using it for globals. It is because of this confusion that Singleton is looked down upon. Please, don't confuse Singletons and globals. If used for the purpose it was intended for, you will gain extreme benefits from the Singleton pattern. A: Paraphrased from Brian Button: * *They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell. *They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle. *They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases. *They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other. A: Singletons are bad from a purist point of view. From a pratical point of view, a singleton is a trade-off developing time vs complexity. If you know your application won't change that much they are pretty OK to go with. Just know that you may need to refactor things up if your requirements change in an unexpected way (which is pretty OK in most cases). Singletons sometimes also complicate unit testing. A: I'm not going to comment on the good/evil argument, but I haven't used them since Spring came along. Using dependency injection has pretty much removed my requirements for singleton, servicelocators and factories. I find this a much more productive and clean environment, at least for the type of work I do (Java-based web applications). A: There is nothing inherently wrong with the pattern, assuming it is being used for some aspect of your model which is truly single. I believe the backlash is due to its overuse which, in turn, is due to the fact that it's the easiest pattern to understand and implement. A: Singleton is a pattern and can be used or abused just like any other tool. The bad part of a singleton is generally the user (or should I say the inappropriate use of a singleton for things it is not designed to do). The biggest offender is using a singleton as a fake global variable. A: Off the top of my head: * *They enforce tight-coupling. If your singleton resides on a different assembly than its user, the using assembly cannot ever function without the assembly containing the singleton. *They allow for circular dependencies, e.g., Assembly A can have a singleton with a dependency on Assembly B, and Assembly B can use Assembly A's singleton. All without breaking the compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/137975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2146" }
Q: Q's on pgsql I'm a newbie to pgsql. I have few questionss on it: 1) I know it is possible to access columns by <schema>.<table_name>, but when I try to access columns like <db_name>.<schema>.<table_name> it throwing error like Cross-database references are not implemented How do I implement it? 2) We have 10+ tables and 6 of have 2000+ rows. Is it fine to maintain all of them in one database? Or should I create dbs to maintain them? 3) From above questions tables which have over 2000+ rows, for a particular process I need a few rows of data. I have created views to get those rows. For example: a table contains details of employees, they divide into 3 types; manager, architect, and engineer. Very obvious thing this table not getting each every process... process use to read data from it... I think there are two ways to get data SELECT * FROM emp WHERE type='manager', or I can create views for manager, architect n engineer and get data SELECT * FROM view_manager Can you suggest any better way to do this? 4) Do views also require storage space, like tables do? Thanx in advance. A: * *Cross Database exists in PostGreSQL for years now. You must prefix the name of the database by the database name (and, of course, have the right to query on it). You'll come with something like this: SELECT alias_1.col1, alias_2.col3 FROM table_1 as alias_1, database_b.table_2 as alias_2 WHERE ... If your database is on another instance, then you'll need to use the dblink contrib. *This question doe not make sens. Please refine. *Generally, views are use to simplify the writing of other queries that reuse them. In your case, as you describe it, maybe that stored proceudre would better fits you needs. *No, expect the view definition. A: 1: A workaround is to open a connection to the other database, and (if using psql(1)) set that as your current connection. However, this will work only if you don't try to join tables in both databases. A: 1) That means it's not a feature Postgres supports. I do not know any way to create a query that runs on more than one database. 2) That's fine for one database. Single databases can contains billions of rows. 3) Don't bother creating views, the queries are simple enough anyway. 4) Views don't require space in the database except their query definition.
{ "language": "en", "url": "https://stackoverflow.com/questions/137998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make XMLHttpRequest work over HTTPS on Firefox? When I try to send an HTTP GET request through XMLHttpRequest it works on non-secure HTTP. But when sent over HTTPS, different browsers gave different results: On Firefox 3.0.2: - The GET request doesn't reach the web server. On IE 7: - The GET request reached the web server. Does this have something to do with Firefox 3 getting stricter with untrusted certificates? Is there a way around this? I've already added the URL as an exception in Firefox's Certificate Manager. The error console doesn't report any error. I've added a try-catch around XMLHttpRequest's open() and send. No exception is thrown. Using both absolute and relative URL path doesn't work. Here's the code snippet: var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { return false; } } } // we won't be handling any HTTP response xmlHttp.onreadystatechange=function() { // do nothing.. } // send HTTP GET request try { xmlHttp.open("GET", "/[relative path to request]", true); xmlHttp.send(null); } catch (e) { alert('Error sending HTTP GET request!'); return false; } Thanks, Kenneth A: Try placing your closure after the open: // send HTTP GET request try { xmlHttp.open("GET", "/[relative path to request]", true); } catch (e) { alert('Error sending HTTP GET request!'); return false; } // we won't be handling any HTTP response xmlHttp.onreadystatechange=function() { // do nothing.. } // Then send it. xmlHttp.send(null); A little googling found confirmation: http://www.ghastlyfop.com/blog/2007/01/onreadystate-changes-in-firefox.html Although that document says to attach the function after .send(null), I've always attached after open. A: By any chance, are you requesting a non-HTTPS URL in an HTTPS page? Do any messages appear in the error log/console?
{ "language": "en", "url": "https://stackoverflow.com/questions/138000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Do you know update site addresses for *latest* eclipse components? I am looking for all addresses related to: * *3.x eclipse itself (milestones and/or integration builds) *3.x other components (GEF, GMF, EMF, ...) In the spirit of answering my own question, I do have an answer for: * *3.5 eclipse itself, with some details and caveats, *3.6 Helios, with the steps involved to follow the updates. However, If you have further addresses, either for eclipse or other eclipse components, please publish them here. A: Update September 2009: see also addresses for eclipse 3.6 Helios For eclipse itself, the eclipse wiki * *3.5milestones http://download.eclipse.org/eclipse/updates/3.5milestones *3.5-I-builds http://download.eclipse.org/eclipse/updates/3.5-I-builds However, the Milestone names are not there yet. (For instance, the build number there is 20080807 is assumed to be 3.5M1) The update site will be added as a location for builds in order to get published to automatically: see bug 248509 Warning: the update process in itself might generate some freeze (see bug 234916) which might be solved by using a local http client (bug 220240). Meaning you should first update your eclipse installation with the ECF_Apache_Httpclient-Based_Provider update site (http://download.eclipse.org/technology/ecf/httpclientrepo), then try the different update sites mentionned for eclipse components. Update May 2009 The page "compare package" now provides all links to different released packages (See links to the left of the page: Europa 3.3, Ganymede 3.4, Ganymede SR1, and Galileo 3.5Mx) The current available Galileo M6 lists packages built with M6 release. That address will soon be not valid since Galileo M7 has just been published (May, 2d 2009). The new Galileo packages (M7) will then be at this address. A: For eclipse 3.6 Helios (see above for eclipse3.5), from "Catching up with Milestones and I-Builds" The p2 repos for Eclipse are not only for the stable releases, but also for the Milestones, I Builds and Nightly builds: See Eclipse Project Updates Sites * *Milestones: http://download.eclipse.org/eclipse/updates/3.6milestones *I-Builds: http://download.eclipse.org/eclipse/updates/3.6-I-builds *Nightly Builds: http://download.eclipse.org/eclipse/updates/3.6-N-builds Prakash G.R. in his post advices: Go to your Preferences and add the required repo in your Available Software Site preferences (and disable all others, it will be slow to update). Also enable the automatic updates. You are done. Whenever there is a new Milestone (or an I-Build), then your Eclipse gets updated automatically to it and you don't have to worry about installing other required plug-ins A: How about this one for Eclipse 3.5? http://download.eclipse.org/releases/galileo
{ "language": "en", "url": "https://stackoverflow.com/questions/138004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Is the best approach a typed or not typed view in ASP.NET MVC? In ASP.NET MVC it's possible to choice between having a typed view were you define in the codebehind what kind of data the view can should expect. But it's also possible to not define this and just pass any kind of data to view in a ViewData container. What would the best model here or should I mix depending on what kind of data we're talking about (maybe just make sure to have data that's critical to the functionality of the view typed and other data not typed?)? I don't really understand why there is a option here ... A: I would recommend always using the strongly typed ViewData... that way you have compile time checking, intellisense, you don't have to do casting in your view, and the ability to refactor your code much easier. A: Earlier releases of the framework required you to choose between a ViewData dictionary and strongly typed view model. Now you can mix the two. Combine this with some of the new features of Preview 5, such as ModelState, validation, and auto-binding to form fields and it becomes more compelling to use the ViewPage for the main model in your view being rendered. You can still add data to the dictionary in the controller pipeline and request it later on using ViewData["key"] ... or even better ViewData.Get("key") from MvcContrib. A: I had this thought too in the past. In my site, I used to strong-type the view, when the view is almost a 1:1 model of the class you are showing. Like showing a list of all users, I type to List, this way I don't need to cast anytime to have the right datatype. In none specific views, I just strong-type to the most "heavy"/used type. In forms, the form itself is the type of the view when returning View(form); ....
{ "language": "en", "url": "https://stackoverflow.com/questions/138009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to call a COM API from Java? Is it possible to call a COM API from Java (specifically the HP/Mercury Quality Center OTA API)? If so, what's the best way? Is something like JACOB appropriate? Code fragments would be helpful for the basics :-) A: after a comparison of all the above, none was totally satisfactory. the most complete solution is in https://github.com/java-native-access/jna now. It supports, * *getting interface to a running COM object *starting a new COM object and returning its interface *calling COM methods and returning results *optional separate COM thread handling *ComEventCallbacks *RunninObjectTable queries *lowlevel COM use *util / high level java proxy abstraction E.g. MsWordApp comObj = this.factory.createObject(MsWordApp.class); Documents documents = comObj.getDocuments(); _Document myDocument = documents.Add(); String path = new File(".").getAbsolutePath(); myDocument.SaveAs(path + "\\abcdefg", WdSaveFormat.wdFormatPDF); comObj.Quit(); A: maybe you should have a look at http://qctools4j.sourceforge.net/ it's a java library used by qclylyn (http://sourceforge.net/apps/mediawiki/qcmylyn/index.php?title=Main_Page) to retrieve defects from QC. unfortunately the COM bridge doesn't work for linux as it loads jacob dlls A: jacob : yes, http://sourceforge.net/projects/jacob-project/ is an active project that will suite your purpose pretty well. you can see multiple examples : http://jacob-project.wiki.sourceforge.net/Event+Callbacks but if you want something that is more tested and are willing to pay money, then go for http://www.nevaobject.com/_docs/_java2com/java2com.htm. A: j-Interop is a Java-COM bridge: j-Interop. It's written in pure Java and licensed under the LGPL v3. It uses the DCOM wire protocol to call COM objects as opposed to the JNI approach used by JACOB. A: You can use J-Integra COM2JAVA tool. The com2java tool generates Java "proxy" classes and interfaces that correspond to the coclasses and interfaces contained in a COM type library. It effectively generates a Java API which you can use to access a COM component from Java.
{ "language": "en", "url": "https://stackoverflow.com/questions/138028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Get Bound Event Handler in Tkinter After a bind a method to an event of a Tkinter element is there a way to get the method back? >>> root = Tkinter.Tk() >>> frame = Tkinter.Frame(root, width=100, height=100) >>> frame.bind('<Button-1>', lambda e: pprint('Click')) # function needed >>> frame.pack() >>> bound_event_method = frame.??? A: The standard way to do this in Tcl/Tk is trivial: you use the same bind command but without the final argument. bind .b <Button-1> doSomething puts "the function is [bind .b <Button-1>]" => the function is doSomething You can do something similar with Tkinter but the results are, unfortunately, not quite as usable: e1.bind("<Button-1>",doSomething) e1.bind("<Button-1>") => 'if {"[-1208974516doSomething %# %b %f %h %k %s %t %w %x %y %A %E %K %N %W %T %X %Y %D]" == "break"} break\n' Obviously, Tkinter is doing a lot of juggling below the covers. One solution would be to write a little helper procedure that remembers this for you: def bindWidget(widget,event,func=None): '''Set or retrieve the binding for an event on a widget''' if not widget.__dict__.has_key("bindings"): widget.bindings=dict() if func: widget.bind(event,func) widget.bindings[event] = func else: return(widget.bindings.setdefault(event,None)) You would use it like this: e1=Entry() print "before, binding for <Button-1>: %s" % bindWidget(e1,"<Button-1>") bindWidget(e1,"<Button-1>",doSomething) print " after, binding for <Button-1>: %s" % bindWidget(e1,"<Button-1>") When I run the above code I get: before, binding for <Button-1>: None after, binding for <Button-1>: <function doSomething at 0xb7f2e79c> As a final caveat, I don't use Tkinter much so I'm not sure what the ramifications are of dynamically adding an attribute to a widget instance. It seems to be harmless, but if not you can always create a global dictionary to keep track of the bindings. A: The associated call to do that for the tk C API would be Get_GetCommandInfo which places information about the command in the Tcl_CmdInfo structure pointed to by infoPtr However this function is not used anywhere in _tkinter.c which is the binding for tk used by python trough Tkinter.py. Therefore it is impossible to get the bound function out of tkinter. You need to remember that function yourself. A: Doesn't appear to be... why not just save it yourself if you're going to need it, or use a non-anonymous function? Also, your code doesn't work as written: lambda functions can only contain expressions, not statements, so print is a no-go (this will change in Python 3.0 when print() becomes a function).
{ "language": "en", "url": "https://stackoverflow.com/questions/138029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create a resizable CDialog in MFC? I have to create a dialog based application, instead of old CFormView type of design. But CDialog produces fixed-size dialogs. How can I create dialog based applications with resizable dialogs? A: Since Visual Studio 2015, you can use MFC Dynamic Dialog Layout, but it seems, there is no way to restrict dialog size to minimal size (still only the old way by handling WM_GETMINMAXINFO). Dynamic layout can be done: * *at design time in resource editor by selecting the control and setting the Moving Type and Sizing Type properties (this emits new AFX_DIALOG_LAYOUT section into .rc file); *or programatically using the CMFCDynamicLayout class. Documentation: Dynamic Layout A: If your using a dialog template then open the dialog template in the resource editor and set the Style property to Popup and the Border property to Resizing. I'm pretty sure this will do the same as what jussij said and set the WS_POPUP and WS_THICKFRAME styles. To set these dynamically then override the PreCreateWindow function and add the following: cs.style |= WS_POPUP | WS_THICKFRAME; A: There is no easy way to do this. Basically, you will need to dynamically layout controls when the window size is changed. See http://www.codeproject.com/KB/dialog/resizabledialog.aspx for an example A: In the RC resource file if the dialog has this style similar to this it will be fixed size: IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201 STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU If the dialog has this style it will be sizeable: IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201 STYLE WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME With these sizable frame options the dialog will be re-sizeable but you will still need to do a lot of work handling the WM_SIZE message to manage the sizing an positioning of the controls within the dialog. A: In addition to setting the style to WS_THICKFRAME, you'll probably also want to have a system to move and resize the controls in a dialog as the dialog is resized. For my own personal use I've created a base class to replace CDialog that has this capability. Derive from this class and in your InitDialog function call the AutoMove function for each child control to define how much it should move and how much it should resize relative to the parent dialog. The size of the dialog in the resource file is used as a minimum size. BaseDialog.h: #if !defined(AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_) #define AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <vector> class CBaseDialog : public CDialog { // Construction public: CBaseDialog(UINT nIDTemplate, CWnd* pParent = NULL); // standard constructor void AutoMove(int iID, double dXMovePct, double dYMovePct, double dXSizePct, double dYSizePct); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBaseDialog) protected: //}}AFX_VIRTUAL protected: //{{AFX_MSG(CBaseDialog) virtual BOOL OnInitDialog(); afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnSize(UINT nType, int cx, int cy); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: bool m_bShowGripper; // ignored if not WS_THICKFRAME private: struct SMovingChild { HWND m_hWnd; double m_dXMoveFrac; double m_dYMoveFrac; double m_dXSizeFrac; double m_dYSizeFrac; CRect m_rcInitial; }; typedef std::vector<SMovingChild> MovingChildren; MovingChildren m_MovingChildren; CSize m_szInitial; CSize m_szMinimum; HWND m_hGripper; }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_) BaseDialog.cpp: #include "stdafx.h" #include "BaseDialog.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CBaseDialog::CBaseDialog(UINT nIDTemplate, CWnd* pParent /*=NULL*/) : CDialog(nIDTemplate, pParent), m_bShowGripper(true), m_szMinimum(0, 0), m_hGripper(NULL) { } BEGIN_MESSAGE_MAP(CBaseDialog, CDialog) //{{AFX_MSG_MAP(CBaseDialog) ON_WM_GETMINMAXINFO() ON_WM_SIZE() //}}AFX_MSG_MAP END_MESSAGE_MAP() void CBaseDialog::AutoMove(int iID, double dXMovePct, double dYMovePct, double dXSizePct, double dYSizePct) { ASSERT((dXMovePct + dXSizePct) <= 100.0); // can't use more than 100% of the resize for the child ASSERT((dYMovePct + dYSizePct) <= 100.0); // can't use more than 100% of the resize for the child SMovingChild s; GetDlgItem(iID, &s.m_hWnd); ASSERT(s.m_hWnd != NULL); s.m_dXMoveFrac = dXMovePct / 100.0; s.m_dYMoveFrac = dYMovePct / 100.0; s.m_dXSizeFrac = dXSizePct / 100.0; s.m_dYSizeFrac = dYSizePct / 100.0; ::GetWindowRect(s.m_hWnd, &s.m_rcInitial); ScreenToClient(s.m_rcInitial); m_MovingChildren.push_back(s); } BOOL CBaseDialog::OnInitDialog() { CDialog::OnInitDialog(); // use the initial dialog size as the default minimum if ((m_szMinimum.cx == 0) && (m_szMinimum.cy == 0)) { CRect rcWindow; GetWindowRect(rcWindow); m_szMinimum = rcWindow.Size(); } // keep the initial size of the client area as a baseline for moving/sizing controls CRect rcClient; GetClientRect(rcClient); m_szInitial = rcClient.Size(); // create a gripper in the bottom-right corner if (m_bShowGripper && ((GetStyle() & WS_THICKFRAME) != 0)) { SMovingChild s; s.m_rcInitial.SetRect(-GetSystemMetrics(SM_CXVSCROLL), -GetSystemMetrics(SM_CYHSCROLL), 0, 0); s.m_rcInitial.OffsetRect(rcClient.BottomRight()); m_hGripper = CreateWindow(_T("Scrollbar"), _T("size"), WS_CHILD | WS_VISIBLE | SBS_SIZEGRIP, s.m_rcInitial.left, s.m_rcInitial.top, s.m_rcInitial.Width(), s.m_rcInitial.Height(), m_hWnd, NULL, AfxGetInstanceHandle(), NULL); ASSERT(m_hGripper != NULL); if (m_hGripper != NULL) { s.m_hWnd = m_hGripper; s.m_dXMoveFrac = 1.0; s.m_dYMoveFrac = 1.0; s.m_dXSizeFrac = 0.0; s.m_dYSizeFrac = 0.0; m_MovingChildren.push_back(s); // put the gripper first in the z-order so it paints first and doesn't obscure other controls ::SetWindowPos(m_hGripper, HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_SHOWWINDOW); } } return TRUE; // return TRUE unless you set the focus to a control } void CBaseDialog::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { CDialog::OnGetMinMaxInfo(lpMMI); if (lpMMI->ptMinTrackSize.x < m_szMinimum.cx) lpMMI->ptMinTrackSize.x = m_szMinimum.cx; if (lpMMI->ptMinTrackSize.y < m_szMinimum.cy) lpMMI->ptMinTrackSize.y = m_szMinimum.cy; } void CBaseDialog::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); int iXDelta = cx - m_szInitial.cx; int iYDelta = cy - m_szInitial.cy; HDWP hDefer = NULL; for (MovingChildren::iterator p = m_MovingChildren.begin(); p != m_MovingChildren.end(); ++p) { if (p->m_hWnd != NULL) { CRect rcNew(p->m_rcInitial); rcNew.OffsetRect(int(iXDelta * p->m_dXMoveFrac), int(iYDelta * p->m_dYMoveFrac)); rcNew.right += int(iXDelta * p->m_dXSizeFrac); rcNew.bottom += int(iYDelta * p->m_dYSizeFrac); if (hDefer == NULL) hDefer = BeginDeferWindowPos(m_MovingChildren.size()); UINT uFlags = SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER; if ((p->m_dXSizeFrac != 0.0) || (p->m_dYSizeFrac != 0.0)) uFlags |= SWP_NOCOPYBITS; DeferWindowPos(hDefer, p->m_hWnd, NULL, rcNew.left, rcNew.top, rcNew.Width(), rcNew.Height(), uFlags); } } if (hDefer != NULL) EndDeferWindowPos(hDefer); if (m_hGripper != NULL) ::ShowWindow(m_hGripper, (nType == SIZE_MAXIMIZED) ? SW_HIDE : SW_SHOW); } A: I have some blog instructions on how to create a very minimalist re-sizeable dialog in MFC. It is basically an implementation of Paulo Messina's posting at CodeProject but with as much extraneous stuff removed as possible, just to help clarify how to do it better. It is fairly straightforward to implement once you've had a bit of practice: the important bits are to: i. ensure you have his CodeProject libraries etc pulled into your project and it all compiles correctly. ii. do the extra initialization required inside the OnInitDialog method: make the gripper visible, set the maximum dilog size, add anchor points to the dialog control items that you wish to 'stretch' etc. iii. Replace usage of CDialog with CResizableDialog at the appropriate points: in the dialog class definition, constructor, DoDataExchange, BEGIN_MESSAGE_MAP, OnInitDialog etc. A: I've tried many MFC layout libraries and found this one the best: http://www.codeproject.com/KB/dialog/layoutmgr.aspx. Check out the comments there for some bug fixes and improvements (disclaimer: some of them by me ;) ). When you use this library, setting the correct resize flags on your window will be handled for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/138040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Find the next TCP port in .NET I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel. A: First open the port, then give the correct port number to the other process. Otherwise it is still possible that some other process opens the port first and you still have a different one. A: Use a port number of 0. The TCP stack will allocate the next free one. A: Here's a more abbreviated way to implement this if you want to find the next available TCP port within a given range: private int GetNextUnusedPort(int min, int max) { if (max < min) throw new ArgumentException("Max cannot be less than min."); var ipProperties = IPGlobalProperties.GetIPGlobalProperties(); var usedPorts = ipProperties.GetActiveTcpConnections() .Where(connection => connection.State != TcpState.Closed) .Select(connection => connection.LocalEndPoint) .Concat(ipProperties.GetActiveTcpListeners()) .Concat(ipProperties.GetActiveUdpListeners()) .Select(endpoint => endpoint.Port) .ToArray(); var firstUnused = Enumerable.Range(min, max - min) .Where(port => !usedPorts.Contains(port)) .Select(port => new int?(port)) .FirstOrDefault(); if (!firstUnused.HasValue) throw new Exception($"All local TCP ports between {min} and {max} are currently in use."); return firstUnused.Value; } A: It's a solution comparable to the accepted answer of TheSeeker. Though I think it's more readable: using System; using System.Net; using System.Net.Sockets; private static readonly IPEndPoint DefaultLoopbackEndpoint = new IPEndPoint(IPAddress.Loopback, port: 0); public static int GetAvailablePort() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(DefaultLoopbackEndpoint); return ((IPEndPoint)socket.LocalEndPoint).Port; } } A: Here is what I was looking for: static int FreeTcpPort() { TcpListener l = new TcpListener(IPAddress.Loopback, 0); l.Start(); int port = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); return port; } A: I found the following code from Selenium.WebDriver DLL Namespace: OpenQA.Selenium.Internal Class: PortUtility public static int FindFreePort() { int port = 0; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 0); socket.Bind(localEP); localEP = (IPEndPoint)socket.LocalEndPoint; port = localEP.Port; } finally { socket.Close(); } return port; } A: If you just want to give a starting port, and let it return to you the next TCP port available, use code like this: public static int GetAvailablePort(int startingPort) { var portArray = new List<int>(); var properties = IPGlobalProperties.GetIPGlobalProperties(); // Ignore active connections var connections = properties.GetActiveTcpConnections(); portArray.AddRange(from n in connections where n.LocalEndPoint.Port >= startingPort select n.LocalEndPoint.Port); // Ignore active tcp listners var endPoints = properties.GetActiveTcpListeners(); portArray.AddRange(from n in endPoints where n.Port >= startingPort select n.Port); // Ignore active UDP listeners endPoints = properties.GetActiveUdpListeners(); portArray.AddRange(from n in endPoints where n.Port >= startingPort select n.Port); portArray.Sort(); for (var i = startingPort; i < UInt16.MaxValue; i++) if (!portArray.Contains(i)) return i; return 0; } A: If you want to get a free port in a specific range in order to use it as local port / end point: private int GetFreePortInRange(int PortStartIndex, int PortEndIndex) { DevUtils.LogDebugMessage(string.Format("GetFreePortInRange, PortStartIndex: {0} PortEndIndex: {1}", PortStartIndex, PortEndIndex)); try { IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] tcpEndPoints = ipGlobalProperties.GetActiveTcpListeners(); List<int> usedServerTCpPorts = tcpEndPoints.Select(p => p.Port).ToList<int>(); IPEndPoint[] udpEndPoints = ipGlobalProperties.GetActiveUdpListeners(); List<int> usedServerUdpPorts = udpEndPoints.Select(p => p.Port).ToList<int>(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); List<int> usedPorts = tcpConnInfoArray.Where(p=> p.State != TcpState.Closed).Select(p => p.LocalEndPoint.Port).ToList<int>(); usedPorts.AddRange(usedServerTCpPorts.ToArray()); usedPorts.AddRange(usedServerUdpPorts.ToArray()); int unusedPort = 0; for (int port = PortStartIndex; port < PortEndIndex; port++) { if (!usedPorts.Contains(port)) { unusedPort = port; break; } } DevUtils.LogDebugMessage(string.Format("Local unused Port:{0}", unusedPort.ToString())); if (unusedPort == 0) { DevUtils.LogErrorMessage("Out of ports"); throw new ApplicationException("GetFreePortInRange, Out of ports"); } return unusedPort; } catch (Exception ex) { string errorMessage = ex.Message; DevUtils.LogErrorMessage(errorMessage); throw; } } private int GetLocalFreePort() { int hemoStartLocalPort = int.Parse(DBConfig.GetField("Site.Config.hemoStartLocalPort")); int hemoEndLocalPort = int.Parse(DBConfig.GetField("Site.Config.hemoEndLocalPort")); int localPort = GetFreePortInRange(hemoStartLocalPort, hemoEndLocalPort); DevUtils.LogDebugMessage(string.Format("Local Free Port:{0}", localPort.ToString())); return localPort; } public void Connect(string host, int port) { try { // Create socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); var localPort = GetLocalFreePort(); // Create an endpoint for the specified IP on any port IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort); // Bind the socket to the endpoint socket.Bind(bindEndPoint); // Connect to host socket.Connect(IPAddress.Parse(host), port); socket.Dispose(); } catch (SocketException ex) { // Get the error message string errorMessage = ex.Message; DevUtils.LogErrorMessage(errorMessage); } } public void Connect2(string host, int port) { try { // Create socket var localPort = GetLocalFreePort(); // Create an endpoint for the specified IP on any port IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort); var client = new TcpClient(bindEndPoint); //client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //will release port when done // Connect to the host client.Connect(IPAddress.Parse(host), port); client.Close(); } catch (SocketException ex) { // Get the error message string errorMessage = ex.Message; DevUtils.LogErrorMessage(errorMessage); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/138043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "81" }
Q: Is there something like Python's getattr() in C#? Is there something like Python's getattr() in C#? I would like to create a window by reading a list which contains the names of controls to put on the window. A: Use reflection for this. Type.GetProperty() and Type.GetProperties() each return PropertyInfo instances, which can be used to read a property value on an object. var result = typeof(DateTime).GetProperty("Year").GetValue(dt, null) Type.GetMethod() and Type.GetMethods() each return MethodInfo instances, which can be used to execute a method on an object. var result = typeof(DateTime).GetMethod("ToLongDateString").Invoke(dt, null); If you don't necessarily know the type (which would be a little wierd if you new the property name), than you could do something like this as well. var result = dt.GetType().GetProperty("Year").Invoke(dt, null); A: There is also Type.InvokeMember. public static class ReflectionExt { public static object GetAttr(this object obj, string name) { Type type = obj.GetType(); BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty; return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null); } } Which could be used like: object value = ReflectionExt.GetAttr(obj, "PropertyName"); or (as an extension method): object value = obj.GetAttr("PropertyName"); A: Yes, you can do this... typeof(YourObjectType).GetProperty("PropertyName").GetValue(instanceObjectToGetPropFrom, null); A: There's the System.Reflection.PropertyInfo class that can be created using object.GetType().GetProperties(). That can be used to probe an object's properties using strings. (Similar methods exist for object methods, fields, etc.) I don't think that will help you accomplish your goals though. You should probably just create and manipulate the objects directly. Controls have a Name property that you can set, for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/138045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: When editing Lisp code, can emacs be configured to display each nested level of parentheses in a different color? In other words, a block of code like this: (setq initial-major-mode (lambda () (text-mode) (font-lock-mode) )) ... would come out looking like something like this: If something like this already exists, what is it? And if it doesn't exist, how should I go about writing it? A: There is the package rainbow-delimiters, which doesn't do exactly what you want, but does just colorize the parentheses - which is a nice subset and allows you to still see the other syntax highlighting provided by the major mode. A: If you need this to help editing, then I suggest turning on coloring the innermost sexp which contains the cursor with a different background color. At least I'm used to this and it is sufficient. A: http://nschum.de/src/emacs/highlight-parentheses/ lets you highlight just the parentheses. A: I think you are looking for something like mwe-color-box.el
{ "language": "en", "url": "https://stackoverflow.com/questions/138056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Detecting file being reopened in Java I'm working on a small Java application (Java 1.6, Solaris) that will use multiple background threads to monitor a series of text files for output lines that match a particular regex pattern and then make use of those lines. I have one thread per file; they write the lines of interest into a queue and another background thread simply monitors the queue to collect all the lines of interest across the whole collection of files being monitored. One problem I have is when one of the files I'm monitoring is reopened. Many of the applications that create the files I'm monitoring will simply restart their logfile when they are restarted; they don't append to what's already there. I need my Java application to detect that the file has been reopened and restart following the file. How can I best do this? A: Could you keep a record of each of the length of each file? When the current length subsequently goes back to zero or is smaller than the last time you recorded the length, you know the file has been restarted by the app? A: using a lockfile is a solution as Jurassic mentioned. Another way is to try and open the file while you're reading the pattern and find if the file has a new size and create time. If the create time is NOT same as when you found it, then you can be sure that it has been recreated. A: You could indicate somewhere on the filesystem that indicates you are reading a given file. Suppose next to the file being read (a.txt), you create a file next to it (a.txt.lock) that indicates a.txt is being read. When your process is done with it, a.txt.lock is deleted. Every time a process goes to open a file to read it, it will check for the lock file beforehand. If there is no lockfile, its not being used. I hope that makes sense and answers your question. cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/138059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: TFS Build Server drop location error We're using TFS Build Server to ensure that all files checked in by developers are going to compile to a working source tree, cuz there's nothing worse than a broken build! Anyway we've having some problems with the drop location that Build Server wants to use, we keep getting this error: TFS209011: Could not create drop location \build-server\drops\project\BuildNumber. No more connections can be mades to this remote computer at this time because there are already as many connections as the computer can accept Since this is being used in a pilot program at the moment we only have 2 projects which are using the Build Server. I've checked the network share and the allowed number of connections is about 100 so I don't really get what the problem is. Only occationally does the problem raise it's head, quite often we'll not have one for days, and then we'll have a bunch in a row. I can't seem to find much info on this either. A: I'm pretty good with TFS - but a dev not a network guy. I would GUESS that while the NETWORK SHARE itself allows 100 connections, is it possible the underlying server it is running on doesn't have some sort of limitation? Have you checked event logs? This problem seems specific enough I would encourage you to post to the official Microsoft forums. A: It looks like the problem is to do with our install of Windows 2003, we have "Web Edition" installed and it is limited to just 10 connections. I ended up with a post of the MSDN forums in which I got this answer: http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3967598&SiteID=1&mode=1
{ "language": "en", "url": "https://stackoverflow.com/questions/138060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to determine whether a drive is network mounted? I am searching for all drives and their contents. I don't want to search network drives. How can I determine if a given drive is network mounted? What I would want further is to get similar information one gets using NET USE command? A: You want the GetDriveType function. A: Also if you would like to add remove drives or check status, check this article out: http://support.microsoft.com/kb/173011 That's using the win32 api.
{ "language": "en", "url": "https://stackoverflow.com/questions/138065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Catching exceptions within .aspx and .ascx pages The questions says everything, take this example code: <ul id="css-id"> <li> <something:CustomControl ID="SomeThingElse" runat="server" /> <something:OtherCustomControl runat="server" /> </li> </ul> Now if an error gets thrown somewhere inside these controlls (that are located in a master page) they will take down the entire site, how would one catch these exceptions? A: You can catch all exception not handled elswhere in the Global.asax page / class. Look at: protected void Application_Error(Object sender, EventArgs e) method. A: Unfortunately an unhandled exception will always error your site. YOu can prevent this a few ways though. * *Use the section in your web.config to show a user friendly message *In your Global.asax - or a Custom Handler - catch your unhandled exception and react accordingly - like this best solution * *Make sure you controls don't throw unhandled exceptions! A: Add a global.asax en implement the Application_Error handler. Use the Server.GetLastError() function to get a handle on the exception thrown. A: Using the global.asax Application_Error method, as described in How to create custom error reporting pages in ASP.NET by using Visual C# .NET. An alternative approach would be to use a HTTP module; this gives you some more flexibility (you can handle errors from multiple applications, for example). A: Do you want to catch the exception and handle it? Or do you want to prevent the Yellow Screen Of Death? If you are trying to prevent the Yellow Screen Of Death, look at handling the Error event on the HttpApplication (in other words, in your Global.asax). See the following MSDN page for more details: http://msdn.microsoft.com/en-us/library/system.web.httpapplication.error.aspx Specifically this paragraph: The exception that raises the Error event can be accessed by a call to the GetLastError method. If your application generates custom error output, suppress the default error message that is generated by ASP.NET by a call to the ClearError method.
{ "language": "en", "url": "https://stackoverflow.com/questions/138071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to log a stored procedure error Scenario: C# apps uses SQL2000. It excecute 3 stored procs within a try catch in the app. In the catch the error is suppressed. Due to some legalities, the c# code cannot be changed and implemented. Q: How do I trap the actual SQL error in the stored proc into a log file or other table? @@Error returns an error message to the app but when evaluated in query analyzer it is always 0 although the 'If @@Error <> 0' does fire. I try to store the @@Error number, but it is always 0. Please help. A: @@ERROR is reset to 0 when you check it. Why? Because it reflects the status of the last statement executed. IF @@ERROR <> 0 ... is a statement, and that statement succeeds, causing @@ERROR to be set to 0. The proper way to examine and operate on @@ERROR values is as follows: DECLARE @ErrorCode INT INSERT INTO Table ... SET @ErrorCode = @@ERROR IF @ErrorCode <> 0 BEGIN INSERT INTO ErrorLog (ErrorCode, Message) VALUES (@ErrorCode, 'The INSERT operation failed.') END A: Haven't got an example to hand, but look at using RAISERROR ... WITH LOG see: http://msdn.microsoft.com/en-us/library/aa238452(SQL.80).aspx for more on this. Or use: xp_logevent {error_number, 'message'} [, 'severity'] to write to the event log. More details at http://msdn.microsoft.com/en-us/library/aa260695(SQL.80).aspx A: Didn't try it myself but I guess you can monitor the errors with Sql Server Profiler. A: ALTER PROCEDURE [dbo].[StoreProcedureName] ( parameters ) AS BEGIN SET NOCOUNT On BEGIN TRY --type your query End Try BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage RETURN -1 END CATCH End
{ "language": "en", "url": "https://stackoverflow.com/questions/138073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Emulate hard disk in .NET Is there a way to emulate a disk drive in .NET, intercepting read/write/lock operations? I would like to create something with a front-end similar to GMail Drive in C#. Thanks, Tom A: On Linux you can use the Mono.Fuse API (http://www.jprl.com/Projects/mono-fuse.html) to implement .NET-based file systems with user-land code. A: You could see how http://www.truecrypt.org/ is doing it. It's doing exactly that either by using files or by using a drive or a partition. And then it mounts the file as if it were a real drive. Now, probably that the source code is a bit complex ;) A: I use the Eldos Callback File System myself for this purpose, but although it's good, it's not exactly cheap. There are some free/cheap projects as well, and I'm sure one of them was mentioned in a similar question on SO recently -- can't find it anymore at the moment, though. Stability tends to be a major issue, though, as layered Windows file system drivers aren't trivial. A: Not really, .Net sits on top of OS functionality like disk access to give you things like managed file accessors.You could write all of it in managed C#, but you'd need unmanaged calls to make the OS treat it like another drive. All the shell extension stuff is COM: http://msdn.microsoft.com/en-us/library/cc147467(VS.85).aspx You could, however, write a .Net desktop app that allowed drag-drop from explorer and that looked like a file system view. A: You could also use EZNamespaceExtension for .NET. This gives you integration with Windows Explorer. Not too expensive given that the license is per developer and not distribution. Update Big problem with EZNamespaceExtension.NET. It hasn't been updated for a long time. LogicNP seems to have lost their interest in EZNamespaceExtension.NET because there hasn't been a release with new a handful of features since 2010. No .NET 4 support and no support for Windows 8 ribbon toolbar A: I've just checkout EZNamespaceExtension for .NET with the above link. It seem that they keep up to date as release 2013 version. But not sure that can answer the question of Showing as a Drive in Explorer.exe (AFAIK. it can't show as drive letter)
{ "language": "en", "url": "https://stackoverflow.com/questions/138080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to protect application against duplication of a virtual machine We are using standard items such as Hard Disk and CPU ID to lock our software licenses to physical hardware. How can we reduce the risk of customers installing onto a virtual machine and then cloning the virtual machine, bypassing our licensing? A: One approach is to have a licensing server. When you enter a license code into the client (on a VM), it contacts the server and sends it its license code and other information. It contacts it repeatedly (you define the interval -- maybe once every few hours) asking 'Am I still valid"? Along with this request, it sends a unique ID. The server replies 'Yes, you are valid', and sends a new unique ID back to the client. The client sends this unique ID back with its next request to the server. The server verifies this is the same ID it sent to the client for that license, the previous request. If the VM is duplicated, the next time it asks the server 'Am I valid?', the unique ID will be incorrect either for it, or for the other VM. Both will not continue to work. You will need to determine what to do if the server goes down, or the network goes down, such that the client cannot communicate with the server. Do you immediately disable your software? Bad idea! Don't make your customers angry. You'll want to give them a grace period. How long should this be? A few days? Weeks? Let's say you give them a 1-month grace period. In theory, they could clone the parent VM just after entering the license key, then restore the other VMs to this clone just before their grace period runs out, disabling network access to them. This would be a hassle for your customers though, just to have pirated additional copies of your software. You have to determine what kind of grace period won't hassle your legitimate customers, while hopefully giving you the protection you seek. Additional protection could be achieved by verifying that the VM's clock is set correctly. This would prevent the above approach to pirating. Another consideration is that a savvy user could write their own licensing server to communicate with the VM instances, and tell them all 'you're good' -- so encrypting the communication could help deter this. How far you want to go here really depends on how much you think pirating really might be an issue with your customers. In the end you won't be able to stop true pirates who have time on their hands, but you can keep honest users honest. A: License. Tell your users, they may not run unlicensed copies. We are actually failing to buy a license for a software at the moment, because the vendor is scared of virtual machines: The infrastructure for our department is being moved to a centralized virtualized sollution and we have to fight the vendor to be allowed to buy a license for his software! Don't be afraid of paying users. People too cheep to buy licenses are going to look for another sollution and will be too much hassle anyway. (good luck telling your boss that, though...) A: There is no good reason to lock to a physical machine. Last I checked computers can break down, and then the user is probably going to be inconvenienced not only by a dead computer, but by having to call you to get the software locked to a new machine. If you must do draconian license management use a (local) management server and have running copies verify that they have a license every few minutes. Just realize that whatever you do if someone really wants to use your software without paying you they will find a way. A: You need something outside the computer "hardware" to authenticate against. Most companies choose hardware keys (dongles) in for software with a high cost where users will put up with it. Other companies use online methods - if more than one user with CPUID and other hardware is concurrently using a given license, then disallow another instantiation, or close the existing instantiation. You have to choose protection according to your needs and the consumer's willingness to jump through your anti-piracy hoops. -Adam A: There's not a lot you can do AFAIK, except require periodic online activation. We have problems with people Norton-ghosting physical machines. Apparently HDD serial numbers are ghosted too. A: If your software runs under a VM, then it will run under any number of cloned VMs. Therefore, the only option seems to prevent it running under a VM at all. Here's an article about virtual machine detection: Detect if your program is running inside a Virtual Machine and one about thwarting it. By the way, cloning a VM is usually enough of a hassle to deter casual users from bypassing your licensing and those hell bent on cracking will probably find a way to bypass it anyway. A: "Don't bother" is the short version. It's non trivial enough for your clients to do it that if they are doing that, then either they won't pay for what they use no matter what (they will not use it unless they can get it for free) or you are just flat charging to much (as in you are gouging.) The "real" customer will generally pay for the stuff. From what I've seen, places like businesses will generally consider it not worth the effort. A: I know some virtual machine software (at least VMware) have features that allow software to detect virtualization. But there is no foolproof way, it's possible to patch such features away anyway. Mysteriously changing performance (due to CPU spikes in the host) could also be used, reliability is questionable. There is a plethora of "signs of being virtualized", but they tend to be not 100% reliable. A: It is a problem, and any savvy user will be able to defeat pretty much anything you do about it. Unsavvy users might get caught by behaviors like VmWare's player that changes MAC and other IDs of the virtual machine when you move it, presumably in a nod to this kind of issue. The best solution is likely to use a license server instead, since that server will count the number of active licenses. Node locking is easier to defeat, and using a server tends also to push responsibility onto an IT department that is more sensitive to not breaking license agreements compared to individual users who just want to get their job done as quickly as possible. But in the end, I agree that it all falls back to proper license language and having customers you trust somewhat. If you think that people are making a fool of you in this way, you should not be selling your software to them in the first place... A: If your software was required to under on a VM what about this concept: * *on the host machine you create a compiled program that run eg. every half hour, which reads the Hard Disk and CPU ID, and then stores that together with the current timestamp in a file together with a salted hash of all that information. *you then require that the folder with the file is shared with the VM. *in your compiled software within the VM you can then read this file and check that the timestamp is recent and the hash is valid. Or better yet, have the host program somehow communicate with the software in the VM directly. Couldn't this be an okay solution? Not as secure as using a hardware key (like Yubikey) but you would have to be quite tech savvy to break it...?
{ "language": "en", "url": "https://stackoverflow.com/questions/138081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: How to add a Page to Frame using code in WPF I have a Window where I have put a Frame. I would like to add a Page to the Frame when I click a button that is also on the Window but not in the Frame. There are several buttons in the Window and each click on a button should load a different Page in the Frame. Since I'm a total newbie on this WPF stuff it's quite possible that this approach is not the best and I have thought about replacing the Frame with a Canvas and then make UserControls instead of Pages that will be added to the Canvas. I welcome any ideas and suggestions on how to best solve this. I aiming for a functionality that is similar to the application Billy Hollis demonstrated in dnrtv episode 115. (http://dnrtv.com/default.aspx?showID=115). A: the Frame class exposes a method named "Navigate" that takes the content you want to show in your frame as parameter. try calling myFrame.Navigate(myPageObject); this should work A: yourFramName.NavigationService.Navigate(yourPageObject) e.g Frame1.NavigationService.Navigate(new Page1());
{ "language": "en", "url": "https://stackoverflow.com/questions/138096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do I find my PID in Java or JRuby on Linux? I need to find the PID of the current running process on a Linux platform (it can be a system dependent solution). Java does not support getting the process ID, and JRuby currently has a bug with the Ruby method, Process.pid. Is there another way to obtain the PID? A: Only tested in Linux using Sun JVM. Might not work with other JMX implementations. String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; A: If you have procfs installed, you can find the process id via the /proc/self symlink, which points to a directory whose name is the pid (there are also files here with other pertinent information, including the PID, but the directory is all you need in this case). Thus, with Java, you can do: String pid = new File("/proc/self").getCanonicalFile().getName(); In JRuby, you can use the same solution: pid = java.io.File.new("/proc/self").canonical_file.name Special thanks to the #stackoverflow channel on free node for helping me solve this! (specifically, Jerub, gregh, and Topdeck) A: You can use the JNI interface to call the POSIX function getpid(). It is quite straight forward. You start with a class for the POSIX functions you need. I call it POSIX.java: import java.util.*; class POSIX { static { System.loadLibrary ("POSIX"); } native static int getpid (); } Compile it with $ javac POSIX.java After that you generate a header file POSIX.h with $ javah -jni POSIX The header file contains the C prototype for the function with wraps the getpid function. Now you have to implement the function, which is quite easy. I did it in POSIX.c: #include "POSIX.h" #include <sys/types.h> #include <unistd.h> JNIEXPORT jint JNICALL Java_POSIX_getpid (JNIEnv *env, jclass cls) { return getpid (); } Now you can compile it using gcc: $ gcc -Wall -I/usr/lib/jvm/java-1.6.0-sun-1.6.0.21/include -I/usr/lib/jvm/java-1.6.0-sun-1.6.0.21/include/linux -o libPOSIX.so -shared -Wl,-soname,libPOSIX.so POSIX.c -static -lc You have to specify the location where your Java is installed. That's all. Now you can use it. Create a simple getpid program: public class getpid { public static void main (String argv[]) { System.out.println (POSIX.getpid ()); } } Compile it with javac getpid.java and run it: $ java getpid & [1] 21983 $ 21983 The first pid is written by the shell and the second is written by the Java program after shell prompt has returned. ∎ A: Spawn a shell process that will read its parent's pid. That must be our pid. Here is the running code, without exception and error handling. import java.io.*; import java.util.Scanner; public class Pid2 { public static void main(String sArgs[]) throws java.io.IOException, InterruptedException { Process p = Runtime.getRuntime().exec( new String[] { "sh", "-c", "ps h -o ppid $$" }); p.waitFor(); Scanner sc = new Scanner(p.getInputStream()); System.out.println("My pid: " + sc.nextInt()); Thread.sleep(5000); } } This solution seems to be the best if the PID is to be obtained only to issue another shell command. It's enough to wrap the command in back quotes to pass it as an argument to another command, for example: nice `ps h -o ppid $$` This may substitue the last string in the array given to exec call. A: Java 9 finally offers an official way to do so with ProcessHandle: ProcessHandle.current().pid(); This: * *First gets a ProcessHandle reference for the current process. *In order to access its pid. No import necessary as ProcessHandle is part of java.lang. A: You can try getpid() in JNR-Posix. It also has a Windows POSIX wrapper that calls getpid() off of libc. No JNI needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/138097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How do I add a type to GWT's Serialization Policy whitelist? GWT's serializer has limited java.io.Serializable support, but for security reasons there is a whitelist of types it supports. The documentation I've found, for example this FAQ entry says that any types you want to serialize "must be included in the serialization policy whitelist", and that the list is generated at compile time, but doesn't explain how the compiler decides what goes on the whitelist. The generated list contains a number of types that are part of the standard library, such as java.lang.String and java.util.HashMap. I get an error when trying to serialize java.sql.Date, which implements the Serializable interface, but is not on the whitelist. How can I add this type to the list? A: The whitelist is generated by the GWT compiler and contains all the entries that are designated by the IsSerializable marker interface. To add a type to the list you just need to make sure that the class implements the IsSerializable interface. Additionally for serialization to work correctly the class must have a default no arg constructor (constructor can be private if needed). Also if the class is an inner it must be marked as static. A: There's a workaround: define a new Dummy class with member fields of all the types that you want to be included in serialization. Then add a method to your RPC interface: Dummy dummy(Dummy d); The implementation is just this: Dummy dummy(Dummy d) { return d; } And the async interface will have this: void dummy(Dummy d, AsyncCallback< Dummy> callback); The GWT compiler will pick this up, and because the Dummy class references those types, it will include them in the white list. Example Dummy class: public class Dummy implements IsSerializable { private java.sql.Date d; } A: IMHO the simpliest way to access whitelist programmatically is to create a class similar to this: public class SerializableWhitelist implements IsSerializable { String[] dummy1; SomeOtherThingsIWishToSerialize dummy2; } Then include it in the .client package and reference from the RPC service (so it gets analyzed by the compiler). I couldn't find a better way to enable tranfer of unparameterized maps, which is obviously what you sometimes need in order to create more generic services... A: Any specific types that you include in your service interface and any types that they reference will be automatically whitelisted, as long as they implement java.io.Serializable, eg: public String getStringForDates(ArrayList<java.util.Date> dates); Will result in ArrayList and Date both being included on the whitelist. It gets trickier if you try and use java.lang.Object instead of specific types: public Object getObjectForString(String str); Because the compiler doesn't know what to whitelist. In that case if the objects are not referenced anywhere in your service interface, you have to mark them explicitly with the IsSerializable interface, otherwise it won't let you pass them through the RPC mechanism. A: to ensure the desired result delete all war/<app>/gwt/*.gwt.rpc A: The whitelist is generated by the gwt compiler and contains all the entries that are designated by the IsSerializable marker interface. To add a type to the list you just need to make sure that the class implements the IsSerializable interface. -- Andrej This is probably the easiest solution. The only thing to remember with this is that all the classes that you want to serialize should have "public, no-argument" constructor, and (depending upon requirements) setter methods for the member fields. A: To anyone who will have the same question and doesn't find previous answers satisfactory... I'm using GWT with GWTController, since I'm using Spring, which I modified as described in this message. The message explains how to modify GrailsRemoteServiceServlet, but GWTController calls RPC.decodeRequest() and RPC.encodeResponseForSuccess() in the same way. This is the final version of GWTController I'm using: /** * Used to instantiate GWT server in Spring context. * * Original version from <a href="http://docs.google.com/Doc?docid=dw2zgx2_25492p5qxfq&hl=en">this tutorial</a>. * * ...fixed to work as explained <a href="http://blog.js-development.com/2009/09/gwt-meets-spring.html">in this tutorial</a>. * * ...and then fixed to use StandardSerializationPolicy as explained in * <a href="http://markmail.org/message/k5j2vni6yzcokjsw">this message</a> to allow * using Serializable instead of IsSerializable in model. */ public class GWTController extends RemoteServiceServlet implements Controller, ServletContextAware { // Instance fields private RemoteService remoteService; private Class<? extends RemoteService> remoteServiceClass; private ServletContext servletContext; // Public methods /** * Call GWT's RemoteService doPost() method and return null. * * @param request * The current HTTP request * @param response * The current HTTP response * @return A ModelAndView to render, or null if handled directly * @throws Exception * In case of errors */ public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { doPost(request, response); return null; // response handled by GWT RPC over XmlHttpRequest } /** * Process the RPC request encoded into the payload string and return a string that encodes either the method return * or an exception thrown by it. * * @param payload * The RPC payload */ public String processCall(String payload) throws SerializationException { try { RPCRequest rpcRequest = RPC.decodeRequest(payload, this.remoteServiceClass, this); // delegate work to the spring injected service return RPC.invokeAndEncodeResponse(this.remoteService, rpcRequest.getMethod(), rpcRequest.getParameters(), rpcRequest.getSerializationPolicy()); } catch (IncompatibleRemoteServiceException e) { return RPC.encodeResponseForFailure(null, e); } } /** * Setter for Spring injection of the GWT RemoteService object. * * @param RemoteService * The GWT RemoteService implementation that will be delegated to by the {@code GWTController}. */ public void setRemoteService(RemoteService remoteService) { this.remoteService = remoteService; this.remoteServiceClass = this.remoteService.getClass(); } @Override public ServletContext getServletContext() { return servletContext; } public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } } A: I found that just putting it in the client package or using it in a dummy service interface was not sufficient as it seemed the system optimized it away. I found it easiest to create a class that derived from one of the types already used in the service interface and stick it in the client package. Nothing else needed. public class GWTSerializableTypes extends SomeTypeInServiceInterface implements IsSerializable { Long l; Double d; private GWTSerializableTypes() {} } A: I had this problem but ended up tracing the problem back to a line of code in my Serializable object: Logger.getLogger(this.getClass().getCanonicalName()).log(Level.INFO, "Foo"); There were no other complaints before the exception gets caught in: @Override protected void serialize(Object instance, String typeSignature) throws SerializationException { assert (instance != null); Class<?> clazz = getClassForSerialization(instance); try { serializationPolicy.validateSerialize(clazz); } catch (SerializationException e) { throw new SerializationException(e.getMessage() + ": instance = " + instance); } serializeImpl(instance, clazz); } And the business end of the stack trace is: com.google.gwt.user.client.rpc.SerializationException: Type 'net.your.class' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = net.your.class@9c7edce at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:619)
{ "language": "en", "url": "https://stackoverflow.com/questions/138099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Delphi Pop Up menu visibility Is there a way in Delphi 7 to find out if a pop-up menu is visible (shown on the screen) or not, since it lacks a Visible property. A: You could make your own flag by setting it in the OnPopup event. The problem is knowing when the popupmenu is closed. Peter Below has a solution for that. But my I ask why you would want this? Maybe there is a better way to solve the underlying problem. A: This seems to be a bit simpler (I used Delphi 2007): In your WM_CONTEXTMENU message handler, before calling the inherited handler, the popup menu is about to be shown, you can set your flag. After calling inherited, the popup menu has been closed, reset your flag. procedure TForm1.WMContextMenu(var Message: TWMContextMenu); begin FPopupActive := True; try OutputDebugString(PChar(Format('popup opening', []))); inherited; finally FPopupActive := False; OutputDebugString(PChar(Format('popup closed', []))); end; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/138105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Change order of images in icon file Is there an app that can change the order of images inside an icon? Thanks! A: What you'll need to do that is a resource editor. A google search will reveal many free ones out there. The restorator is a great one, but not free and over-priced IMO. Any decent resource editor will allow you to see icons in the exe or dll and save them or replace them. I don't know of any that will allow you to reorder them, but just about any out there would allow you to save the icons out and then replace them back in the exe/dll in whatever order you'd like. A: The only resource editor I know of that will allow you to re-order the embedded icons including png compressed vista icons is Resource Tuner Console. A: You can change the image order using Pixelformer (an icon/bitmap editor). Import the icon, reorder the images as you wish, then export it back. A: Using a resource editor is not an easy way to do this because you have to edit both ICON and ICON GROUP and I tried to do this with Resource Hacker and could not do it. I found Easy Icon Maker is able to rearrange the order of the icons properly... it's the only icon editor that I found with this option, and I tried about half a dozen. The editor itself is not nearly as good as IcoFX (http://portableapps.com/apps/graphics_pictures/icofx_portable) Why would you want to do this? Well there are certain times when Windows will use the first icon file that matches the size, but this may not be the color-depth that you want... for instance if you are on an older machine like Windows 2000 that doesn't support Alpha Channels then putting these at the beginning of your ICO file will cause Windows 2000 to try to render it so it results in black dots all over the image.
{ "language": "en", "url": "https://stackoverflow.com/questions/138115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What happens when I click the Stop button on the browser? Let's say I click a button on a web page to initiate a submit request. Then I suddenly realize that some data I have provided is wrong and that if it gets submitted, then I will face unwanted consequences (something like a shopping request where I may be forced to pay up for this incorrect request). So I frantically click the Stop button not just once but many times (just in case). What happens in such a scenario? Does the browser just cancel the request without informing the server? If in case it does inform the server, does the server just kill the process or does it also do some rolling back of all actions done as part of this request? I code in Java. Does Java have any special feature that we can use to detect STOP requests and rollback whatever we did as part of this transaction? A: Generally speaking, the server will not know that you've hit stop, and the server-side process will complete. At the point that the server tries to send the response data back to the client, you may see an error because the connection was closed, but equally you may not. What you won't get is the server thread being suddenly interrupted. You can use various elaborate mechanisms to mitigate this, like having the send send frequent ajax calls to the server that say "still waiting", and have the server perform its processing in a new thread which checks these calls, but that doesn't solve the problem completely. A: A Web Page load from a browser is usually a 4 step process (not considering redirections): * *Browser sends HTTP Request, when the Server is available *Server executes code (for dynamic pages) *Server sends the HTTP Response (usually HTML) *Browser renders HTML, and asks for other files (images, css, ...) The browser reaction to "Stop" depends on the step your request is at that time: * *If your server is slow or overloaded, and you hit "Stop" during step 1, nothing happens. The browser doesn't send the request. *Most of the times, however, "Stop" will be hit on steps 2, 3 and 4, and in those steps your code is already executed, the browser simply stops waiting for the response (2), or receiving the response (3), or rendering the response (4). The HTTP call itself is always a 2 steps action (Request/Response), and there is no automatic way to rollback the execution from the client A: Since this question may attract attention for people not using Java, I thought I would mention PHPs behavior in regard to this question, since it is very surprising. PHP internally maintains a status of the connection to the client. The possible values are NORMAL, ABORTED and TIMEOUT. While the connection status is NORMAL, life is good and the script will continue to execute as expected. If the user clicks the Stop button in their browser, the connection is typically closed by the client and the status changes to ABORTED. A change of status to ABORTED will immediately end execution of the running script. As an aside, the same thing happens when the status changes to TIMEOUT (PHPs setting for the allowed run-time of scripts is exceeded). This behavior may be useful in certain circumstances, but there are others where it could be problematic. It seems that it should be safe to abort at any time during a proper GET request; however, aborting in the middle of a request that makes a change on the server could lead to only partially completed changes. Check out the PHP manual's entry on Connection Handling to see how to avoid complications resulting from this behavior: http://www.php.net/manual/en/features.connection-handling.php A: The client will immediately stop transmitting data and close its connection. 9 out of 10 times your request will already have got through (perhaps due to OS buffers being "flushed" to the server). No extra information is sent to the server informing it that you stopped your request. A: Your submit in important scenarios should have two stages. Verify and submit. If the final submit goes though, you commit any tranactions. I cant think of any other way really to avoid that situation, other than allowing your user to undo his actions after a commit. for example The order example, after the order is done to allow your customers to change their mind and canel the order if it has not been shipped yet. Of course its extra code you need to write to suuport that.
{ "language": "en", "url": "https://stackoverflow.com/questions/138116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: how to send rich text message in system.net.mail how to send rich text message in system.net.mail need code for send a mail as html A: System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(); mm.Body = "<html>...</html>"; mm.IsBodyHtml = true; A: //create the mail message MailMessage mail = new MailMessage(); //set the addresses mail.From = new MailAddress("me@mycompany.com"); mail.To.Add("you@yourcompany.com"); //set the content mail.Subject = "This is an email"; mail.Body = "<b>This is bold</b> <font color=#336699>This is blue</font>"; mail.IsBodyHtml = true; //send the message SmtpClient smtp = new SmtpClient("127.0.0.1"); smtp.Send(mail); A: You should be aware, that not every person/mailclient can present a message formatted in HTML. If you rely on layout to make your message clear this can be a problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/138117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a very big bitmap in C++/MFC / GDI I'd like to be able to create a large (say 20,000 x 20,000) pixel bitmap in a C++ MFC application, using a CDC derived class to write to the bitmap. I've tried using memory DCs as described in the MSDN docs, but these appear to be restricted to sizes compatible with the current display driver. I'm currently using a bitmap print driver to do the job, but it is extremely slow and uses very large amounts of intermediate storage due to spooling GDI information. The solution I'm looking for should not involve metafiles or spooling, as the model that I am drawing takes many millions of GDI calls to render. I could use a divide and conquer approach via multiple memory DCs, but it seems like a pretty cumborsome and inelegant technique. any thoughts? A: CDC and CBitmap appears to only support device dependant bitmaps, you might have more luck creating your bitmap with ::CreateDIBSection, then attaching a CBitmap to that. The raw GDI interfaces are a little hoary, unfortunately. You probably won't have much luck with 20,000 x 20,000 at 32 BPP, at least in a 32-bit application, as that comes out at about 1.5 GB of memory, but I got a valid HBITMAP back with 16 bpp: BITMAPINFOHEADER bmi = { sizeof(bmi) }; bmi.biWidth = 20000; bmi.biHeight = 20000; bmi.biPlanes = 1; bmi.biBitCount = 16; HDC hdc = CreateCompatibleDC(NULL); BYTE* pbData = 0; HBITMAP hbm = CreateDIBSection(hdc, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, (void**)&pbData, NULL, 0); DeleteObject(SelectObject(hdc, hbm)); A: This is unusual as I often created a DC based on the screen that will be used for a bitmap image that is much larger than the screen - 3000 pixels plus in some cases - with no problems at all. Do you have some sample code showing this problem in action? A: Considering such a big image resolution, you cannot create the image using compatible bitmaps. Example: pixel depth = 32 bits = 4 bytes per pixel pixel count = 20.000 * 20.000 = 400.000.000 total bytes = pixel count * 4 = 1.600.000.000 bytes = 1.562.500 kb ~= 1525 MB ~= 1.5GB I'm speculating about the final intentions, but suppose you want to create and allow users to explore an immense map with very detailed zooms. You should create a custom image file format; you can put inside that file various layers containing grids of bitmaps for example, to speedup rendering. The render process can use GDI DIBs or GDI+ to create partial images and then render them together. Of course this need some experimenting/optimizing to reach the perfect user feeling. good luck A: To keep your memory usage within acceptable limits, you'll have to use your 'divide and conquer' strategy. It's not a hack, if implemented right it's actually a very elegant way of dealing with bitmaps of unlimited size. If you design it right, you can combine the 'only render/show part of the image', 'render the whole image at low resolution for on-screen display' and 'render the whole thing to an on-disk bitmap' approaches in one engine and shield users of your code (most likely yourself in two weeks ;) ) from the internals. I work on a product with the same issues: rendering (potentially large) maps either to the screen or to .bmp files. A: If the image has to be this resolution - say a hi-res scan of an x-ray - then you might want to look at writing custom spooling routines for it - 1.5 gb is very expensive - even for modern desktops. If it is vector based then you can look at SVG as it supports view ports and most allow you to render to other formats. I use SVG to JPG via Batik (java) so it is possible to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/138122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When does the Community believe that it is appropriate to use a Singleton? Possible Duplicate: Singleton: How should it be used Following on from Ewan Makepeace 's excellent earlier question about the Singleton pattern, I thought I would ask "when does the Community believe that it is appropriate to use a Singleton?" Let me offer up an example to critique: I have an "IconManager" singleton. It begins by reading a properties file which indicates where my icons are located on disk, and then reads all the icons and caches them for future use. The icons can be used all over my UI (tabs, tables, frames etc)... hence accessing them via a static Singleton method is very convinent. I also want to make sure that the icons are read once and only once (if would be very slow to read them from disk each time I needed one) Does the community believe this is an appropriate use of a Singleton? If not, how else might it have been implemented? What other valid uses of Singletons might there be? A: An alternative approach would be to create an instance of your class that loads up the icons and then you pass a reference to this instance to each and every control that needs to access the resources. That way in the future you could have more than one icon loader and pass them around as needed. More flexible for the future but with the rather large downside of making you pass the reference around to a zillion controls. A: Your IconManager implements the factory pattern, it builds icons. And you probably only need one factory to build icons. So no problems for this case to use a singleton IMHO. I've built software with several of these centralized factories and everything worked out fine. See also this thread: Most common examples of misuse of singleton class A: A good use of the singleton is when accessing a resource that may only have one active connection. There are many hardware devices that have this limitation. Let's say you are connecting to a CCTV camera that only allows one connection. The Singleton pattern would create this connection on first use and keep it open. Whenever you needed a picture from the camera, possibly from multiple sources, you can hit the Singleton knowing that, al other problems considered, the picture will be available. If the camera has a slow initial connection time too, holding the connection open in this way rather than opening the connection, grabbing a picture and closing the connection again could be much more efficient. A: I have actually never used a singleton, but haven't used design patterns much. I think that they ae very valuable when other patterns call for them like the Factory and Gateway patterns. However, they almost never are good all by themselves. You might want to consider the Monostate Pattern which gives you all of the benefits of the singleton without many of the drawbacks. This also allows you to have a rich object that has state that just happens to have the global properties that you are looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/138124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to split a string (e.g. a long URL) in a table cell using CSS? Here's the situation: I'm trying my hand at some MySpace page customisations. If you've ever tried [stackoverflow], I'm sure you understand how frustrating it can be. Basically it can be all customised via CSS, within a certain set of rules (e.g. the '#' character is not allowed...how useful!). Have a look at this blog if you want more info, I used it as the basis for my customisations So the only problem is with the comments section, where 'friends' post whatever they feel like. It already has... max-width:423px; ...set on the table, but I've discovered if long URLs are posted in the comment section, it blows out the table width, regardless of the max setting! Question: Is there a way to manage text that is going to push the width of the table? Perhaps splitting/chopping the string? Or is there more I should be doing..? The URLs are posted as text, not hrefs. Using Firefox and Firebug btw. Edit: Also javascript is not allowed ;) Another edit Just checked with IE7, and it seems to work.. so firefox is being the hassle in this case.. A: Have you tried the various values for the "overflow" css property? I think that may do what you need in some permutation. A: a few browsers support word-wrap ex. <div style="width: 50px; word-wrap: break-word">insertsuperlongwordhereplease</div> browser support currently is IE / Safari / Firefox 3.1 (Alpha) A: Your options are pretty limited, if you are using only CSS. You can try overflow: hidden to hide the offending parts. CSS 3 supports text-wrap, but support for it is probably non-existent. IIRC there is an IE-only css-property for doing the same thing, but I can't remember it at the moment and my Google-Fu fails me.
{ "language": "en", "url": "https://stackoverflow.com/questions/138132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there a standard framework for .NET parameter validation that uses attributes? Is there a standard framework (maybe part of Enterprise Library... or .NET itself) that allows you to do common parameter validation in method attributes? A: The Microsoft Enterprise Library has the Microsoft.Practices.EnterpriseLibrary.Validation library/namespace which allows validation using attributes. A: Microsoft Code Contracts, which are part of .NET Framework since 4.0 CTP and are available for earlier .NET Framework versions as a stand-alone package, allow to specify coding assumptions. This includes specifying pre-conditions which can verify parameters. An example use for parameter checking would be (copied from Code Contracts documentation): public Rational(int numerator, int denominator) { Contract.Requires(denominator ! = 0); this.numerator = numerator; this.denominator = denominator; } The benefit of using Code Contracts is that it is a library which will be part of future .NET Framework releases, so sooner or later you will have one dependency less in your application. EDIT: Just noticed that your specifically asking for a library that uses Attributes for argument checking... that Code Contracts does not. The reason why Code Contracts does not use attributes is listed in their FAQ: The advantage of using custom attributes is that they do not impact the code at all. However, the benefits of using method calls far outweigh the seemingly natural first choice of attributes: Runtime support: Without depending on a binary rewriter, contracts expressed with attributes cannot be enforced at runtime. This means that if there are preconditions (or other contracts) that you want enforced at runtime, you need to either duplicate the contracts in the code or else include a binary rewriter in your build process. Contract.RequiresAlways serves both as a declarative contract and as a runtime-checked validation. Need for parsing: Since the values that can be used with custom attributes are limited, conditions end up being encoded as strings. This requires defining a new language that is appropriate for all source languages, requires the strings to be parsed, duplicating all of the functionality the compiler already possesses. Lack of IDE support: Expressed as strings, there is no support for Intellisense, type checking, or refactoring, all of which are available for authoring contracts as code. A: While Microsoft Code Contracts are out for a while, they are still hosted in MS Research and you cannot use configuration (app.config/database etc.) to switch on/off or even change rules. My library Bouncer does provide declarive rule definition: attributes in source code or app.config entries for rules at the entity class/property level. The library is opensource under LGPL (you can freely use it in commercial products). If you configure the rules via app.config you can adjust the rule settings without the need of a recompile. A: Dynamic Data for ASP.NET (and ASP.NET MVC) lets you do validation for model properties using attributes. A: You could also use postsharp and implement your own attributes for validation. A: Here is an example using PostSharp http://dpatrickcaldwell.blogspot.com/2009/03/validate-parameters-using-attributes.html
{ "language": "en", "url": "https://stackoverflow.com/questions/138133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: BUILTIN\Administrators removed - how to undo it SQL Server 2000 Standard, Windows 2003 My coworker removed 'BUILTIN\Administrators' group from SQL Server which results in 'SQL Server Agent' not working. All my TSQLs to synchronize databases stopped working. I have Administrator rights on the server and my database user is in sysadmin role. Does any one have idea how to bring 'BUILTIN\Administrators' back without restoring master database from backup? Edit: When I try to add Administrators or MACHINENAME\Administrators using Enterprise Manager I have this group on the list to choose, but when I accept my choice I have error: Error 15041: Windows NT user or group 'MACHINENAME\Administrators' not found. Check the name again of course instead of MACHINENAME I see my server name Edit2: Found it * *Login as sysadmin *Run following TSQL queries EXEC sp_grantlogin 'BUILTIN\Administrators' and EXEC sp_addsrvrolemember 'BUILTIN\Administrators','sysadmin' A: You don't want to re-add 'BUILTIN\Administrators' as it is a SQL Server 2000 security flaw. All domain administrators will have full sysadmin rights to your SQL Server to drop databases etc. Find the account that is running SQL Agent (Right click SQL Server agent in enterprise manager and select properties). Then add this account as a SQL Server login using windows authentication and add it to the sysadmin fixed server role. A: Another method is to connect to your SQL Server database with the "NT AUTHORITY\SYSTEM" account. This approach requires you to start SQL Server Management Studio as the system account. After connect, you can create a new login or reset sa password. A: Using Enterprise Manager, can't you just go into Logins and add "Administrators" as a Windows Login to the server? Then add the login to the sysadmin role? If you can't use "Administrators", try "MACHINENAME\Administrators" (obviously substituting MACHINENAME for the actual name). Sorry I don't have a more definitive answer, I don't really want to try it :)
{ "language": "en", "url": "https://stackoverflow.com/questions/138142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }