Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
How would I use Regex to extract the body from a html doc, taking into account that the html and body tags might be in uppercase, lowercase or might not exist?
Don't use a regular expression for this - use something like the [Html Agility Pack](http://html-agility-pack.net). > This is an agile HTML parser that > builds a read/write DOM and supports > plain XPATH or XSLT (you actually > don't HAVE to understand XPATH nor > XSLT to use it, don't worry...). It is > a .NET code library that allows you to > parse "out of the web" HTML files. The > parser is very tolerant with "real > world" malformed HTML. The object > model is very similar to what proposes > System.Xml, but for HTML documents (or > streams). Then you can extract the `body` with an XPATH.
How about something like this? It captures everything between `<body></body>` tags (case insensitive due to `RegexOptions.IgnoreCase`) into a group named `theBody`. `RegexOptions.Singleline` allows us to handle multiline HTML as a single string. If the HTML does not contain `<body></body>` tags, the `Success` property of the match will be false. ``` string html; // Populate the html string here RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Singleline; Regex regx = new Regex( "<body>(?<theBody>.*)</body>", options ); Match match = regx.Match( html ); if ( match.Success ) { string theBody = match.Groups["theBody"].Value; } ```
Regex Extract html Body
[ "", "c#", "vb.net", "regex", "" ]
So I have this ``` public class Foo { public int UniqueIdentifier; public Foo() { UniqueIdentifier = ???? } } ``` How do I get a completely unique number? Thanks!
``` System.Guid guid = System.Guid.NewGuid(); String id = guid.ToString(); ```
Although not an int, a method of creating unique identifiers commonly uses GUIDs. You can use Guid.NewGuid() to generate one. There are some various conversion methods including byte arrays and strings. For more information on GUIDs you can read up on them at [Wikipedia](http://en.wikipedia.org/wiki/Globally_Unique_Identifier). Best of luck.
What is the simplest unique identifier available in .Net?
[ "", "c#", ".net", "guid", "class-design", "" ]
i am creating xml using linq.xml through xelement. my hirerachy is some thing like this I want this schema 2 str here is my code for schema generation ``` XNamespace ns = XNamespace.Get("urn:APISchema.xsd"); root = new XElement(ns + "Foo"); root.Add(new XElement("version", "2")); root.Add(new XElement("foochild", "str")); ``` but the resultant schema is ``` <Foo xlmns="urn:APISchema.xsd"> <version xlmns="">2</version> <foochild xlmns="">str</foochild> </Foo> ``` any idea why such problem why it is appending xlmn to root childs...?
``` root.Add(new XElement(namespace + "foo", "str")) ``` Edit: upon further SO searching, [this question](https://stackoverflow.com/questions/61084/empty-namespace-using-linq-xml) seems to be addressing the same issue.
``` XNamespace myNamespace = XNamespace.Get("urn:APISchema.xsd"); root = new XElement(myNamespace + "Foo", new XElement(myNamespace + "version", "2"), new XElement(myNamespace + "foochild", "str")); ``` Give that a shot, it should do the trick for you.
adding/creating namespace to root xelement element in c#
[ "", "c#", "linq-to-xml", "" ]
I have a select statement which is something like this ``` select col1 from table1 where cond1=true ``` This returns results like ``` col1 _____ 5 5 6 3 ``` but I want to change it to return me ``` 5-5-6-3 ``` Is this possible? If so how? Please let me know how to do this. Thanks in advance for your replies.
You probably could, but why not do this in the application? I don't know what language you're using, but you could do something like this after you get the result of the query (pseudocode): ``` result = result.join('-') ```
This does exactly what you want: ``` declare @ret varchar(500) set @ret='' select @ret = @ret + col1 + '-' from test select substring(@ret, 1, len(@ret)-1) ``` NOTE: if your col1 is *int* then I think you will have to use *convert* or *cast* to make it *varchar*.
concatenate rows from a select statement
[ "", "sql", "sql-server-2005", "" ]
How do I execute some JavaScript that is a string? ``` function ExecuteJavascriptString() { var s = "alert('hello')"; // how do I get a browser to alert('hello')? } ```
With the [`eval`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) function, like: ``` eval("my script here"); ``` > WARNING: Any malicious code contained within the string will be executed with the same privileges of your site, make absolutely sure you can trust the source.
You can execute it using a function. Example: ``` var theInstructions = "alert('Hello World'); var x = 100"; var F=new Function (theInstructions); return(F()); ```
Execute JavaScript code stored as a string
[ "", "javascript", "" ]
I'm looking for Java solution but any general answer is also OK. Vector/ArrayList is O(1) for append and retrieve, but O(n) for prepend. LinkedList (in Java implemented as doubly-linked-list) is O(1) for append and prepend, but O(n) for retrieval. Deque (ArrayDeque) is O(1) for everything above but cannot retrieve element at arbitrary index. In my mind a data structure that satisfy the requirement above has 2 growable list inside (one for prepend and one for append) and also stores an offset to determine where to get the element during retrieval.
You're looking for a double-ended queue. This is implemented the way you want in the C++ STL, which is you can index into it, but not in Java, as you noted. You could conceivably roll your own from standard components by using two arrays and storing where "zero" is. This could be wasteful of memory if you end up moving a long way from zero, but if you get too far you can rebase and allow the deque to crawl into a new array. A more elegant solution that doesn't really require so much fanciness in managing two arrays is to impose a circular array onto a pre-allocated array. This would require implementing push\_front, push\_back, and the resizing of the array behind it, but the conditions for resizing and such would be much cleaner.
A **deque** (double-ended queue) may be implemented to provide all these operations in O(1) time, although not all implementations do. I've never used Java's ArrayDeque, so I thought you were joking about it not supporting random access, but you're absolutely right — as a "pure" deque, it only allows for easy access at the ends. I can see why, but that sure is annoying... To me, the ideal way to implement an exceedingly fast deque is to use a [circular buffer](http://en.wikipedia.org/wiki/Circular_buffer), especially since you are only interested in adding removing at the front and back. I'm not immediately aware of one in Java, but I've written one in Objective-C as part of an open-source framework. You're welcome to use the code, either as-is or as a pattern for implementing your own. Here is a [WebSVN portal to the code](http://dysart.cs.byu.edu/websvn/listing.php?repname=BYU+CocoaHeads&path=/CHDataStructures/source/) and the [related documentation](http://dysart.cs.byu.edu/CHDataStructures/interface_c_h_circular_buffer_deque.html). The real meat is in the **CHAbstractCircularBufferCollection.m** file — look for the `appendObject:` and `prependObject:` methods. There is even a custom enumerator ("iterator" in Java) defined as well. The essential circular buffer logic is fairly trivial, and is captured in these 3 centralized `#define` macros: ``` #define transformIndex(index) ((headIndex + index) % arrayCapacity) #define incrementIndex(index) (index = (index + 1) % arrayCapacity) #define decrementIndex(index) (index = ((index) ? index : arrayCapacity) - 1) ``` As you can see in the `objectAtIndex:` method, all you do to access the Nth element in a deque is `array[transformIndex(N)]`. Note that I make `tailIndex` always point to one slot beyond the last stored element, so if `headIndex == tailIndex`, the array is full, or empty if the size is 0. Hope that helps. My apologies for posting non-Java code, but the question author *did* say general answers were acceptable.
What is a data structure that has O(1) for append, prepend, and retrieve element at any location?
[ "", "java", "data-structures", "vector", "linked-list", "deque", "" ]
So say I have this XML file: ``` <?xml version="1.0" encoding="utf-8" standalone="yes"?> <Root> <Category Name="Tasties"> <Category Name="Pasta"> <Category Name="Chicken"> <Recipe Name="Chicken and Shrimp Scampi" /> <Recipe Name="Chicken Fettucini Alfredo" /> </Category> <Category Name="Beef"> <Recipe Name="Spaghetti and Meatballs" /> <Recipe Name="Lasagna" /> </Category> <Category Name="Pork"> <Recipe Name="Lasagna" /> </Category> <Category Name="Seafood"> <Recipe Name="Chicken and Shrimp Scampi" /> </Category> </Category> </Category> </Root> ``` And I want to return the names of all the recipes in Tasties\Pasta\Chicken, how would I do this? What I have currently is: ``` var q = from chk in (from c in doc.Descendants("Category") where c.Attribute("Name").Value == "Chicken" select c) select from r in chk.Descendants("Recipe") select r.Attribute("Name").Value; foreach (var recipes in q) { foreach (var recipe in recipes) { Console.WriteLine("Recipe name = {0}", recipe); } } ``` Which kinda works, although it doesn't check the path, only for the first category named Chicken. I could dig through each element in the path recursively, but it seems like there probably is a better solution I'm missing. Also my current query returns `IEnumerable<IEnumerable<String>>` when all I want is just an `IEnumerable<String>`. Basically I can make it work but it looks messy and I'd like to see any LINQ suggestions or techniques to do better querying.
Personally, I'd use `XmlDocument` and the familiar `SelectNodes`: ``` foreach(XmlElement el in doc.DocumentElement.SelectNodes( "Category[@Name='Tasties']/Category[@Name='Pasta']/Category[@Name='Chicken']/Recipe")) { Console.WriteLine(el.GetAttribute("Name")); } ``` For LINQ-to-XML, I'd guess (untested) something like: ``` var q = from c1 in doc.Root.Elements("Category") where c1.Attribute("Name").Value == "Tasties" from c2 in c1.Elements("Category") where c2.Attribute("Name").Value == "Pasta" from c3 in c2.Elements("Category") where c3.Attribute("Name").Value == "Chicken" from recipe in c3.Elements("Recipe") select recipe.Attribute("Name").Value; foreach (string name in q) { Console.WriteLine(name); } ``` --- Edit: if you want the category selection to be more flexible: ``` string[] categories = { "Tasties", "Pasta", "Chicken" }; XDocument doc = XDocument.Parse(xml); IEnumerable<XElement> query = doc.Elements(); foreach (string category in categories) { string tmp = category; query = query.Elements("Category") .Where(c => c.Attribute("Name").Value == tmp); } foreach (string name in query.Descendants("Recipe") .Select(r => r.Attribute("Name").Value)) { Console.WriteLine(name); } ``` This should now work for any number of levels, selecting all recipes at the chosen level or below. --- Edit for discussion (comments) on why `Where` has a local `tmp` variable: This might get a bit complex, but I'm trying to do the question justice ;-p Basically, the `foreach` (with the iterator lvalue "captured") looks like: ``` class SomeWrapper { public string category; public bool AnonMethod(XElement c) { return c.Attribute("Name").Value == category; } } ... SomeWrapper wrapper = new SomeWrapper(); // note only 1 of these using(var iter = categories.GetEnumerator()) { while(iter.MoveNext()) { wrapper.category = iter.Current; query = query.Elements("Category") .Where(wrapper.AnonMethod); } } ``` It might not be obvious, but since `Where` isn't evaluated immediately, the value of `category` (via the predicate `AnonMethod`) isn't checked until much later. This is an unfortunate consequence of the precise details of the C# spec. Introducing `tmp` (**scoped inside** the foreach) means that the capture happens per iteration: ``` class SecondWrapper { public string tmp; public bool AnonMethod(XElement c) { return c.Attribute("Name").Value == tmp; } } ... string category; using(var iter = categories.GetEnumerator()) { while(iter.MoveNext()) { category = iter.Current; SecondWrapper wrapper = new SecondWrapper(); // note 1 per iteration wrapper.tmp = category; query = query.Elements("Category") .Where(wrapper.AnonMethod); } } ``` And hence it doesn't matter whether we evaluate now or later. Complex and messy. You can see why I favor a change to the specification!!!
A little bit late, but extension methods can really help to clean up messy looking LINQ to XML queries. For your scenario you could work with code like this: ``` var query = xml.Root .Category("Tasties") .Category("Pasta") .Category("Chicken") .Recipes(); ``` ... using some techniques I show in [From LINQ To XPath And Back Again](http://odetocode.com/Blogs/scott/archive/2009/06/05/12881.aspx)
Better way to do this LINQ to XML query?
[ "", "c#", ".net", "linq-to-xml", "" ]
I have this `<ul>` ``` <ul id="select_opts" class="bullet-list" style="margin-left:15px;"></ul> ``` This javascript code which is meant to go throug a JSON object and add the options to the UL: ``` $.each(q.opts, function(i,o) { var str=''; str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>"; str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>"; $("#select_opts").append(str); }); ``` If I do console.log() I can see that the looping is working. If I do: ``` console.log($("#select_opts").html()); ``` It shows the HTML being updated as expected. However in the browser window, it shows the UL as empty! What am I doing wrong?
I found the bug, another part of the code was emptying the `<ul>` when i clicked a certain button.
``` $("select_opts").append(str); ``` should be ``` $("#select_opts").append(str); ```
Jquery append() isn't working
[ "", "javascript", "jquery", "" ]
I serve pre-compressed CSS and JS files on my site, and IE6-8 and FF is working perfectly with my .htaccess file. ``` # Compressed files RewriteCond %{HTTP:Accept-Encoding} .*gzip.* AddEncoding x-gzip .gz AddType application/x-javascript .gz AddType text/css .gz ``` I call the files with the .gz extension already [example]: ``` <link rel="stylesheet" type="text/css" media="all" href="css/layout.css.gz" /> ``` So why is this breaks in google Chrome? Thanks.
Download [Fiddler](http://www.fiddler2.com/fiddler2/) and look at the raw response headers to see what the server is sending back for that particular request. FYI, Fiddler is a client side proxy that filters your browser requests through. Super informative when dealing with these kind of issues. **-- Update** Upon further investigation, it doesn't appear that your RewriteCond is actually doing what you think it is doing. According to the [Documentation](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond), the RewriteCond directive is only used in conjunction with a RewriteRule.
1. You must use the `Content-Encoding: gzip` response header. 2. You must only return GZIP compressed content when the client's `Accept-Encoding` header allows **GZIP**.
pre-compressed gzip break on chrome, why?
[ "", "javascript", ".htaccess", "gzip", "google-chrome", "" ]
I am fairly new to JavaScript and I want to create objects and arrays using JavaScript. What I'm basically after is a way of creating an object that will store the following information, i.e.: [index, name] such as [0,"NameA"][1,"NameB"] etc. I am unsure how to create an object/array to store this type of info with jQuery. Secondly, I then need a means of passing this object/array as a parameter into another function then be able to loop through this object/array and print out it's contents. Again, I am unsure how to do this part as well.
If you're interested in saving some data in an array, and pluck it out together with its index, why not do it the simplest way possible? ``` var arr = ["Alpha", "Bravo", "Charlie", "Dog", "Easy"]; for (i = 0; i<5; i++) { alert("Element with index " + i + " is " + arr[i] + "."); } ```
You may find the following article interesting * [Peeling away the jQuery wrapper and finding an array](http://www.learningjquery.com/2008/12/peeling-away-the-jquery-wrapper) Essentially, the (jQuery) object returned by the jQuery `$()` function has a bunch of properties, which include one for each element that matches the selector, with the property name being a numeric "index" For example, given the following HTML ``` <p>Hello, World!</p> <p>I'm feeling fine today</p> <p>How are you?</p> ``` and the selector ``` $('p'); ``` the object returned will look as follows ``` ({length:3, 0:{}, 1:{}, 2:{}}) ``` Using the [`.get()`](http://docs.jquery.com/Core/get) command, you can access matched elements and operate on them accordingly. Following with the example ``` $(function () { var p = $('p').get(); for (var prop in p) alert(prop + ' ' + p[prop].innerHTML); }); ``` or alternatively, knowing how the returned object is structured ``` $(function () { var p = $('p'); for (var i=0; i< p.length; i++) alert(i + ' ' + p[i].innerHTML); }); ``` will alert ``` 0 Hello, World! 1 I'm feeling fine today 2 How are you? ``` I know that I have not answered your question directly, but thought that it may be useful to provide insight into how jQuery works. I think what you need in order to answer your question is either * a simple array, as demonstrated by [Tomas Lycken's answer](https://stackoverflow.com/questions/901335/jquery-objects-arrays-how/901371#901371). This seems to best fit what you are asking for `var mySimpleArray = ['a','b','c'];` * an array of objects, with each object having an 'index' and 'name'. I'll make the assumption here that 'index' is implied to be be any number that you want to assign and does not imply an ordinal position `var myObjectArray = [{ index: 5, name: 'a' },{ index: 22, name: 'b'},{ index: 55, name: 'c'}];`
How to create objects/arrays in JavaScript?
[ "", "javascript", "arrays", "" ]
I'm a newcomer to regular expressions, and am having a hard time with what appears to be a simple case. I need to replace "foo bar" with "fubar", where there is any amount and variety of white space between foo and bar. For what it's worth, I'm using php's eregi\_replace() to accomplish this. Thanks in advance for the help.
`... =` [`preg_replace`](http://php.net/preg_replace)`('/foo\s+bar/', 'fubar', ...);`
I'm not sure about the `eregi_replace` syntax, but you'd want something like this: ``` Pattern: foo\s*bar Replace with: fubar ```
Replace two words that may have one or more of any kind of whitespace between them
[ "", "php", "regex", "preg-replace", "whitespace", "" ]
I hit on this nasty behavior on JBoss 4.2 in QA, and I want to nip it in the bud before we go into production and find some other corner case. A jsp calles a method that had the following signature: ``` public void methodName(String arg) ``` This was changed to: ``` public void methodName(String arg, Object... args) ``` A pre-existing JSP called this method via: ``` methodName("param"); ``` On deployment of the modified code, JBoss did not recompile the JSP and this caused a crash in QA. Adding a silly comment to the jsp fixed the problem (JBoss recognized that the JSP changed and recompiled it). Is there a setting on JBoss to force recompilation of JSPs on restart? EDIT: To clarify some points in the answer, the setup is that the JSPs are part of a war which is part of an ear. The ear has all classes in it, in a jar. Regarding the desire to pre-compile, if the system doesn't think that the jsp needs compilation, will pre-compile force recompilation? It doesn't seem so. The error here is not a compliation error, it is a method invocation error because of the "changed" (at the byte code level, not really at the code level) method signature. Addendum: Note that we experienced in production recently that even with the accepted answer's flag set the JSPs did not recompile, even though the JSP did in fact change. Major bug there, but regardless, JBoss was shutdown normally. At this point it is getting to be an old version of JBoss, but if you are still using it, deleting the content of the work and tmp directories is the only way to be sure. I'm not changing the accepted answer simply because it really gets to the point of what the question was looking for. JBoss bugs are kind of a separate issue.
If the JSPs are part of a WAR that is part of an EAR that is being deployed as a jar, then I'm not clear why your JSPs are not being recompiled. Don't the JSPs in the war file have newer timestamps than their JBoss-compiled class files from the last deploy? If not, couldn't you touch the JSPs as part of building the WAR/EAR before deploying. [I'm referring to using the Unix "touch" command, not manually touching each JSP file.] Alternatively, the DeleteWorkDirOnContextDestroy setting in $JBOSS/server/default/deploy/jboss-web.deployer/META-INF/jboss-service.xml may be what you are looking for. It is false by default, but setting it to true may be what you need. I think this should delete the JSPs' class files on redeploy so that they get recreated upon first access of each JSP. See <https://jira.jboss.org/jira/browse/JBAS-3358> for more info.
I don't know of a setting, but deleting the generated Java class file in the work directory of your JBoss instance will cause the JSP to be recompiled the next time it is called.
How can you force recompilation of jsps in JBoss 4.2?
[ "", "java", "jsp", "jboss", "recompile", "" ]
I'm making a site like StackOverflow in Rails but I'm not sure if it's necessary for the Votes on a question to be stored in a separate table in the database. Is there any good reason to separate the data? Or could I store the Votes as a single sum in a field of the Questions table?
How would you know if a user voted on a question without keeping a votes table? Or like this website that holds you to X votes a day, how would you know how many votes a user made in the day? How would you keep track of how many up and down votes a user has done? I think good design practices pretty much scream for you to normalize the data and keep a votes table, with perhaps keeping a current +/- denormalized field in the question row for easy fetching.
Yes! Think about it from an object perspective. In model driven development (objects first) you would have a container (table) of questions, and a container of votes. Of course you could simply roll them up to an aggregate form. However by doing that you lose a lot of metric detail such as who cast the vote, when, etc. It really depends on if you need the detail or not. Space is cheap so not keeping the detail is usually not a good idea. It is hard to foresee what is needed in the future!
In a site like StackOverflow should the Question and its Votes be separate tables?
[ "", "sql", "database", "database-design", "" ]
It's the year 2009. Internet Explorer 8 has finally been released, and Firefox is coming up to 3.5. Many of the large browsers are starting to integrate features from CSS3 and HTML 5, or have been doing that for quite a while now. Still, I find myself developing web pages exactly the same way I did back in 2005. A lot of progress has been made since then, and I think the reason that I haven't started taking advantage of these new possibilities is that it's so hard to know which of the new features that work in all major browsers. Since I'm mostly a backend developer I just don't have the time to keep up these developments anymore. Still, I feel like I'm missing out on a lot of cool stuff that actually would make my life a lot easier. **How can I quickly determine if a feature of CSS3 or HTML5 is supported by all major modern browsers?**
[Can I Use](https://caniuse.com) is a website which tracks browser support for current and upcoming web standards. Check it out if you would like to know whether or not a given feature is widely supported.
Font embedding through CSS, using `@font-face`. Webkit/Safari has been supporting it since version 3.1, Microsoft since IE4, Mozilla since Firefox 3.5 ([browser support overview](http://webfonts.info/wiki/index.php?title=%40font-face_browser_support)). Also, the varied implementations of the [Selectors API](http://www.w3.org/TR/selectors-api/), which provides a browser-native CSS selector engine for use in DOM scripting. For other examples, [When Can I Use...](http://a.deveria.com/caniuse/) seems to be a very good reference.
What new browser features are available today?
[ "", "javascript", "html", "css", "internet-explorer-8", "" ]
Let's start with another behavior: even if you declare a method/variable as private, another instance of the same class can access it. That's OK I can live with it. I call these class-private and not instance-private. Now the question part: For example, at runtime I want to be able to check that all String variables in `this` class are not null, and if they are null they should be changed to the string "NULL". I can run through the variables using reflection and get their values. But if I extend my class and add private or even protected variables my base class can't access them. I have to `setAccessible` on the variables before I can use them. So please explain to me why the base-class (super-class) can't access private/protected variables from its sub-class. It is its sub-class, so I don't get it. What's the idea behind this? I know that the super-class should not know about its sub-classes, but in my example it makes sense, no? Is it because I can't or shouldn't restrict my sub-classes in this way? --- **Update:** Based on the answers, I want to know also: Why isn't accessing another instance's private variables from the same class considered a violation of encapsulation?
It's as simple as it's a violation of encapsulation. Another class should not be able to reach into your class and be messing around with things, even if you generalize that class. How does a Vehicle know anything about a Car for example? The whole point of a base class is to provide for the sub-classes, but like an over-protective parent, what you're suggesting would be too much.
To answer your update question (as the original question is well answered already) the purpose of private is to hide implementation details so that those implementation details don't become dependencies. This is the essence of object oriented programing - encapsulation ensuring that complexity is kept manageable by keeping different parts isolated to their own area. Since the class knows about its own implementation - it defines it, there is nothing gained in limiting access to other instances, since the class implementation declares all the private instances it is already exposed to all of these details. Hiding it in this case would in fact increase complexity as you would have to add an additional access level to allow class-level visibility instead of instance level visibility without actually really encapsulating any further complexity.
In Java, why can't a super-class method access protected or private methods/variables from a sub-class instance?
[ "", "java", "oop", "class", "inheritance", "instance", "" ]
I have the following very basic stored procedure: CREATE PROCEDURE [dbo].[GetNumberToProcess] AS RETURN 999 I then have some code using Enterprise Library to run and get the return value: ``` Dim cmd As DbCommand Dim ResultValue as String Dim lDBCommand as String = "dbo.GetNumberToProcess" Dim actionDB As Sql.SqlDatabase = New Sql.SqlDatabase(lConnectionString) cmd = actionDB.GetSqlStringCommand(lDBCommand) Dim SQLreturnValue As New SqlParameter("RETURN_VALUE", DbType.Int32) SQLreturnValue.Direction = ParameterDirection.ReturnValue cmd.Parameters.Add(SQLreturnValue) ' Execute the command and put the result into the ResultValue for later processing actionDB.ExecuteNonQuery(cmd).ToString() ResultValue = cmd.Parameters("RETURN_VALUE").Value.ToString ``` Problem is that all I ever get back as ResultValue is "0" when I should get "999" (the Stored Proc is very cut down just so that I can get to the bottom of why it's not working). According to the multiple examples I've seen on the web this should work. Anyone got any suggestions as to why it doesn't?
Your stored proc is obviously fine, I don't use the EntLib much I think your problem is the line ``` cmd = actionDB.GetSqlStringCommand(lDBCommand) ``` Try using this instead ``` cmd = actionDB.GetStoredProcCommand(lDBCommand) ```
have your tried ``` ResultValue = SQLreturnValue.Value.ToString() ``` I think that's just a syntax thing tho, shouldn't make a diff. I personally do not have a name for my return param and it works fine: ``` var returnCode = new SqlParameter(); returnCode.Direction = System.Data.ParameterDirection.ReturnValue; returnCode.DbType = System.Data.DbType.Int32; ``` Maybe the name RETURN\_VALUE is messing with it?
Return Value from Stored Procedure not set
[ "", "sql", "stored-procedures", "return-value", "" ]
I have an SDK that is written primarily in C#. We have some native code that was written for security and performance reasons. We use DllImport to interop with the native code. There are a few functions that I get an "`Unable to find an entry point named '...' in DLL '...'.":"`" error. I have verified that the function that is not found is exported. I have verified that it does not have a mangled name. I have verified that the parameters line up. I have tried a couple different calling conventions in the DllImport attribute. I guess I can keep trying this sort of randomly, but I am hoping there is a more direct approach. Does anyone know of a tool or method to get more information in a case like this? How confident should I be that the dll has been located? Would I get this exception if the parameters are wrong? Any help would be appreciated. Pat O
Not if this works in the Full Framework or not, but you can try: <http://blogs.msdn.com/stevenpr/archive/2005/06/22/431612.aspx>
I use [Dependency Walker](http://www.dependencywalker.com/) to find the exported functions in a C++ DLL. This will help ensure you're trying to import the right name, etc.
What are the troubleshooting steps/tools for C# to Native interop?
[ "", "c#", "interop", "native", "" ]
I'm creating a tower-defense game in javascript and want to have a high score and other multiplayer interactions. Probably have a couple of players start the game at the same time and tell them how fast the other guys are going and that kind of stuff. I don't know how flash games send their scores or events to make sure the information that each client is sending is actually correct and not just someone sending incredible scores. I remember a couple of years ago when flash games started having high scores, it was very common to see unreal(hacked) scores and well... that's pretty weird not; so what is the secret here?
People will always be capable of cheating at games... the best you can do is make it difficult to cheat. Scores for old flash games were very easy to rig because the score would be submitted via an HTTP request. Sniffing the traffic would reveal the submission URL and what variables needed to be passed in order to update the score. I hope that it has since changed. If I were you I would make use of some error checking code that will be passed along with the final score in order to verify that the score is legitimate. The error-checking code algorithm should be difficult to determine from a score (if the person is sniffing it). The javascript should also be arbitrarily obfuscated. This is nowhere near ideal but it should deter a good portion of the cheaters.
The best practice I have seen for this is to do sanity checks. Record the time elapsed, enemies killed, etc... check the score with the data, and see if they add up.
Ajax Highscores security
[ "", "javascript", "ajax", "multiplayer", "" ]
It's my understanding that if I want to get the ID of an item in a list, I can do this: ``` private static void a() { List<string> list = new List<string> {"Box", "Gate", "Car"}; Predicate<string> predicate = new Predicate<string>(getBoxId); int boxId = list.FindIndex(predicate); } private static bool getBoxId(string item) { return (item == "box"); } ``` But what if I want to make the comparison dynamic? So instead of checking if item=="box", I want to pass in a user-entered string to the delegate, and check if item==searchString.
Using a compiler-generated closure via an anonymous method or lambda is a good way to use a custom value in a predicate expression. ``` private static void findMyString(string str) { List<string> list = new List<string> {"Box", "Gate", "Car"}; int boxId = list.FindIndex(s => s == str); } ``` If you're using .NET 2.0 (no lambda), this will work as well: ``` private static void findMyString(string str) { List<string> list = new List<string> {"Box", "Gate", "Car"}; int boxId = list.FindIndex(delegate (string s) { return s == str; }); } ```
You can just do ``` string item = "Car"; ... int itemId = list.FindIndex(a=>a == item); ```
How do I find the index of an undefined string in a List<T>
[ "", "c#", "list", "delegates", "predicate", "" ]
As a trivial example lets say I have the following grid and I am looking for a particular cells value. When found I no longer need to process the loops. ``` foreach(DataGridViewRow row in grid.Rows) { foreach(DataGridViewCell cell in row.Cells) { if(cell.Value == myValue) { //Do Something useful //break out of both foreach loops. } } } ``` How is this done in C#. In Java I could use a label to name the outermost loop, and then break that loop, but I can't seem to find an equivelant in C#. What is the tersest way of accomplishing this in c#? I know I can set a boolean flag, and check it in the outer loop to break out of that one as well, but it just seems too verbose. Thanks,
The most pleasant way is to break the second loop out into a function, like this: ``` public void DoubleLoop() { for(int i = 0; i < width; i++) { for(int j = 0; j < height; j++) { if(whatever[i][j]) break; // let's make this a "double" break } } } ``` goes to ``` public bool CheckWhatever(int whateverIndex) { for(int j = 0; j < height; j++) { if(whatever[whateverIndex][j]) return false; } return true; } public void DoubleLoop() { for(int i = 0; i < width; i++) { if(!CheckWhatever(i)) break; } } ``` Of course, feel free to simplify this with LINQ or whatever (you could put `CheckWhatever` into the loop condition, too.) This is just a verbose demonstration of the principle.
1 ``` foreach(DataGridViewRow row in grid.Rows) foreach(DataGridView cell in row.Cells) if (cell.Value == somevalue) { // do stuff goto End; } End: // more stuff ``` 2 ``` void Loop(grid) { foreach(row in grid.Rows) foreach(cell in row.Cells) if (something) { // do stuff return; } } ``` 3 ``` var cell = (from row in grid.Rows.OfType<DataGridViewRow>() from cell in row.Cells.OfType<DataGridViewCell>() where cell.Value == somevalue select cell ).FirstOrDefault(); if (cell != null) { // do stuff } ```
How to break out of 2 loops without a flag variable in C#?
[ "", "c#", "syntax", "" ]
If I have two string of xml1 and xml2 which both represent xml in the same format. What is the fastest way to combine these together? The format is not important, but I just want to know how can I get rid off or ? xml1 : ``` <?xml version="1.0" encoding="utf-8"?> <AllNodes> <NodeA> <NodeB>test1</NodeB> <NodeB>test2</NodeB> </NodeA> </AllNodes> ``` xm2 : ``` <?xml version="1.0" encoding="utf-8"?> <AllNodes> <NodeA> <NodeB>test6</NodeB> <NodeB>test7</NodeB> </NodeA> <NodeA> <NodeB>test99</NodeB> <NodeB>test23</NodeB> </NodeA> </AllNodes> ``` and have something like this : ``` <?xml version="1.0" encoding="utf-8"?> <AllNodes> <NodeA> <NodeB>test1</NodeB> <NodeB>test2</NodeB> </NodeA> <NodeA> <NodeB>test6</NodeB> <NodeB>test7</NodeB> </NodeA> <NodeA> <NodeB>test99</NodeB> <NodeB>test23</NodeB> </NodeA> </AllNodes> ```
The easiest way to do this is using LINQ to XML. You can use either [Union](http://msdn.microsoft.com/en-us/library/bb341731.aspx) or [Concat](http://msdn.microsoft.com/en-us/library/bb302894.aspx) depending on your needs. ``` var xml1 = XDocument.Load("file1.xml"); var xml2 = XDocument.Load("file2.xml"); //Combine and remove duplicates var combinedUnique = xml1.Descendants("AllNodes") .Union(xml2.Descendants("AllNodes")); //Combine and keep duplicates var combinedWithDups = xml1.Descendants("AllNodes") .Concat(xml2.Descendants("AllNodes")); ```
An XSLT transformation could do it: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:param name="pXml1" select="''" /> <xsl:param name="pXml2" select="''" /> <xsl:param name="pRoot" select="'root'" /> <xsl:template match="/"> <xsl:variable name="vXml1" select="document($pXml1)" /> <xsl:variable name="vXml2" select="document($pXml2)" /> <xsl:element name="{$pRoot}"> <xsl:copy-of select="$vXml1/*/*" /> <xsl:copy-of select="$vXml2/*/*" /> </xsl:element> </xsl:template> </xsl:stylesheet> ``` Pass in the names of the files as parameters, as well as the name of the new root element. Apply to any XML document, e.g. an empty one.
What is the fastest way to combine two xml files into one
[ "", "c#", "xml", "" ]
I am using the [openwysiwyg](http://www.openwebware.com/) editor in my webpage. I want to clear the contents of it. I have used ``` $('#report').val(''); ``` but that doesn't clear it. The editor creates an iframe and updates the contents there, syncing as it goes. How would I go about clearing it?
You probably need to supply a bit more information - the html itself would be very useful, but I'm going to assume that `report` is the id of the textarea you need cleared. If it's a normal textarea, your code should really work. If (as Paulo mentions in the comments) it's being modified by an openwysiwyg editor, it's probably being turned into an iFrame with it's own HTML page in it. It's a lot more difficult to manipulate the iFrame. Looks like that's the case. --- Have a look at this example to see if it helps you reference the iFrame itself: <http://www.bennadel.com/index.cfm?dax=blog:1592.view> --- This is a hacked excerpt of the example.html that comes with openwysiwyg: ``` <script type="text/javascript"> // Use it to attach the editor to all textareas with full featured setup //WYSIWYG.attach('all', full); // Use it to attach the editor directly to a defined textarea WYSIWYG.attach('textarea1'); // default setup WYSIWYG.attach('textarea2', full); // full featured setup WYSIWYG.attach('textarea3', small); // small setup // Use it to display an iframes instead of a textareas //WYSIWYG.display('all', full); function getIFrameDocument( id ) { var iframe = document.getElementById(id); if (iframe.contentDocument) { // For NS6 return iframe.contentDocument; } else if (iframe.contentWindow) { // For IE5.5 and IE6 return iframe.contentWindow.document; } else if (iframe.document) { // For IE5 return iframe.document; } else { return null; } } function clearcontents() { getIFrameDocument('wysiwygtextarea1').body.innerHTML = ''; } </script> ``` Then somewhere in the page, I've got a clear button (actually div): ``` <div style="width:120px;height:20px;background:#ff0000;text-align:center;display:block;" onclick="clearcontents();">Clear!</div> ``` --- Note that the id of your textarea is prefixed with `wysiwyg`. That's the name of the iFrame. I've tested this in Firefox but nothing else at the moment. The code for getting the iFrame I found on the Net somewhere, so hopefully it works for other browsers :)
This works, but is butt ugly: ``` var frame = WYSIWYG.getEditor('--ENTER EDITOR NAME HERE--'); var doc = frame.contentWindow.document; var $body = $('html',doc); $body.html(''); ``` Replace `--ENTER EDITOR NAME HERE--` by whatever you pass to the editor when you call `attach`.
How to clear the contents of the openwysiwyg editor?
[ "", "javascript", "jquery", "wysiwyg", "" ]
How do I remove the carriage return character `(\r)` and the Unix newline character`(\n)` from the end of a string?
This will trim off any combination of carriage returns and newlines from the end of `s`: ``` s = s.TrimEnd(new char[] { '\r', '\n' }); ``` **Edit**: Or as JP kindly points out, you can spell that more succinctly as: ``` s = s.TrimEnd('\r', '\n'); ```
This should work ... ``` var tst = "12345\n\n\r\n\r\r"; var res = tst.TrimEnd( '\r', '\n' ); ```
Removing carriage return and linefeed from the end of a string in C#
[ "", "c#", "string", "newline", "carriage-return", "linefeed", "" ]
I am wondering if there is an easy and clean way (one line) to transform an enumeration of long (IEnumerable) to a single string (string) with LINQ? Thanks
If you want the long (integers?) to be comma separated try: ``` string str = string.Join(", ", myLongs.Select(l => l.ToString()).ToArray()); ```
Sounds like a job for aggregate/fold: ``` var longs = new long[] {3, 2, 1, 0}; var str = longs.Aggregate("", (s, l) => s + l); // str = "3210" ``` Although I am not quite sure what the question is.
How to transform an enumeration of long to a single string with LINQ
[ "", "c#", "linq", "ienumerable", "" ]
What is the difference between [Simple Logging Facade for Java](http://www.slf4j.org/) and [Apache Commons Logging](http://commons.apache.org/logging/)?
From the [SLF4J FAQ](http://www.slf4j.org/faq.html): > SLF4J is conceptually very similar to JCL. As such, it can be thought of as yet another logging facade. However, SLF4J is much simpler in design and arguably more robust. In a nutshell, SLF4J avoid the class loader issues that plague JCL. Do a google for "JCL classloader issues" for more on this...
While SLF4J can be used as a facade over libraries like Log4j, or JUL, it can also be used as an API to implement native logging libraries, like [Logback](http://logback.qos.ch/) did. A native SLF4J library won't need adapter glue in the middle like the facade for Log4j or JUL does, so it should be more efficient as well.
Difference between Simple Logging Facade for Java and Apache Commons Logging
[ "", "java", "logging", "slf4j", "apache-commons-logging", "" ]
I've a 3x3 2D dynamic array allocated as below: ``` int** matrix = new int* [3]; matrix[0] = new int [3*3]; for (int i = 1; i < 3; ++i) matrix[i] = matrix[i-1] + 3; ``` How should I deallocate it? Is this correct: ``` delete [] matrix; delete [] matrix[0]; ``` Or should I also delete `matrix[1]`, `[2]`
The way you have it, you should : ``` delete [] matrix[0]; delete [] matrix; ``` But this is a very unconventional way of allocating a dynamic 2D array. Normally you allocate an array of pointers, and then you allocate an array of your actual type for every row (column). ``` // allocate int **matrix = new int*[3]; for(int i = 0; i &lt 3; ++i) matrix[i] = new int[3]; // deallocate for(int i = 0; i &lt 3; ++i) delete [] matrix[i]; delete [] matrix; ```
You'll need one delete for each new, in reverse order of the new's.
Is this deallocation correct?
[ "", "c++", "memory-management", "" ]
Is it possible to turnoff jsessionid in the url in tomcat? the jsessionid seems not too search engine friendly.
You can disable for just search engines using this filter, but I'd advise **using it for all responses** as it's worse than just search engine unfriendly. It exposes the session ID which can be used for certain security exploits ([more info](http://randomcoder.com/articles/jsessionid-considered-harmful)). **Tomcat 6 (pre 6.0.30)** You can use the [tuckey rewrite filter](http://tuckey.org/urlrewrite/). [Example config](http://urlrewritefilter.googlecode.com/svn/trunk/src/doc/manual/3.2/guide.html) for Tuckey filter: ``` <outbound-rule encodefirst="true"> <name>Strip URL Session ID's</name> <from>^(.*?)(?:\;jsessionid=[^\?#]*)?(\?[^#]*)?(#.*)?$</from> <to>$1$2$3</to> </outbound-rule> ``` **Tomcat 6 (6.0.30 and onwards)** You can use [disableURLRewriting](http://tomcat.apache.org/tomcat-6.0-doc/config/context.html) in the context configuration to disable this behaviour. **Tomcat 7 and Tomcat 8** From [Tomcat 7 onwards](http://andrius.miasnikovas.lt/2010/07/whats-new-in-tomcat-7/) you can add the following in the session config. ``` <session-config> <tracking-mode>COOKIE</tracking-mode> </session-config> ```
``` <session-config> <tracking-mode>COOKIE</tracking-mode> </session-config> ``` Tomcat 7 and Tomcat 8 support the above config in your web-app web.xml, which disables URL-based sessions.
Is it possible to disable jsessionid in tomcat servlet?
[ "", "java", "tomcat", "servlets", "jsessionid", "" ]
I wish to make use of my unlimited shared hosting to create several small shared hosting accounts that I can offload processing to. So I need to create some logic in PHP to create the basics of a Load Balancer. I have 4 shared accounts, one is the main site and the other 3 is the processing server accounts. [Please see image](http://img199.imageshack.us/img199/8679/ymproces.jpg). I want to know how I can determine which server to pass the next processing job to? Do I keep a variable of the last server I passed to and go from one to the other? etc. What is the best method?
My KISS Tinpot suggestion would be to use JavaScript upon submitting the form to select a server at random. A list available servers that the upload page would use should be served up as a JS file from the main server. A cron job should update this list periodically to ensure only alive servers are up for selection. Simple example: ## servers.js (hosted on main server, auto-generated): ``` /* Auto Generated 01/01/2009 01:01:01 */ var Servers = new Array(); Servers[0] = "42.81.240.101"; Servers[1] = "42.81.240.120"; Servers[2] = "42.81.240.199"; function LoadBalancer_GetIP() { return Servers[Math.floor(Math.random() * Servers.length)]; } ``` ## upload.html: ``` <html> <head> <script type="text/javascript" src="servers.js"></script> </head> <body> <script type="text/javascript"> function DoUpload() { TestForm.action = "http://"+LoadBalancer_GetIP()+"/upload.php"; TestForm.submit(); } </script> <form id="TestForm" method="POST" action=""> <input type=button value="Upload" onclick="DoUpload()"> </form> </body> </html> ```
Might be going off the hook, but, could you reproduct round-robin / dns / using a method of random requests?
How do I create a Load Balancer sort of logic using PHP?
[ "", "php", "performance", "scalability", "load-balancing", "" ]
***Edited after getting answers*** Some excellent answers here. I like Josh's because it is so clever and uses C++. However I decided to accept Dave's answer because of it's simplicity and recursion. I tested them both and they both produced identical correct results (although in a different order). So thanks again everyone. --- Say I have a string s of chars s[0]:s[N] and where each char s[i] <= s[i+1] For example the string ``` aaacdddghzz ``` I want to generate all combinations of substrings while keeping the same relationship between chars. So for example I would get ``` a aa aaa ad aad aaad add aadd aaadd addd aaddd aaaddd d dd ddd . . . ac aac . . . acdddghzz aacdddghzz aaacdddghzz ``` But not ``` ca hdz ...etc ``` Now I know how to work out how many combinations there are. You create a histogram of the frequency of letters in the string. So in the above example the that would be For string aaacdddghzz ``` a=3 d=3 c=1 g=1 h=1 z=2 ``` and the formula is `(a+1)(c+1)(d+1)(g+1)(h+1)(z+1) = 4*4*2*2*2*3 = 384`. There are 384 substrings that keep the s[i] <=s [i+1] relationship. So the question is how do I generate those 384 substrings recursively? Actually an iterative method would be just as good, maybe better as large strings with many unique chars might cause the stack to overflow. This sounds like homework but it isn't. I'm just useless at coming up with algorithms like this. I use C++ but pseudocode would be fine.
Following is a recursive algorithm to generate all subsequences. ``` /* in C -- I hope it will be intelligible */ #include <stdio.h> static char input[] = "aaabbbccc"; static char output[sizeof input]; /* i is the current index in the input string * j is the current index in the output string */ static void printsubs(int i, int j) { /* print the current output string */ output[j] = '\0'; printf("%s\n", output); /* extend the output by each character from each remaining group and call ourselves recursively */ while(input[i] != '\0') { output[j] = input[i]; printsubs(i + 1, j + 1); /* find the next group of characters */ do ++i; while(input[i] == input[i - 1]); } } int main(void) { printsubs(0, 0); return 0; } ``` If your interest is merely in counting how many subsequences there are, you can do it much more efficiently. Simply count up how many of each letter there are, add 1 to each value, and multiply them together. In the above example, there are 3 a's, 3 b's, 3 c's, and 2 d's, for (3 + 1) \* (3 + 1) \* (3 + 1) \* (2 + 1) = 192 subsequences. The reason this works is that you can choose between 0 and 3 a's, 0 and 3 b's, 0 and 3 c's, and 0 and 2 d's, and *all of these choices are independent*.
An ammendement to Ryan Shaw's answer above: Instead of counting in binary, count each digit in a base dependant on the number of each letter. For example: ``` a d c g h z 3 3 1 1 1 2 ``` So count: ``` 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 1 2 0 0 0 1 0 0 ... 0 0 0 1 1 2 0 0 1 0 0 0 ... 0 0 1 1 1 2 0 1 0 0 0 0 ... 0 3 1 1 1 2 1 0 0 0 0 0 ... 3 3 1 1 1 2 ``` And you've enumerated all the possible subset, without duplicates. For any one of these outputting the string is simply a matter of looping through the digits and outputting as many of each letter as are specified. ``` 1 2 0 0 1 1 => addhz 3 0 0 0 1 2 => aaahzz ``` And the code: ``` void GetCounts(const string &source, vector<char> &characters, vector<int> &counts) { characters.clear(); counts.clear(); char currentChar = 0; for (string::const_iterator iSource = source.begin(); iSource != source.end(); ++iSource) { if (*iSource == currentChar) counts.back()++; else { characters.push_back(*iSource); counts.push_back(1); currentChar = *iSource; } } } bool Advance(vector<int> &current, const vector<int> &max) { if (current.size() == 0) return false; current[0]++; for (size_t index = 0; index < current.size() - 1 && current[index] > max[index]; ++index) { current[index] = 0; current[index + 1]++; } if (current.back() > max.back()) return false; return true; } string ToString(const vector<int> &current, const vector<char> &characters) { string result; for (size_t index = 0; index < characters.size(); ++index) for (int i = 0; i < current[index]; ++i) result += characters[index]; return result; } int main() { vector<int> max; vector<char> characters; GetCounts("aaadddcghzz", characters, max); vector<int> current(characters.size(), 0); int index = 1; while (Advance(current, max)) { cout << index++ << ":" << ToString(current, characters) << endl; } } ```
Recursively generate ordered substrings from an ordered sequence of chars?
[ "", "c++", "algorithm", "recursion", "substring", "sequences", "" ]
Python is filled with little neat shortcuts. For example: ``` self.data = map(lambda x: list(x), data) ``` and (although not so pretty) ``` tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema') ``` among countless others. In the irc channel, they said "too many to know them all". I think we should list some here, as i love using these shortcuts to shorten & refctor my code. I'm sure this would benefit many.
``` self.data = map(lambda x: list(x), data) ``` is dreck -- use ``` self.data = map(list, data) ``` if you're a `map` fanatic (list comprehensions are generally preferred these days). More generally, `lambda x: somecallable(x)` can **always** be productively changed to just `somecallable`, in **every** context, with nothing but good effect. As for shortcuts in general, my wife and I did our best to list the most important and useful one in the early part of the Python Cookbook's second edition -- could be a start.
Alex Martelli provided an even shorter version of your first example. I shall provide a (slightly) shorter version of your second: ``` tuple(t[0] for t in self.result if t[0] not in ('mysql', 'information_schema')) ``` Obviously the in operator becomes more advantageous the more values you're testing for. I would also like to stress that shortening and refactoring is good only to the extent that it improves clarity and readability. (Unless you are code-golfing. ;)
Python shortcuts
[ "", "python", "shortcut", "refactoring", "" ]
I'm getting an array of strings from a JSON object. I want to save these strings in a DB, but only if they're not already in there. What's the best way to compare what's already in the DB with what I'm about to enter, and exclude matches? I'm using PHP and MySQL.
Since what you describe is wanting to leave the record alone if the strings already exist, what you probably want is the `IGNORE` modifier to `INSERT` (i.e. you do `INSERT IGNORE ...`). That will make your query do nothing if a duplicate key is found. This requires, of course, that the string fields you're inserting into have unique keys on them.
REPLACE may do what you want - it inserts, but if the primary key already exists that row gets deleted first. Unless you need to retain other columns in the table, it should work. <http://dev.mysql.com/doc/refman/5.0/en/replace.html>
How to add to a MySQL table only if the record doesn't already exist?
[ "", "php", "mysql", "json", "duplicates", "unique-key", "" ]
The below piece of code that throws the following exception.. Error Message: > Object reference not set to an > instance of an object. Stack Trace: > at > System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior > cmdBehavior, RunBehavior runBehavior, > Boolean returnStream) at > System.Data.SqlClient.SqlCommand.ExecuteNonQuery() I am lost as to the reason why.. ``` sqlcon = new SqlConnection(strSqlconnection); SqlCommand sqlcomSMCheckin = new SqlCommand("prc_CheckIn", sqlcon); sqlcomSMCheckin.CommandType = CommandType.StoredProcedure; sqlcomSMCheckin.Parameters.Add("@Description", SqlDbType.VarChar).Value = "My App"; sqlcomSMCheckin.CommandTimeout = this.iCommandTimeOut; if (sqlcon.State == ConnectionState.Closed) { sqlcon.Open(); } if (sqlcomSMCheckin != null) { sqlcomSMCheckin.ExecuteNonQuery(); // error here sqlcomSMCheckin.Dispose(); } ```
Is sqlCon a class level variable, do you have issues with the same method being called multiple times? Is there anything static in the class? Are you using multiple threads?
Not 100% sure what's going on here - but can you try this snippet of code? ``` using(sqlcon = new SqlConnection(strSqlconnection)) { using(SqlCommand sqlcomSMCheckin = new SqlCommand("dbo.prc_CheckIn", sqlcon)) { sqlcomSMCheckin.CommandType = CommandType.StoredProcedure; sqlcomSMCheckin.Parameters.Add("@Description", SqlDbType.VarChar, 50) .Value = "My App"; sqlcomSMCheckin.CommandTimeout = this.iCommandTimeOut; sqlcon.Open(); sqlcomSMCheckin.ExecuteNonQuery(); sqlcon.Close(); } } ``` I replace "prc\_CheckIn" with "dbo.prc\_CheckIn", I specify a max length on the VARCHAR parameter (adjust as needed), wrapped everything in using {} blocks - that's about it. Do you still get the same error?? Marc
SqlCommand C# Issue
[ "", "c#", "sqlconnection", "sqlcommand", "" ]
I work for a tech company that does more prototyping than product shipment. I just got asked what's the difference between C# and F#, why did MS create F# and what scenarios would it be better than C#. I've been using the language for a while now and I love it so I could easily go on about the great features of F# however I lack the experience in C# to say why we should use one over the other. What's the benefits of using C# vs F# or F# vs C#?
General benefits of functional programming over imperative languages: You can formulate many problems much easier, closer to their definition and more concise in a functional programming language like F# and your code is less error-prone (immutability, more powerful type system, intuitive recurive algorithms). You can code what you mean instead of what the computer wants you to say ;-) *You will find many discussions like this when you google it or even search for it at SO.* Special F#-advantages: * Asynchronous programming is *extremely* easy and intuitive with [`async {}`-expressions](http://blogs.msdn.com/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx) - Even with ParallelFX, the corresponding C#-code is much bigger * [Very easy integration](http://en.wikibooks.org/wiki/F_Sharp_Programming/Lexing_and_Parsing) of compiler compilers and domain-specific languages * Extending the language as you need it: [LOP](http://blogs.msdn.com/chrsmith/archive/2008/05/30/language-oriented-programming-in-f.aspx) * [Units of measure](http://blogs.msdn.com/andrewkennedy/archive/2008/08/29/units-of-measure-in-f-part-one-introducing-units.aspx) * More flexible syntax * Often shorter and more elegant solutions Take a look at [this document](http://2009.scandevconf.se/db/FSharp-Intro-v1.ppt) The advantages of C# are that it's often more accurate to "imperative"-applications (User-interface, imperative algorithms) than a functional programming language, that the .NET-Framework it uses is designed imperatively and that it's more widespread. Furthermore you can have F# and C# together in one solution, so you can combine the benefits of both languages and use them where they're needed.
It's like asking what's the benefit of a hammer over a screwdriver. At an extremely high level, both do essentially the same thing, but at the implementation level it's important to select the optimal tool for what you're trying to accomplish. There are tasks that are difficult and time-consuming in c# but easy in f# - like trying to pound a nail with a screwdriver. You can do it, for sure - it's just not ideal. Data manipulation is one example I can personally point to where f# really shines and c# can potentially be unwieldy. On the flip side, I'd say (generally speaking) complex stateful UI is easier in OO (c#) than functional (f#). (There would probably be some people who disagree with this since it's "cool" right now to "prove" how easy it is to do *anything* in F#, but I stand by it). There are countless others.
What are the benefits of using C# vs F# or F# vs C#?
[ "", "c#", ".net", "f#", "" ]
I'm trying to display the content of a byte array in a text file. This is my code: ``` var writer = new System.IO.StreamWriter(Application.StartupPath + @"\B323.txt"); writer.Write(data.ToString()); writer.Close(); writer.Dispose(); ``` data is a byte[] array. The output is "System.Byte[]",why? I'm trying to display the content of this array,where is the problem?
When you call `byte[].ToString()` that just returns `System.Byte[]`. How were you intending the byte array to be converted? There are any number of ways of converting the bytes to a string. If you want it as a "hex dump" you could you `BitConverter.ToString(byte[])` which will produce output such as ``` 5B-3E-5D ``` Is that what you're after? If you *actually* want to just write the bytes to a file, because they *already* represent encoded text, then you should use a `FileStream` instead and write them directly. (Other points as asides: you should use a `using` statement to handle the writer; you don't need to call close because you're already disposing; `File.WriteAllText` is a simpler way of doing this to start with.)
Calling `ToString` on `data` will turn it into a textual representation (the same you will see in the Watch or Locals window when debugging). You can either just write `data` to the stream, or use one of the functions located in `System.Text.Encoding` to convert your byte[] to a string.
byte[] to string conversion doesn't seem to work the way I want
[ "", "c#", "text", "" ]
i just want to get a text from textbox that is betwen two dots for example. www. abc.org . h
You'll need to be a bit more specific with your question I think. Now, if you're just looking to extract the middle part of the address, something like the following should do the job: ``` var parts = textbox.Text.Split(new char[] {'.'}); if (parts.Length < 3) throw new InvalidOperationException("Invalid address."); var middlePart = parts[1]; ```
in C# ``` string url = "www.google.com"; string[] split_strings = url.Split('.'); Console.WriteLine(split_strings[1]); ``` Get String From Textbox: ``` string url = textbox_url.Text; string[] split_strings = url.Split('.'); Console.WriteLine(split_strings[1]); ``` But please, use try and catch ;)
how to get a text from textbox that is betwen two dots
[ "", "c#", "text-manipulation", "" ]
I need to store a user's password for a short period of time in memory. How can I do so yet not have such information accidentally disclosed in coredumps or tracebacks? Is there a way to mark a value as "sensitive", so it's not saved anywhere by a debugger?
**Edit** I have made a solution that uses ctypes (which in turn uses C) to zero memory. ``` import sys import ctypes def zerome(string): location = id(string) + 20 size = sys.getsizeof(string) - 20 memset = ctypes.cdll.msvcrt.memset # For Linux, use the following. Change the 6 to whatever it is on your computer. # memset = ctypes.CDLL("libc.so.6").memset print "Clearing 0x%08x size %i bytes" % (location, size) memset(location, 0, size) ``` I make no guarantees of the safety of this code. It is tested to work on x86 and CPython 2.6.2. A longer writeup is [here](http://web.archive.org/web/20100929111257/http://www.codexon.com/posts/clearing-passwords-in-memory-with-python). Decrypting and encrypting in Python will not work. Strings and Integers are interned and persistent, which means you are leaving a mess of password information all over the place. Hashing is the standard answer, though of course the plaintext eventually needs to be processed somewhere. The correct solution is to do the sensitive processes as a C module. But if your memory is constantly being compromised, I would rethink your security setup.
> ... **The only solution to this is to use mutable data structures.** That > is, you must only use data structures that allow you to dynamically > replace elements. For example, in Python you can use lists to store an > array of characters. However, *every time you add or remove an element > from a list, the language might copy the entire list behind your back*, > depending on the implementation details. To be safe, if you have to > dynamically resize a data structure, **you should create a new one, copy > data, and then write over the old one**. For example: ``` def paranoid_add_character_to_list(ch, l): """Copy l, adding a new character, ch. Erase l. Return the result.""" new_list = [] for i in range(len(l)): new_list.append(0) new_list.append(ch) for i in range(len(l)): new_list[i] = l[i] l[i] = 0 return new_list ``` **Source: <http://www.ibm.com/developerworks/library/s-data.html>** * Author: John Viega (viega@list.org) is co-author of Building Secure Software (Addison-Wesley, 2001) and Java Enterprise Architecture (O'Reilly and Associates, 2001). John has authored more than 50 technical publications, primarily in the area of software security. He also wrote Mailman, the GNU Mailing List Manager and ITS4, a tool for finding security vulnerabilities in C and C++ code.
Mark data as sensitive in python
[ "", "python", "security", "passwords", "coredump", "" ]
I have a large application written in Delphi. I want to renew it, starting with the user interface. I thought about using the new Qt. During the process of renewing it, I want to change to C++ as the programming language. Is there a way to gradually rewrite the application (starting with the UI) to change to C++? Thank you for your help.
The best course of action highly depends on the C++ development environment. **If it is C++ Builder you have two possibilities:** * Use runtime packages instead of normal DLLs. This will spare you much headaches when it comes to string marshalling and mapping class hierarchies to flat DLL functions. * Use mixed code. You can mix Delphi/Pascal code with C++ code in the same project. (Only one language in a single module/unit though) **If it is any other C++ compiler:** * Go the way you proposed with DLLs. You have to create some kind of layer/facade to map your classes' functionality to flat DLL functions. * If you want to go the plain DLL way even though you are using C++ Builder you can try using a shared memory manager like ShareMem (comes with Delphi) or FastMM ([SourceForge](http://sourceforge.net/projects/fastmm/)) to allow passing of `string`s instead of `PChar`s. * Create .objs instead of .dcus so both compilers work with the same output format. Then link them directly into you C++ program. This is essentially the same as with creating a DLL, but it's static. You will spot certain kinds of errors at compile time rather than runtime.
It's probably easier to go the other way - rewrite the business logic in C++ and call it from Delphi via C interfaces. This is particularly so as one of Delphi's key strengths is working with GUIs.
Port Delphi to C++ gradually
[ "", "c++", "delphi", "qt", "" ]
I need a regular expression to validate time. Valid values would be from `0:00` to `23:59`. When the time is less than `10:00` it should also support one character numbers. These are valid values: * `9:00` * `09:00`
Try this regular expression: ``` ^(?:[01]?[0-9]|2[0-3]):[0-5][0-9]$ ``` Or to be more distinct: ``` ^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$ ```
I don't want to steal anyone's hard work but [this](http://alperguc.blogspot.com/2008/11/c-regex-time-validation-with-regular.html) is exactly what you're looking for, apparently. ``` using System.Text.RegularExpressions; public bool IsValidTime(string thetime) { Regex checktime = new Regex(@"^(20|21|22|23|[01]d|d)(([:][0-5]d){1,2})$"); return checktime.IsMatch(thetime); } ```
Regular expression to validate valid time
[ "", "c#", ".net", "regex", "" ]
``` ServiceController serviceController = new ServiceController(someService); serviceController.Stop(); serviceController.WaitForStopped(); DoSomething(); ``` SomeService works on a sqlserver file. DoSomething() wants to copy that SQL file. If SomeService isn't closed fully it will throw an error because the database file is still locked. In the aforementioned code, I get past the WaitForStopped() method and yet the service doesn't release the database file until after DoSomething(), thus I get an error. Doing some more investigation, I find that before the DoSomething method call I see that the service controller status shows a stopped and yet looking at some ProcMon logs the service releases the database file after I'm thrown an error from DoSomething. Also, if I put a Thread.Sleep between the WaitForStopped and the DoSomething method for say... 5 seconds, the database file is released and all is well. Not the solution of surety I'm looking for however. Any ideas?
ServiceController.WaitForStopped()/WaitForStatus() will return once the service implementation claims it has stopped. This doesn't necessary mean the process has released all of its resources and has exited. I've seen database other than SQL Server do this as well. If you really want to be sure the database is fully and truly stopped, you will have to interface with the database itself, get ahold of the process id and wait for it to exit, wait for locks on the files to be released, ...
Windows Services are a layer on top of processes; in order to be a service, an application must connect to the Service Control Manager and announce which services are available. This connection is handled within the ADVAPI32.DLL library. Once this connection is established, the library maintains a thread waiting for commands from the Service Control Manager, which can then start and stop services arbitrarily. I don't believe the process is required to exit when the last service in it terminates. Though that is what typically happens, the end of the link with the Service Control Manager, which occurs after the last service enters the "Stopped" state, can occur significantly before the process actually terminates, releasing any resources it hasn't already explicitly released. The Windows Service API includes functionality that lets you obtain the Process ID of the process that is hosting the service. It is possible for a single process to host many services, and so the process might not actually exit when the service you are interested in has terminated, but you should be safe with SQL Server. Unfortunately, the .NET Framework does not expose this functionality. It does, however, expose the handle to the service that it uses internally for API calls, and you can use it to make your own API calls. With a bit of P/Invoke, then, you can obtain the process ID of the Windows Service process, and from there, provided you have the necessary permission, you can open a handle to the process that can be used to wait for it to exit. Something like this: ``` [DllImport("advapi32")] static extern bool QueryServiceStatusEx(IntPtr hService, int InfoLevel, ref SERVICE_STATUS_PROCESS lpBuffer, int cbBufSize, out int pcbBytesNeeded); const int SC_STATUS_PROCESS_INFO = 0; [StructLayout(LayoutKind.Sequential)] struct SERVICE_STATUS_PROCESS { public int dwServiceType; public int dwCurrentState; public int dwControlsAccepted; public int dwWin32ExitCode; public int dwServiceSpecificExitCode; public int dwCheckPoint; public int dwWaitHint; public int dwProcessId; public int dwServiceFlags; } const int SERVICE_WIN32_OWN_PROCESS = 0x00000010; const int SERVICE_INTERACTIVE_PROCESS = 0x00000100; const int SERVICE_RUNS_IN_SYSTEM_PROCESS = 0x00000001; public static void StopServiceAndWaitForExit(string serviceName) { using (ServiceController controller = new ServiceController(serviceName)) { SERVICE_STATUS_PROCESS ssp = new SERVICE_STATUS_PROCESS(); int ignored; // Obtain information about the service, and specifically its hosting process, // from the Service Control Manager. if (!QueryServiceStatusEx(controller.ServiceHandle.DangerousGetHandle(), SC_STATUS_PROCESS_INFO, ref ssp, Marshal.SizeOf(ssp), out ignored)) throw new Exception("Couldn't obtain service process information."); // A few quick sanity checks that what the caller wants is *possible*. if ((ssp.dwServiceType & ~SERVICE_INTERACTIVE_PROCESS) != SERVICE_WIN32_OWN_PROCESS) throw new Exception("Can't wait for the service's hosting process to exit because there may be multiple services in the process (dwServiceType is not SERVICE_WIN32_OWN_PROCESS"); if ((ssp.dwServiceFlags & SERVICE_RUNS_IN_SYSTEM_PROCESS) != 0) throw new Exception("Can't wait for the service's hosting process to exit because the hosting process is a critical system process that will not exit (SERVICE_RUNS_IN_SYSTEM_PROCESS flag set)"); if (ssp.dwProcessId == 0) throw new Exception("Can't wait for the service's hosting process to exit because the process ID is not known."); // Note: It is possible for the next line to throw an ArgumentException if the // Service Control Manager's information is out-of-date (e.g. due to the process // having *just* been terminated in Task Manager) and the process does not really // exist. This is a race condition. The exception is the desirable result in this // case. using (Process process = Process.GetProcessById(ssp.dwProcessId)) { // EDIT: There is no need for waiting in a separate thread, because MSDN says "The handles are valid until closed, even after the process or thread they represent has been terminated." ( http://msdn.microsoft.com/en-us/library/windows/desktop/ms684868%28v=vs.85%29.aspx ), so to keep things in the same thread, the process HANDLE should be opened from the process id before the service is stopped, and the Wait should be done after that. // Response to EDIT: What you report is true, but the problem is that the handle isn't actually opened by Process.GetProcessById. It's only opened within the .WaitForExit method, which won't return until the wait is complete. Thus, if we try the wait on the current therad, we can't actually do anything until it's done, and if we defer the check until after the process has completed, it won't be possible to obtain a handle to it any more. // The actual wait, using process.WaitForExit, opens a handle with the SYNCHRONIZE // permission only and closes the handle before returning. As long as that handle // is open, the process can be monitored for termination, but if the process exits // before the handle is opened, it is no longer possible to open a handle to the // original process and, worse, though it exists only as a technicality, there is // a race condition in that another process could pop up with the same process ID. // As such, we definitely want the handle to be opened before we ask the service // to close, but since the handle's lifetime is only that of the call to WaitForExit // and while WaitForExit is blocking the thread we can't make calls into the SCM, // it would appear to be necessary to perform the wait on a separate thread. ProcessWaitForExitData threadData = new ProcessWaitForExitData(); threadData.Process = process; Thread processWaitForExitThread = new Thread(ProcessWaitForExitThreadProc); processWaitForExitThread.IsBackground = Thread.CurrentThread.IsBackground; processWaitForExitThread.Start(threadData); // Now we ask the service to exit. controller.Stop(); // Instead of waiting until the *service* is in the "stopped" state, here we // wait for its hosting process to go away. Of course, it's really that other // thread waiting for the process to go away, and then we wait for the thread // to go away. lock (threadData.Sync) while (!threadData.HasExited) Monitor.Wait(threadData.Sync); } } } class ProcessWaitForExitData { public Process Process; public volatile bool HasExited; public object Sync = new object(); } static void ProcessWaitForExitThreadProc(object state) { ProcessWaitForExitData threadData = (ProcessWaitForExitData)state; try { threadData.Process.WaitForExit(); } catch {} finally { lock (threadData.Sync) { threadData.HasExited = true; Monitor.PulseAll(threadData.Sync); } } } ```
Service not fully stopped after ServiceController.Stop()
[ "", "c#", ".net", "sql-server", "service", "" ]
Background: I'm using WPF and C# (3.5) and am working on an app that allows a user to view a form/window/usercontrol that's already part of a compiled assembly. When they view it, they should be able to click on any control (buttons, textboxes, even labels), a little popup editor should appear by the control where they can then type in a tooltip, helpID, etc., for that control. The long and short of it: I need to imitate a basic design view in WPF. Which means I need to do at least the following: * Load the usercontrol/window from a given assembly *(no problem)* * Instantiate it the usercontrol/window *(no problem)* * **Clear all subscribed EventHandlers for all its controls** * Assign my own "ShowEditorPopup" EventHandler to each control *(shouldn't be a problem)* First off, if anybody has suggestions on an easier or better route to take, please let me know. (Apparently there is no DesignHost kind of component for WPF (like I've read .NET 2 has), so that's out.) I'm stuck on the bolded item - clearing any subscribed EventHandlers. After digging around some and getting into Reflector, I've come up with this cool chunk of dangerous code (here, I'm just trying to get all the EventHandlers for a single Button called someButton defined in the XAML): ``` <Button Name="someButton" Click="someButton_Click"/> ``` Here's the code (you can run it from the someButton\_Click eventHandler if you want): ``` public void SomeFunction() { // Get the control's Type Type someButtonType = ((UIElement)someButton).GetType(); // Dig out the undocumented (yes, I know, it's risky) EventHandlerStore // from the control's Type PropertyInfo EventHandlersStoreType = someButtonType.GetProperty("EventHandlersStore", BindingFlags.Instance | BindingFlags.NonPublic); // Get the actual "value" of the store, not just the reflected PropertyInfo Object EventHandlersStore = EventHandlersStoreType.GetValue(someButton, null); // Get the store's type ... Type storeType = EventHandlersStore.GetType(); // ... so we can pull out the store's public method GetRoutedEventHandlers MethodInfo GetEventHandlers = storeType.GetMethod("GetRoutedEventHandlers", BindingFlags.Instance | BindingFlags.Public); // Reflector shows us that the method's sig is this: // public RoutedEventHandlerInfo[] GetRoutedEventHandlers(RoutedEvent routedEvent); // So set up the RoutedEvent param object[] Params = new object[] { ButtonBase.ClickEvent as RoutedEvent }; // I've also seen this for the param, but doesn't seem to make a difference: // object[] Params = new object[] { someButton.ClickEvent }; // And invoke it ... and watch it crash! GetEventHandlers.Invoke(someButton, Params); } ``` It works up to the Invoke, which returns: Object does not match target type (ie, my params or target object are messed). I've found you can resolve this with: ``` GetEventHandlers.Invoke(Activator.CreateInstance(someButton.GetType()), Params); // Also doesn't work... ``` When I set a watch on the GetEventHandlers MethodInfo, it looks great, it just doesn't like what I'm passing it when I call the Invoke. I feel like I'm at the very last step of how to get a list of the RoutedEvent Handlers (like good old GetInvocationList(), which doesn't work for WPF RoutedEvents, apparently). From there, it'll be simple enough to remove those Handlers from each control and have an eventless form, which I can then add my own events to. Any clues? Again, if there's a better/easier way to do the task overall, let me know :)
What if you take a different approach. You could call [EventManager.RegisterClassHandler()](http://msdn.microsoft.com/en-us/library/ms597874.aspx) for all events, and then in your handler (assuming the event is for a control on the design surface, and not part of your UI) mark the event as handled. This should prevent it from being forwarded on to the controls on your design surface, since class handlers are called before standard event handlers. You'd still need to use reflection to get the list of events provided by a control, but at least this way you wouldn't be using reflection to remove the events. Also, if the assembly you load also registers a class handler (likely before your code does), theirs would be called first, but I would guess that this would be a rare occurrence.
If you use `GetEventHandlers.Invoke(EventHandlersStore , Params)` it seems to work well and does not crash.
Removing Routed Event Handlers through Reflection?
[ "", "c#", "wpf", "reflection", "event-handling", "routedevent", "" ]
I need a robust, user-friendly, professional-looking .NET WinForms IP address control for use in a project I'm working on. This control, at a minimum, should support IPv4 addressing and ideally would support IPv6 addressing as well. I would prefer a free control with C# source code, but don't mind paying for one. I am using .NET 3.5 SP1, so anything .NET 2.0 and greater should be sufficient.
Tada. <http://www.codeproject.com/KB/miscctrl/IpAddrCtrlLib.aspx> The latest version of this control is found here (thanks Pat): <http://code.google.com/p/ipaddresscontrollib/>
I found following ip address control. Its really good. <http://sanity-free.org/127/an_ipaddress_control_the_win32_sysipaddress32_control_in_csharp.html>
Need a .NET WinForms IP Address Control
[ "", "c#", ".net", ".net-3.5", "controls", "ip-address", "" ]
I am developing an application where I have a requirement that I have to include multiple files, as follows: ``` File1.php will include File2.php File2.php will include File3.php File3.php will include File4.php ``` Now, what will be the best and optimized way of doing these. I tried with include() but I think its slowing down my server as my server load graphs goes approx 3-5 times higher than normal server load. These all files are heave means arround `50 KB` for each file. So can anyone please suggest me what will be the best option to include these files so that it will not affect the speed of the site, Which will be best? ``` require() require_once() include() include_once() ``` OR if anyone has some other option then please tell me, Thanks
You should reorganize your files. Have a "common.php" file that includes all the needed files. You shouldn't have a chain like that. I sincerely doubt a couple of includes are slowing down your server. Most web applications have tens, maybe even hundreds of PHP files. There is no way 3 extra files will slow down your application that much. Also, the speed difference between the functions you mentioned is negligible, although you should use `include_once`/`require_once` instead of their counterparts, to make sure you don't include the same file multiple times.
The difference between include() and require() is whether you get a warning or a fatal error (respectively). The PHP docs don't mention any performance difference. Using the \_once() variants is useful if you want to avoid duplicating the contents of the included files. From the [PHP docs](https://www.php.net/manual/en/function.include-once.php) for include\_once: > include\_once() may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.
Including file in PHP?
[ "", "php", "optimization", "include", "performance", "" ]
I asked a similar question yesterday which may have been poorly worded, either way I didn't understand and this is something I really need to crack :) I've never done it before and would be very useful for so many of my projects. This is for a directory website. I have three tables: **entry**, **location**, and **entry-locations**. **entry** contains information about a building such as name, address, image, etc. **location** is simply a list of possible locations each building could be. The location table is pretty much irrelevant for this example, it just contains information about the location which I could display on other areas of the site. **entry-locations** is a table which links the entries to the locations. It only has two fields, *entry-id* and *location*... If you're wondering why I need a seperate table for this is because the same building *could* have multiple locations (don't ask). Basically, what I need to do is display listings from each location it's own page. For example, I need to list every building in France, so the query needs to go through the **entry-locations** table returning every record with the location 'France', then it needs to pull all the data from the **entry** table corresponding to the *entry-id*'s returned. I'm sure there is a way to do this with one query and would be extremely greatful if I could be shown how, I could replicate this in so many projects.
Imagine you have this data: **Entry**: ``` |id|name| | 1|Foo | | 2|Bar | ``` **Entry-Location**: ``` |entry-id|location| |1 |France | |2 |Greece | |2 |France | ``` This is how I understand the tables from your description. A more common approach is to have ``` Entry(id,name) Location(id,name) Entry_Location(entry_id, location_id) ``` This is also the source of some of the confusions in the other posts, I think. Now, ask MySql to fetch data from both tables, where the id's match up. ``` SELECT entry.* FROM `entry`, `entry-location` as el WHERE entry.id = el.`entry-id` AND el.location = 'France'; ``` MySql now treats your data like one table, looking like this: ``` |entry.id|entry.name|el.location| | 1| Foo| France| | 1| Foo| Greece| | 2| Bar| France| ``` And from that table it selects the entries where `el.location = 'France'`, and returns the specified fields. This query fetches all the fields from the `entry` table that matches the requirements you set. First it makes MySql think of the two tables as one table, by `SELECT`-ing from both of them. Have a look at MySql's [SELECT reference](http://dev.mysql.com/doc/refman/5.0/en/select.html).
How about this one? ``` -- // Selects all the columns from both entry-locations and entry SELECT * FROM entry-locations JOIN entry e ON e.id = el.entry-id WHERE el.location = 'France'; -- // To just get the entry data for matching records: (Remove DISTINCT if you -- // don't mind, or want, each entry with multiple locations in the result set -- // multiple times) SELECT DISTINCT e.* FROM entry-locations el JOIN entry e ON e.id = el.entry-id WHERE el.location = 'France' ``` ***Edit:*** Ok, so I tried removing the location table, and instead used entry-location.location as the name of the location.. Is this correct?
PHP MySQL Getting Data Out of Multiple Tables
[ "", "php", "mysql", "" ]
Does anyone know of an implementation of a lock free hash table in C#? Or can anyone confirm for a fact that at least reads on a HashTable are thread-safe? Edit: I can read the documentation, but it's unclear. "It is thread safe for multi-thread use when only one of the threads perform write (update) operations." So, the question is, if I have multiple threads, and they all *could* write to the hashtable, I would use the writerlock. However, those same threads also read from the hashtable. Do I need a readerlock on the reads?
Reads are thread-safe until the collection is modified.
From the [documentation](http://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx): > Hashtable is thread safe for use by > multiple reader threads and a single > writing thread. It is thread safe for > multi-thread use when only one of the > threads perform write (update) > operations, which allows for lock-free > reads provided that the writers are > serialized to the Hashtable. To > support multiple writers all > operations on the Hashtable must be > done through the wrapper returned by > the Synchronized method, provided that > there are no threads reading the > Hashtable object. > > Enumerating through a collection is > intrinsically not a thread safe > procedure. Even when a collection is > synchronized, other threads can still > modify the collection, which causes > the enumerator to throw an exception. > To guarantee thread safety during > enumeration, you can either lock the > collection during the entire > enumeration or catch the exceptions > resulting from changes made by other > threads.
Lock free hash table for c#
[ "", "c#", "multithreading", "" ]
So I'm using an HTML select box with a list of countries and a button to open a small window with more details for the selected item in the HTML select box. Here's how I'm doing this (I apologize in advance for any noobishness here, I'm still pretty new to Javascript): ``` //in header <script type="text/javascript"> function popUp() { countryName = document.getElementById("countrylist").value; document.write(countryName); dest = "countries/" + countryName + ".html"; window.open(dest, 0, "toolbar=0, scrollbars=0, statusbar=0, menubar=0,resizable=0,width=400,height=400,left=440,top=312"); } </script> <form id="countryform"> <select id="countrylist"> <!--List of countries removed for brevity--> </select> <input type="button" name="countryBtn" value="Submit Query" onClick="popUp();"> </form> ``` This works fine in Firefox, but not in IE6. Any help would be appreciated! **UPDATE:** So I tried the first two approaches below, the alternative popup function did not work in either browser, and replacing the document.getElementById line didn't change anything, still works fine in Firefox, doesn't in IE.
Here's how I fixed it: ``` function popUp() { var c = document.getElementById("countrylist"); var countryName = c.options[c.selectedIndex].text; var dest = "countries/" + countryName + ".html"; window.open(dest, 0, "toolbar=0, scrollbars=0, statusbar=0, menubar=0,resizable=0,width=400,height=400,left=440,top=312"); } ``` This works in both IE6 and FF3. Thanks for the help anyways!
``` document.getElementById("countrylist").value; ``` needs to be: ``` document.getElementById("countrylist")[document.getElementById("countrylist").selectedIndex].value; ```
My HTML dropdown won't work in IE6
[ "", "javascript", "html", "internet-explorer-6", "" ]
I am designing an entity class which has a field named "documentYear", which might have unsigned integer values such as 1999, 2006, etc. Meanwhile, this field might also be "unknown", that is, not sure which year the document is created. Therefore, a nullable **int** type as in C# will be well suited. However, Java does not have a nullable feature as C# has. I have two options but I don't like them both: 1. Use `java.lang.Integer` instead of the primitive type `int`; 2. Use -1 to present the "unknown" value Does anyone have better options or ideas? **Update**: My entity class will have tens of thousands of instances; therefore the overhead of java.lang.Integer might be too heavy for overall performance of the system.
You're going to have to either ditch the primitive type or use some arbitrary int value as your "invalid year". A negative value is actually a good choice since there is little chance of having a valid year that would cause an integer overflow and there is no valid negative year.
Using the Integer class here is probably what you want to do. The overhead associated with the object is most likely (though not necessarily) trivial to your applications overall responsiveness and performance.
How to present the nullable primitive type int in Java?
[ "", "java", "nullable", "" ]
Is there an elegant way to access the first property of an object... 1. where you don't know the name of your properties 2. without using a loop like `for .. in` or jQuery's `$.each` For example, I need to access `foo1` object without knowing the name of foo1: ``` var example = { foo1: { /* stuff1 */}, foo2: { /* stuff2 */}, foo3: { /* stuff3 */} }; ```
``` var obj = { first: 'someVal' }; obj[Object.keys(obj)[0]]; //returns 'someVal' Object.values(obj)[0]; // returns 'someVal' ``` Using this you can access also other properties by indexes. Be aware tho! `Object.keys` or `Object.values` return order is not guaranteed as per ECMAScript however unofficially it is by all major browsers implementations, please read <https://stackoverflow.com/a/23202095> for details on this.
Try the [`for … in` loop](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for...in) and break after the first iteration: ``` for (var prop in object) { // object[prop] break; } ```
How to access the first property of a Javascript object?
[ "", "javascript", "object", "" ]
I got a question... I got code like this, and I want to read it with PHP. ``` NAME { title ( A_STRING ); settings { SetA( 15, 15 ); SetB( "test" ); } desc { Desc ( A_STRING ); Cond ( A_STRING ); } } ``` I want: ``` $arr['NAME']['title'] = "A_STRING"; $arr['NAME']['settings']['SetA'] = "15, 15"; $arr['NAME']['settings']['SetB'] = "test"; $arr['NAME']['desc']['Desc'] = "A_STRING"; $arr['NAME']['desc']['Cond'] = "A_STRING"; ``` I don't know how I should start :/. The variables aren't always the same. Can someone give me a hint on how to parse such a file? Thx
If the files are this simple, then rolling your own homegrown parser is probably a lot easier. You'll eventually end up writing regex with lexers anyway. Here's a quick hack example: (in.txt should contain the input you provided above.) ``` <pre> <?php $input_str = file_get_contents("in.txt"); print_r(parse_lualike($input_str)); function parse_lualike($str){ $str = preg_replace('/[\n]|[;]/','',$str); preg_match_all('/[a-zA-Z][a-zA-Z0-9_]*|[(]\s*([^)]*)\s*[)]|[{]|[}]/', $str, $matches); $tree = array(); $stack = array(); $pos = 0; $stack[$pos] = &$tree; foreach($matches[0] as $index => $token){ if($token == '{'){ $node = &$stack[$pos]; $node[$ident] = array(); $pos++; $stack[$pos] = &$node[$ident]; }elseif($token=='}'){ unset($stack[$pos]); $pos--; }elseif($token[0] == '('){ $stack[$pos][$ident] = $matches[1][$index]; }else{ $ident = $token; } } return $tree; } ?> ``` Quick explanation: The first `preg_replace` removes all newlines and semicolons, as they seem superfluous. The next part divides the input string into different 'tokens'; names, brackets and stuff inbetween paranthesis. Do a `print_r $matches;` there to see what it does. Then there's just a really hackish state machine (or read for-loop) that goes through the tokens and adds them to a tree. It also has a stack to be able to build nested trees. Please note that this algorithm is in no way tested. It will probably break when presented with "real life" input. For instance, a parenthesis inside a value will cause trouble. Also note that it doesn't remove quotes from strings. I'll leave all that to someone else... But, as you requested, it's a start :) Cheers! PS. Here's the output of the code above, for convenience: ``` Array ( [NAME] => Array ( [title] => A_STRING [settings] => Array ( [SetA] => 15, 15 [SetB] => "test" ) [desc] => Array ( [Desc] => A_STRING [Cond] => A_STRING ) ) ) ```
This looks like a real grammar - you should use a parser generator. [This discussion](http://netevil.org/blog/2006/nov/parser-and-lexer-generators-for-php) should get you started. There are a few options already made for php: a [lexer generator module](http://pear.php.net/package/PHP_LexerGenerator/redirected) and this is a [parser generator module](http://pear.php.net/package/PHP_ParserGenerator/redirected).
Read lua-like code in php
[ "", "php", "parsing", "" ]
Supposing we have the following records in an SQL Server table. ``` Date 19/5/2009 12:00:00 pm 19/5/2009 12:15:22 pm 20/5/2009 11:38:00 am ``` What is the SQL syntax for getting something like this one? *Date* **Count** *19/5/2009* **2** *20/5/2009* **1**
You need to do any grouping on a Date only version of your datefield, such as this. ``` SELECT CONVERT(VARCHAR(10), YourDateColumn, 101), COUNT(*) FROM YourTable GROUP BY CONVERT(VARCHAR(10), YourDateColumn, 101) ``` I usually do this though, as it avoids conversion to varchar. ``` SELECT DATEPART(yy, YourDateColumn), DATEPART(mm, YourDateColumn), DATEPART(dd, YourDateColumn), COUNT(*) FROM YourTable GROUP BY DATEPART(yy, YourDateColumn), DATEPART(mm, YourDateColumn), DATEPART(dd, YourDateColumn) ``` EDIT: Another way to get just the date part of a datetime ``` DATEADD(d, 0, DATEDIFF(d, 0, YourDateColumn)) ```
That would depend on your database engine. For SQL Server 2008 (and future versions), you can use the `date` type to do this. ``` select convert(date, date_column_name) as Date, count(1) as Count from table_name group by convert(date, date_column_name) ```
SQL Server Server query - Count distinct DateTime field
[ "", "sql", "sql-server", "distinct", "" ]
I was helping somebody out with his JavaScript code and my eyes were caught by a section that looked like that: ``` function randOrd(){ return (Math.round(Math.random())-0.5); } coords.sort(randOrd); alert(coords); ``` My first though was: **hey, this can't possibly work!** But then I did some experimenting and found that it indeed at least seems to provide nicely randomized results. Then I did some web search and almost at the top found an [article](http://javascript.about.com/library/blsort2.htm) from which this code was most ceartanly copied. Looked like a pretty respectable site and author... But my gut feeling tells me, that this must be wrong. Especially as the sorting algorithm is not specified by ECMA standard. I think different sorting algoritms will result in different non-uniform shuffles. Some sorting algorithms may probably even loop infinitely... But what do you think? And as another question... how would I now go and measure how random the results of this shuffling technique are? **update:** I did some measurements and posted the results below as one of the answers.
It's never been my favourite way of shuffling, partly because it *is* implementation-specific as you say. In particular, I seem to remember that the standard library sorting from either Java or .NET (not sure which) can often detect if you end up with an inconsistent comparison between some elements (e.g. you first claim `A < B` and `B < C`, but then `C < A`). It also ends up as a more complex (in terms of execution time) shuffle than you really need. I prefer the shuffle algorithm which effectively partitions the collection into "shuffled" (at the start of the collection, initially empty) and "unshuffled" (the rest of the collection). At each step of the algorithm, pick a random unshuffled element (which could be the first one) and swap it with the first unshuffled element - then treat it as shuffled (i.e. mentally move the partition to include it). This is O(n) and only requires n-1 calls to the random number generator, which is nice. It also produces a genuine shuffle - any element has a 1/n chance of ending up in each space, regardless of its original position (assuming a reasonable RNG). The sorted version *approximates* to an even distribution (assuming that the random number generator doesn't pick the same value twice, which is highly unlikely if it's returning random doubles) but I find it easier to reason about the shuffle version :) This approach is called a [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher%2dYates_shuffle). I would regard it as a best practice to code up this shuffle once and reuse it everywhere you need to shuffle items. Then you don't need to worry about sort implementations in terms of reliability or complexity. It's only a few lines of code (which I won't attempt in JavaScript!) The [Wikipedia article on shuffling](http://en.wikipedia.org/wiki/Shuffling#Shuffling_algorithms) (and in particular the shuffle algorithms section) talks about sorting a random projection - it's worth reading the section on poor implementations of shuffling in general, so you know what to avoid.
After Jon has already [covered the theory](https://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling/962829#962829), here's an implementation: ``` function shuffle(array) { var tmp, current, top = array.length; if(top) while(--top) { current = Math.floor(Math.random() * (top + 1)); tmp = array[current]; array[current] = array[top]; array[top] = tmp; } return array; } ``` The algorithm is `O(n)`, whereas sorting should be `O(n log n)`. Depending on the overhead of executing JS code compared to the native `sort()` function, this might lead to a [noticable difference in performance](https://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling/963872#963872) which should increase with array sizes. --- In the comments to [bobobobo's answer](https://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling/962886#962886), I stated that the algorithm in question might not produce evenly distributed probabilities (depending on the implementation of `sort()`). My argument goes along these lines: A sorting algorithm requires a certain number `c` of comparisons, eg `c = n(n-1)/2` for Bubblesort. Our random comparison function makes the outcome of each comparison equally likely, ie there are `2^c` *equally probable* results. Now, each result has to correspond to one of the `n!` permutations of the array's entries, which makes an even distribution impossible in the general case. (This is a simplification, as the actual number of comparisons neeeded depends on the input array, but the assertion should still hold.) As Jon pointed out, this alone is no reason to prefer Fisher-Yates over using `sort()`, as the random number generator will also map a finite number of pseudo-random values to the `n!` permutations. But the results of Fisher-Yates should still be better: `Math.random()` produces a pseudo-random number in the range `[0;1[`. As JS uses double-precision floating point values, this corresponds to `2^x` possible values where `52 ≤ x ≤ 63` (I'm too lazy to find the actual number). A probability distribution generated using `Math.random()` will stop behaving well if the number of atomic events is of the same order of magnitude. When using Fisher-Yates, the relevant parameter is the size of the array, which should never approach `2^52` due to practical limitations. When sorting with a random comparision function, the function basically only cares if the return value is positive or negative, so this will never be a problem. But there is a similar one: Because the comparison function is well-behaved, the `2^c` possible results are, as stated, equally probable. If `c ~ n log n` then `2^c ~ n^(a·n)` where `a = const`, which makes it at least possible that `2^c` is of same magnitude as (or even less than) `n!` and thus leading to an uneven distribution, even if the sorting algorithm where to map onto the permutaions evenly. If this has any practical impact is beyond me. The real problem is that the sorting algorithms are not guaranteed to map onto the permutations evenly. It's easy to see that Mergesort does as it's symmetric, but reasoning about something like Bubblesort or, more importantly, Quicksort or Heapsort, is not. --- The bottom line: As long as `sort()` uses Mergesort, you *should* be reasonably safe except in corner cases (at least I'm hoping that `2^c ≤ n!` is a corner case), if not, all bets are off.
Is it correct to use JavaScript Array.sort() method for shuffling?
[ "", "javascript", "random", "sorting", "shuffle", "" ]
I want this SQL query to be written in rails controller using find: ``` select id,name from questions where id not in (select question_id from levels_questions where level_id=15) ``` How will I do this? I am using Rails framework and MySQL. Thanks in advance.
Simple way: ``` ids = LevelsQuestion.all(:select => "question_id", :conditions => "level_id = 15").collect(&:question_id) Question.all(:select => "id, name", :conditions => ["id not in (?)", ids]) ``` One shot: ``` Question.all(:select => "id, name", :conditions => ["id not in (select question_id from levels_questions where level_id=15)"]) ```
``` Question.find_all_by_sql('select id,name from questions where id not in (select question_id from levels_questions where level_id=15)') ``` This is admittedly non-ActiveRecord-ish, but I find that complicated queries such as this tend to be LESS clear/efficient when using the AR macros. If you already have the SQL constructed, you might as well use it. Some suggestions: encapsulate this find call in a method INSIDE the Question class to hide the details from the controller/view, and consider other SQL constructions that may be more efficient (eg, an OUTER JOIN where levels\_questions.question\_id is null)
Rails SQL Query with find
[ "", "sql", "ruby-on-rails", "find", "" ]
I have a template class that I've subclassed with a pointer to it (Decorator pattern). I added a `getBase()` call to return the pointer to the base class for any further subclasses. However, when I use that `getBase()` and call the base classes only method, I get a linker error that it can't find the symbol for that method in the intervening (Decorator) class? Like this: ``` template <typename T> class B { public: typedef std::auto_ptr<T> MYFUN( std::istream&, const std::string&, const std::string& ); public: B<T>( MYFUN* p ); auto_ptr<T> fun( istream& ); private: MYFUN *fptr; }; template <typename T> class D : public class B<T> { D( typename B<T>::MYFUN *fPtr, B<T> *providedBase ); //Looks like B B* getBase() { return base_ ; } private: B* base_; }; template <typename T> class Dagain : public class D<T> { //Looks like D auto_ptr<T> fun( istream& ); }; auto_ptr<T> Dagain::fun( istream& is ) { this->getBase()->fun( is ); } ``` Note that there is no definition for `fun( istream& )` in `D<T>`. The intention is for the client to use the pointer to the base to call `B<T>::fun( istream& )` When the client constructs a `Dagain` object, the linker says (basically): `Client.o: (.data.rel.ro. --stuff-- [vtable for D<T>]: undefined reference to 'D<T>::fun( basic_istream<char, char_traits<char> >&)'` But, I'm not calling **D**'s definition of `fun(istream&)`... it doesn't even have one! I'm using the pointer directly to the base class... When I add a definition for `D<T>::fun(istream&)` things work, but I don't understand why?
You have forgotten to specify the template parameter in the template definition. Furthermore you had some more errors. Here is the working code: ``` template <typename T> class B { public: typedef std::auto_ptr<T> MYFUN( std::istream&, const std::string&, const std::string& ); public: B<T>( MYFUN* p ); auto_ptr<T> fun( istream& ); private: MYFUN *fptr; }; template <typename T> class D : public B<T> { D( typename B<T>::MYFUN *fPtr, B<T> *providedBase ); //Looks like B B<T>* getBase() { return base_ ; } private: B<T>* base_; }; template <typename T> class Dagain : public D<T> { //Looks like D auto_ptr<T> fun( istream& ); }; template <typename T> auto_ptr<T> Dagain<T>::fun( istream& is ) { this->getBase()->fun( is ); } ```
It looks to me like your `getBase` is returning the wrong type. It should be returning the correct type of the base class: ``` template <typename T> class D : public class B<T> { ... //Looks like B B<T>* getBase() { return base_ ; } private: B<T>* base_; }; ```
Can't call base class method even though I have a pointer to it (Decorator)?
[ "", "c++", "templates", "decorator", "" ]
I need to create a text editing control in C# and I'm not sure where to start. For a bit of context: a C# program is going to edit an XML document (using this control). The XML document can be converted to HTML. The XML document will contain the following: * Normal text (obviously) * Headings (which will be formatted differently) * Lists * Images * Videos (they don't need to be viewed in the control, but there needs to be a box or something to indicate that they're there) I want this control to take the XML and render it and act as an WYSIWYG editor for the XML. For the moment, I'm not to concerned about implementing all the above details (although they will need to be implemented eventually), I just want to know where to start with creating this control. Should I be inheriting from TextBoxBase (or TextBox) and going from there? And what methods would I need to override? Or should I inherit from Control (in which case I think I'd need to all the text box stuff - selecting text, copy and paste, the caret etc. - myself, which is something I don't really want to do, but I am prepared to do if I have to). I am aware of preexisting controls like [TX Text Control](http://www.textcontrol.com/products/client_side/) that do something like what I want (although this one is far more powerful than I need), but I can't use these (this is for a university project), and besides, I really do want to know how to make this from scratch.
The topic of creating a feature rich edition control with syntax highlighting, code completion, etc. has been discussed by the developers of #develop in their book "dissecting a C# Application" <http://www.icsharpcode.net/OpenSource/SD/InsideSharpDevelop.aspx> (I think you can't buy it anymore, the link says it's available for free to download but the links seems to be broken) The book basically explain the core features of #develop (pre V1, so it's kinda outdated), including the code editor and (what is important, too) which mistakes they made during the process.
> Should I be inheriting from TextBoxBase (or TextBox) and going from there? You can't inherit from TextBoxBase (its constructor is `internal`). So you can inherit from TextBox or from Control or UserControl. The problem with TextBox is that its painting is done by unmanaged code, which isn't overridden when you override OnPaint. For further details, see [this question, answer and comments](https://stackoverflow.com/questions/3608652). > I am aware of preexisting controls like TX Text Control that do something like what I want The TX Text Control is something else: it's implemented using Win32 code, with a .NET wrapper/API.
How to create a custom text editing control?
[ "", "c#", "" ]
I'm trying to figure out the best way to search a customer in an `ArrayList` by its Id number. The code below is not working; the compiler tells me that I am missing a `return` statement. ``` Customer findCustomerByid(int id){ boolean exist=false; if(this.customers.isEmpty()) { return null; } for(int i=0;i<this.customers.size();i++) { if(this.customers.get(i).getId() == id) { exist=true; break; } if(exist) { return this.customers.get(id); } else { return this.customers.get(id); } } } //the customer class is something like that public class Customer { //attributes int id; int tel; String fname; String lname; String resgistrationDate; } ```
The compiler is complaining because you currently have the 'if(exist)' block inside of your for loop. It needs to be outside of it. ``` for(int i=0;i<this.customers.size();i++){ if(this.customers.get(i).getId() == id){ exist=true; break; } } if(exist) { return this.customers.get(id); } else { return this.customers.get(id); } ``` That being said, there are better ways to perform this search. Personally, if I were using an ArrayList, my solution would look like the one that Jon Skeet has posted.
Others have pointed out the error in your existing code, but I'd like to take two steps further. Firstly, assuming you're using Java 1.5+, you can achieve greater readability using the *enhanced for loop*: ``` Customer findCustomerByid(int id){ for (Customer customer : customers) { if (customer.getId() == id) { return customer; } } return null; } ``` This has also removed the micro-optimisation of returning `null` before looping - I doubt that you'll get any benefit from it, and it's more code. Likewise I've removed the `exists` flag: returning as soon as you know the answer makes the code simpler. Note that in your original code I *think* you had a bug. Having found that the customer at index `i` had the right ID, you then returned the customer at index `id` - I doubt that this is really what you intended. Secondly, if you're going to do a lot of lookups by ID, have you considered putting your customers into a `Map<Integer, Customer>`?
search in java ArrayList
[ "", "java", "search", "arraylist", "" ]
.htaccess files are not my strong point. I have document uploads going to /uploads. The user should be able to view the documents they've just uploaded by clicking on the document link that appears via ajax after uploading is completed. However, I would like to be able to password protect the /uploads folder BUT still enable the current user to view the clicked document without having a password request appear. Is this possible to do in .htaccess? Thanks for any suggestions.
I don't think this is possible in .htaccess - since .htaccess has no way of knowing which user uploaded which files. Even if it did (e.g. by putting files in `uploads/username/`), I don't think .htaccess files are the way to go. I think you'll probably want to enforce this at the application level.
Unless you are using HTTP auth to authenticate your user before the upload, this probably cannot be simply done with just .htaccess. You need to know file's owner and compare it with current user, which is way beyond the scope of usual web server's capabilities. If you may use Nginx or Lighttpd, you may use [`X-Accel-Redirect`](http://wiki.nginx.org/NginxXSendfile)/[`X-Sendfile`](http://redmine.lighttpd.net/projects/1/wiki/X-LIGHTTPD-send-file) header. There's also a module for Apache2 called [mod\_xsendfile](http://tn123.ath.cx/mod_xsendfile/). Make all request to `/uploads` transparently pass through your application, verify access then tell web server to send file. While this requires the ability to configure the web server (which is sometimes not possible) this is probably the most correct and universal solution. Here are some useful links: * [PHP and Ruby on Rails examples](http://blog.kovyrin.net/2006/11/01/nginx-x-accel-redirect-php-rails/lang/en/) (and some general information on configuration) * [Python/Django code snippet](http://www.djangosnippets.org/snippets/491/)
Htaccess and uploads
[ "", "php", "upload", "file-upload", "" ]
This is related to my [previous post](https://stackoverflow.com/questions/858476/12-digit-number-java-encryption-question), where my only option was to have a RSA algorithm which seemed relatively weak. Let us assume that I want to encode a 35 bit number (From 0 upto 34359738367) with a 36 bit modulo (between 34359738368 upto 68719476735). Referring to <http://en.wikipedia.org/wiki/RSA> I can see that my n is between 34359738368 upto 68719476735 a random totient (of the form p-1 \* q-1). I pick a random d and e. I encode a number and show that on the UI. For the purpose of argument let us assume that a user can see upto 1,000 such outputs. Can he use some algorithms like Polla's or anything of the like to crack my d,e or n and thereby start predicting new numbers? If so how hard is it going to be ? (By just knowing say 1000 sets of inputs/outputs) As an example (consider 6 outputs as sample in input/output format), 1. 10001621865,31116156015 2. 10001621866,33031668326 3. 10001621867,37351399313 4. 10001621868,06071714212 5. 10001621869,01188523761 6. 10001621870,18341011998 Can someone tell me what my n, d, e was? (N between 34359738368 upto 68719476735) I simply want to know how crackable it is, so if you could give me any information on how long, how fast, how many outputs does one has to see, what algorithms can one use etc. It will be great. PS: User does not see the "e" like the standard RSA algorithm. He can only see the input output sets. ***DETAILS ADDED*** I am trying to present a sequential user-id from db to the user. Because it is sequential I dont want a user to guess another user's id by doing a few registrations. To avoid this I have to scramble it to a <= 12 digit number. There were lot of constraints around this which were explained in [this question](https://stackoverflow.com/questions/858476/12-digit-number-java-encryption-question) . Also the value of n,d and e is not known to the user. The maximum a user can see is a few input ouput samples (by way of registering repeatedly) Accepting the answer posted by Accipitridae since the "Jacobi" algorithm can be used to crack this in a matter of few seconds. Without knowing n, e or p.
An attacker can guess a factor p of n and e mod (p-1). Each guess can be checked by taking a message m, computing m^e mod p and then comparing with c mod p, where c is the corresponding ciphertext. Since p and e mod (p-1) are maybe 20 bits each, this means that the security of the scheme is not larger than 40 bits. But 40 bits is only a very crude upper bound. An attacker can do much better. For example he can guess a factor p. Then he computes the Jacobi symbols of the messages and ciphertexts. If a message m is a quadratic residue mod p then the ciphertext must be a quadratic residue mod p and vice versa. Hence if this relation is not satisfied for a message/ciphertext pair he can reject the guess for p. Or the attacker can compute discrete logarithms between message and ciphertext. This gives a much faster candidate for e mod (p-1). That should give a security level of 20-30 bits, hence require a few seconds to break. If you extend your number of samples to 20 I might try some benchmarks. **Update:** Since you didn't give me 20 samples to run an experiment, I had to generate them myself. With the following samples ``` m = 10001621865 c = 31116156015 m = 10001621866 c = 33031668326 m = 10001621867 c = 37351399313 m = 10001621868 c = 6071714212 m = 10001621869 c = 1188523761 m = 10001621870 c = 18341011998 m = 10001621871 c = 7620400191 m = 10001621872 c = 36106912203 m = 10001621873 c = 37615263725 m = 10001621874 c = 7795237418 m = 10001621875 c = 34774459868 m = 10001621876 c = 4555747045 m = 10001621877 c = 33123599635 m = 10001621878 c = 34836418207 m = 10001621879 c = 33962453633 m = 10001621880 c = 6258371439 m = 10001621881 c = 7500991556 m = 10001621882 c = 5071836635 m = 10001621883 c = 911495880 m = 10001621884 c = 39558568485 ``` as input, the algorithm described above finds the factors 201821 and 206153 in 20ms. As described this does not need to know e, although your choice of e=65537 is easy to guess and can be exploited as well. The strength of RSA is that it is based on the difficulty of factoring large integers. Here you remove this difficulty and what remains are all the weaknesses (i.e. mathematical relations) of RSA. Building a block cipher based on RSA is a horrible idea. I really don't see why you don't want to use a Luby-Rackoff construction as I proposed earlier.
RSA is vulnerable against a Chosen-Ciphertext attack. That is, say we want to break ciphertext y, we can use one of the ciphertext-plaintext pairs to break it. How to break it: choose an x0 and y0, where x0 and y0 is a plaintext-ciphertext pair that has been provided. y1 = y0\*y mod n y1 is another one of the 1000 ciphertexts given to the user that satisfies this criteria. x1 is the decryption of y1, which is also given, this means: x1 = y1^d mod n (this has been given to us, we already know x1) x1 = (y0\*y)^d mod n x1 = y0^d \* y^d mod n Ξ x0\*x x1\*x0^-1 = x x is the decryption of y. This is of course dependent on whether or not y0\*y mod n produces another ciphertext that we already have, and since we have only 1000 such pairs to work with, it is unlikely but not unfeasible to break. You just have to choose your pairs extremely carefully. I'd also like to add that the size of n you're working with allows a factoring heuristic to find the prime factorization of n fairly quickly. Also, RSA is vulnerable to timing attacks, but that can be easily thwarted. **With added info:** Without knowing n, d, or e, there is absolutely no information provided at all, which means guessing combinations of n, d, or e is as good as guessing the plaintext itself. To find n and e, there are at least 43,359,738,367 combinations of n to guess as well as all of the combinations e could be. It's not easy for someone even with 1000 ciphertext-plaintext pairs to be able to crack n and e.
Cracking a N bit RSA modulo numbers
[ "", "java", "security", "encryption", "cryptography", "rsa", "" ]
I currently have a database with over 6 million rows and growing. I currently do SELECT COUNT(id) FROM table; in order to display the number to my users, but the database is getting large and I have no need to store all of those rows except to be able to show the number. Is there a way to select the auto\_increment value to display so that I can clear out most of the rows in the database? Using `LAST_INSERT_ID()` doesn't seem to work.
If it's only about getting the number of records (rows) I'd suggest using: ``` SELECT TABLE_ROWS FROM information_schema.tables WHERE table_name='the_table_you_want' -- Can end here if only 1 DB AND table_schema = DATABASE(); -- See comment below if > 1 DB ``` (at least for MySQL) instead.
Following is the most performant way to find the next `AUTO_INCREMENT` value for a table. This is quick even on databases housing millions of tables, because it does not require querying the potentially large `information_schema` database. ``` mysql> SHOW TABLE STATUS LIKE 'table_name'; // Look for the Auto_increment column ``` However, if you must retrieve this value in a query, then to the `information_schema` database you must go. ``` SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DatabaseName' AND TABLE_NAME = 'TableName'; ```
Most efficient way to get table row count
[ "", "mysql", "sql", "count", "" ]
We just finished a small project for a client (~35k), and the client would like to open a service contract with us to respond to any issues within 4 hours. The client would pay a monthly fee regardless of if there are any issues or not. Since this is a new product, it is likely that there will be issues, but we think that they would be small. We're in Salt Lake City, and the client is as well. We're using a c# front end and mysql backend. I've read that some people charge by the hour after fixing bugs for free the first 3 months. Should we go with a service contract and how much should we charge per month so that we don't shaft ourselves? Or should we go with an hourly rate to fix issues as they come up?
**Advice:** Start with hourly fixes. Unless you are dead confident in your code and the airtightness of everything you put in a spec and put blueprints on, go hourly. Why? Every time I have launched a new project I try to leave it hourly to build a history of cases that need to be resolved. Once I have some data (average amount of time to fix, type of bug, etc) to back it up, I see if I can average out a price for the year. So If I figure I use 100 hours a year of "support", I can then come up with a yearly cost, pad it due to the programmers genetic make up of underestimating and then present it. **Critical considerations for service contracts:** First, it has to be good for you and them. It has to stay good for you and them. There can't be more bad months than good for either of you. Regardless of what you are paid you will have to present value or lose the support agreement at renewal. * **What does it cover?** You must be careful when it comes to Fixing "anything". Becoming the catch-all to support the entire application even if it's not your problem (hardware, or network issues, etc) is very costly, first to your time, and second potentially to your image, if you are being called for a central support resource for the entire application. * **4 Hour what?** 4 hour response is much different from 4 hour resolution. The only thing you can offer is the first, the second is a bonus for 60-80% of cases. If they want the latter, add a zero to everything. You may need to staff an extra person. You will also have to track your own performance (response time, etc.) * **Define Support.** Training? Meetings? Answering Questions? Bugs only? Don't become a free department that needs to be on call 24/7. * **Priority.** - I set all my cases with priority. Only Priority 1 or 2 cases (out of 7) should be 4 hour response time. That way any fires get attention appropriately and the smaller bugs keep getting fixed. * **Cap the hours/bugs monthly.** - Cap the number of requests, or fixes per month if you insist on going on a support contract. So, up to 50 hours a month, or up to 10 priority 1, and 10 priority 2 cases, etc. Anything beyond 15 blazing infernos a month and its x per incident, where each incident is so many hours. It entirely depends on your customer and their habits. The ones who break stuff a lot and need more of your time and attention personally will need more checks and balances for both sides to be happy. * **Be optomistic, but be realistic.** With a new project neither of you know what may come. So for you to cover your unknown, what could be the absolute worst amount of time that could be spent? It's often best to work from worst case estimates instead of best case. What you're selling is essentially an insurance policy. The more unknowns and lack of data history there is, the higher your insurance policy would be, right? * **Have an air tight process.** - Have a mutually agreed upon way of defining what is support and what is a "change request" for new or modified functionality. Be sure you have the appropriate signoffs for analysis (mutual interpretation), design (how you're going to build it), and signoffs for launching so there can't be any pointing back to mis-interpretations or mis-understandings. * **Subtle abuse** - Clients, often, will make you do the leg work after a contract is up. Something looks wrong... but isn't? Send it to you to figure it out. Over time you can spend so much time supporting inquiries of where "it isn't working" when, in fact, someone is simply using you as the path of least resistance to answer their question, or what they are assuming about how it works since they have forgotten. So, to clear your name you have to show that it was how the system was used.. and not something that happened spontaneously like a bug. So, after all that.. how to bill? * **Sliding scales for billing?** Set your rate at $125 hr for priority 3 and 4 fixes, and $150/hr for Priority 2 and Priority 1 fixes. This will also encourage them to truly prioritize with their wallets and give you some breathing room to fix stuff before it becomes a raging fire. I always present it like, don't fix things that don't add value to the bottom line. Priority 1 cases are minimum 1 hour. You could be booked on other work and have to be interrupted to do it, because like everyone, you have your development time scheduled. * **Billing hourly and working up to a contract may build trust.** Building this relationship further that you're always going to act in their best interest and spend their money at least as good as your own, if not better is a great way to win more business. If they want a support contract and you say "lets just see first how much it needs to be instead of picking a high number and it not being good for you", they will respect you that much more because you are not gouging them. This, again, is best with clients that you have a good relationship with, who will likely refer you other work. If on the other hand there is a lot of devils in the details, it may be best to stick to hourly, period so they can control their decisions on what they want to address, or not. **Wild Guess:** Chances are if your client wants a support contract (maybe even approached you), they are likely very happy with you, your process, the quality of your product, and the value you have generated for their business with their $35k investment in you. They want to make sure your attention is kept for them because it is of value to them.
In today's economy, ***take the service contract*** with some protection for yourself. 1. A contract should provide stable cash flow. For example, a 24 month contract with a $500 to $1000 retainer is a guaranteed $500 to $1000 each month for 24 months. If you are just hourly, you may never get any of that. You should also guarantee the contract for the full length and if they cancel, require a payout of 4 months. 2. It should create an opportunity to be placed on a retainer as well as set some kind of hourly rate up. Maybe its 10 hours per month of support and $150 per hour for each additional hour after 10? I just threw the $ values out there. Does this company seem like they want to spend a good amount of money for good support, or are they looking to save some pennies here and there cutting quality?
Service contract - how much should we charge for 12 month service contract
[ "", "c#", "mysql", "" ]
There is a [JSLint](http://www.jslint.com) option, one of The Good Parts in fact, that "[requires] parens around immediate invocations," meaning that the construction ``` (function () { // ... })(); ``` would instead need to be written as ``` (function () { // ... }()); ``` My question is this -- can anyone explain why this second form might be considered better? Is it more resilient? Less error-prone? What advantage does it have over the first form? --- Since asking this question, I have come to understand the importance of having a clear visual distinction between function values and the values of functions. Consider the case where the result of immediate invocation is the right-hand side of an assignment expression: ``` var someVar = (function () { // ... }()); ``` Though the outermost parentheses are syntactically unnecessary, the opening parenthesis gives an up-front indication that the value being assigned is *not* the function itself but rather the result of the function being invoked. This is similar to Crockford's advice regarding capitalization of constructor functions -- it is meant to serve as a visual cue to anyone looking at the source code.
From Douglass Crockford's [style convention guide](http://javascript.crockford.com/code.html): (search for "invoked immediately") ***When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.*** So, basically, he feels it makes more clear the distinction between function values, and the values of functions. So, it's an stylistic matter, not really a substantive difference in the code itself. *updated reference, old PPT no longer exists*
Immediately Called Anonymous Functions get wrapped it in parens because: 1. They are function expressions and leaving parens out would cause it to be interpreted as a function declaration which is a syntax error. 2. Function expressions cannot start with the word function. 3. When assigning the function expression to a variable, the function itself is not returned, the return value of the function is returned~~, hence the parens evaluate what's inside them and produce a value.~~ when the function is executed, and the trailing parens `..}()` cause the function to execute immediately.
Immediate function invocation syntax
[ "", "javascript", "syntax", "jslint", "iife", "" ]
What's a good method to bind Commands to Events? In my WPF app, there are events that I'd like to capture and process by my ViewModel but I'm not sure how. Things like losing focus, mouseover, mousemove, etc. Since I'm trying to adhere to the MVVM pattern, I'm wondering if there's a pure XAML solution. Thanks!
Have a look at Marlon Grech's [Attached Command Behaviour](http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/), it could be exactly what you're looking for
Use **System.Windows.Interactivity** ``` …xmlns:i=http://schemas.microsoft.com/expression/2010/interactivity… <Slider <i:Interaction.Triggers> <i:EventTrigger EventName="ValueChanged"> <i:InvokeCommandAction Command="{Binding MyCommand}" CommandParameter="{Binding Text, ElementName=textBox}"/> </i:EventTrigger> </i:Interaction.Triggers> </Slider> ``` Make sure your project references the assembly System.Windows.Interactivity. *Source: [MSDN Blog Executing a command from an event of your choice](http://blogs.msdn.com/b/luc/archive/2010/11/18/executing-a-command-from-an-event-of-your-choice.aspx)* **[Update]** Have a look to to [**Microsoft.Xaml.Behaviors.Wpf**](https://www.nuget.org/packages/Microsoft.Xaml.Behaviors.Wpf) (available since 03.12.2018) Official package by Microsoft.
Binding Commands to Events?
[ "", "c#", "wpf", "xaml", "mvvm", "" ]
For example: ``` BitmapImage bitmap = new BitmapImage(); byte[] buffer = GetHugeByteArray(); // from some external source using (MemoryStream stream = new MemoryStream(buffer, false)) { bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = stream; bitmap.EndInit(); bitmap.Freeze(); } ``` Can you tell me any more about `using`? **Edit:** As was discussed in the comments of JaredPar's post, this question is more concerned with an implementation of `Using` in VS2003. It was pointed out that `Using` was not introduced until .NET 2.0 (VS2005). JaredPar posted an equivalent workaround.
Using has virtually the same syntax in VB as C#, assuming you're using .NET 2.0 or later (which implies the VB.NET v8 compiler or later). Basically, just remove the braces and add a "End Using" ``` Dim bitmap as New BitmapImage() Dim buffer As Byte() = GetHugeByteArrayFromExternalSource() Using stream As New MemoryStream(buffer, false) bitmap.BeginInit() bitmap.CacheOption = BitmapCacheOption.OnLoad bitmap.StreamSource = stream bitmap.EndInit() bitmap.Freeze() End Using ``` You can get the full documentation here * <http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx> **EDIT** If you're using VS2003 or earlier you'll need the below code. The using statement was not introduced until VS 2005, .NET 2.0 ([reference](http://en.wikipedia.org/wiki/Visual_Basic_2005#Visual_Basic_2005_.28VB_8.0.29)). Thanks Chris!. The following is equivalent to the using statement. ``` Dim bitmap as New BitmapImage() Dim buffer As Byte() = GetHugeByteArrayFromExternalSource() Dim stream As New MemoryStream(buffer, false) Try bitmap.BeginInit() bitmap.CacheOption = BitmapCacheOption.OnLoad bitmap.StreamSource = stream bitmap.EndInit() bitmap.Freeze() Finally DirectCast(stream, IDisposable).Dispose() End Try ```
Its important to point out that using is actually compiled into various lines of code, similar to lock, etc. From the C# language specification.... A using statement of the form ``` using (ResourceType resource = expression) statement ``` corresponds to one of two possible expansions. When `ResourceType` is a value type, the expansion is ``` { ResourceType resource = expression; try { statement; } finally { ((IDisposable)resource).Dispose(); } } ``` Otherwise, when ResourceType is a reference type, the expansion is ``` { ResourceType resource = expression; try { statement; } finally { if (resource != null) ((IDisposable)resource).Dispose(); } } ``` (end language specification snippet) Basically, at compile time its converted into that code. There is no method called using, etc. I tried to find similar stuff in the vb.net language specification but I couldn't find anything, presumably it does the exact same thing.
How does the "Using" statement translate from C# to VB?
[ "", "c#", ".net", "vb.net", "visual-studio-2005", ".net-2.0", "" ]
I am demoing a piece of software and want to build a mouse 'mover' function so that I can basically automate the process. I want to create realistic mouse movements but am having a bit of a mental block in the thought process. I can move a mouse around easily with c# but want it to be a bit more realistic than just the cursor appearing at a certain x, y, coordinates and then pressing a button. I get the current position of the mouse and then get the end point. Calculate an arc between the two points, but then I need to calculate points along that arc so that I can add a timer event into that so that I can move from one point to the next, and then repeat this till I get to the target... Anybody want to elaborate? Thanks, R.
I tried the arc calculation method, turned out to be far to complex and, in the end, it didn't look realistic. Straight lines look much more human, as JP suggests in his comment. This is a function I wrote to calculate a linear mouse movement. Should be pretty self-explanatory. GetCursorPosition() and SetCursorPosition(Point) are wrappers around the win32 functions GetCursorPos and SetCursorPos. As far as the math goes - technically, this is called [Linear Interpolation](http://en.wikipedia.org/wiki/Linear_interpolation) of a line segment. ``` public void LinearSmoothMove(Point newPosition, int steps) { Point start = GetCursorPosition(); PointF iterPoint = start; // Find the slope of the line segment defined by start and newPosition PointF slope = new PointF(newPosition.X - start.X, newPosition.Y - start.Y); // Divide by the number of steps slope.X = slope.X / steps; slope.Y = slope.Y / steps; // Move the mouse to each iterative point. for (int i = 0; i < steps; i++) { iterPoint = new PointF(iterPoint.X + slope.X, iterPoint.Y + slope.Y); SetCursorPosition(Point.Round(iterPoint)); Thread.Sleep(MouseEventDelayMS); } // Move the mouse to the final destination. SetCursorPosition(newPosition); } ```
I converted the `WindMouse` function mentioned earlier into C# and it is actually pretty realistic. Note that this is just a rough sample and does not use wrappers for `GetCursorPos` and `SetCursorPos`. I will be using the [Windows Input Simulator](http://inputsimulator.codeplex.com/) wrappers. ``` static class SampleMouseMove { static Random random = new Random(); static int mouseSpeed = 15; static void Main(string[] args) { MoveMouse(0, 0, 0, 0); } static void MoveMouse(int x, int y, int rx, int ry) { Point c = new Point(); GetCursorPos(out c); x += random.Next(rx); y += random.Next(ry); double randomSpeed = Math.Max((random.Next(mouseSpeed) / 2.0 + mouseSpeed) / 10.0, 0.1); WindMouse(c.X, c.Y, x, y, 9.0, 3.0, 10.0 / randomSpeed, 15.0 / randomSpeed, 10.0 * randomSpeed, 10.0 * randomSpeed); } static void WindMouse(double xs, double ys, double xe, double ye, double gravity, double wind, double minWait, double maxWait, double maxStep, double targetArea) { double dist, windX = 0, windY = 0, veloX = 0, veloY = 0, randomDist, veloMag, step; int oldX, oldY, newX = (int)Math.Round(xs), newY = (int)Math.Round(ys); double waitDiff = maxWait - minWait; double sqrt2 = Math.Sqrt(2.0); double sqrt3 = Math.Sqrt(3.0); double sqrt5 = Math.Sqrt(5.0); dist = Hypot(xe - xs, ye - ys); while (dist > 1.0) { wind = Math.Min(wind, dist); if (dist >= targetArea) { int w = random.Next((int)Math.Round(wind) * 2 + 1); windX = windX / sqrt3 + (w - wind) / sqrt5; windY = windY / sqrt3 + (w - wind) / sqrt5; } else { windX = windX / sqrt2; windY = windY / sqrt2; if (maxStep < 3) maxStep = random.Next(3) + 3.0; else maxStep = maxStep / sqrt5; } veloX += windX; veloY += windY; veloX = veloX + gravity * (xe - xs) / dist; veloY = veloY + gravity * (ye - ys) / dist; if (Hypot(veloX, veloY) > maxStep) { randomDist = maxStep / 2.0 + random.Next((int)Math.Round(maxStep) / 2); veloMag = Hypot(veloX, veloY); veloX = (veloX / veloMag) * randomDist; veloY = (veloY / veloMag) * randomDist; } oldX = (int)Math.Round(xs); oldY = (int)Math.Round(ys); xs += veloX; ys += veloY; dist = Hypot(xe - xs, ye - ys); newX = (int)Math.Round(xs); newY = (int)Math.Round(ys); if (oldX != newX || oldY != newY) SetCursorPos(newX, newY); step = Hypot(xs - oldX, ys - oldY); int wait = (int)Math.Round(waitDiff * (step / maxStep) + minWait); Thread.Sleep(wait); } int endX = (int)Math.Round(xe); int endY = (int)Math.Round(ye); if (endX != newX || endY != newY) SetCursorPos(endX, endY); } static double Hypot(double dx, double dy) { return Math.Sqrt(dx * dx + dy * dy); } [DllImport("user32.dll")] static extern bool SetCursorPos(int X, int Y); [DllImport("user32.dll")] public static extern bool GetCursorPos(out Point p); } ```
C# moving the mouse around realistically
[ "", "c#", "mouse", "" ]
I'm developing a system to allow users to vote on different subjects using a Yes / No / Maybe question set. Each question will be weighted as 2 (Yes) / 0 (No)/ 1 (Maybe) **NOTE(The users will be voting multiple times, potentially huge amounts)** My plan is to store the answers in a mysql db. 1. Do I store each vote separately? (ID/Vote/) 2. What is a proper query to tally the vote results? 3. What is the most efficient way to store and retrieve the results? Should I have a table that stores the vote scores?
main reason you would need to do #1 is to ensure no duplicate voting (e.g. store IP address where each vote was cast with this record). if your looking for great performance, you can do what digg.com (according to a lecture) does for some things of this nature. they store all votes in a memcached node with IP to prevent duplicates with an expiration of ~24 hrs. they then have a daemon/cron job come and tally the votes and store them in an aggregated format at the persistent/db layer.
I wouldn't store the weighted values in the DB, instead I'd use the DB as a tally system for 3 different types of votes. You can have 1 table with 3 fields in it Fields: Yes, No, Maybe, all integers. Initially start the field values at 0. Every time a vote comes in, increment the appropriate field value. After, do the weighted math in your code. As simple as multiplying the number, say in the "yes" field by 2 to get the weighted result, as an example. This is of course if the vote totals matter, and you don't care about storing each individual voters preference separately. To ensure uniqueness I'd make the user sign up up first, that way you can flag the user as already voted for that particular poll, so they can't vote again. They can always sign up again, though. Unfortunately it's tough to get around that, as they can simply use another computer, a proxy server, or a lot of people have dynamic IP's which would simply require a modem reboot to vote again, even if you did store IP's to limit such situations.
Voting system - How to store all votes in MySQL and how to properly tally the results
[ "", "php", "mysql", "" ]
In my code, I have a `div` tag with `type="hidden"`. I just don't want to show the `div`. If needed, I will show it using JQuery `Show()`. But, using this, my `div` is not hidden from view. Edit: Now I hide the `div` by using ``` <div style="visibility:hidden">XYZ</div> ``` If I need to show it again, how can I?
try using style instead of type ``` <div style="display: none;">content</div> ```
``` type="hidden" ``` is used only for hidden input textbox. If you want to hide you div use : ``` style="display:none" ``` Or with JQuery hide your div with [hide()](http://docs.jquery.com/API/1.1/Effects/Animations#hide.28.29).
Div type="hidden" + Not hided
[ "", "javascript", "html", "visibility", "" ]
Is it possible to enumerate every function present in a DLL ? How about getting its signature ? Can I do this in C# ? Or do I have to go low level to do this? Regards and tks, Jose
If it's a .NET DLL [RedGate's Reflector](http://www.red-gate.com/products/reflector/index.htm) can list the methods and even attempt to disassemble the code. It's a great item for any developer's toolbox and it's free **Edit:** If you are trying to read the types and methods at runtime you'll want to use Reflection. You would have to load the `Assembly` and `GetExportedTypes`. Then, iterate over the `Members` to the the `Methods` and `Properties`. Here is an article from MSDN that has an example of iterating over the [`MemberInfo`](http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.aspx) information. Also, here is an MSDN Magazine article, [Extracting Data from .NET Assemblies](http://msdn.microsoft.com/en-us/magazine/cc164006.aspx). Finally, Here is a little test method I wrote for executing a method on a loaded object. In this example ClassLibrary1 has one class of Class1: ``` public class Class1 { public bool WasWorkDone { get; set; } public void DoWork() { WasWorkDone = true; } } ``` And here is the test: ``` [TestMethod] public void CanExecute_On_LoadedClass1() { // Load Assembly and Types var assm = Assembly.LoadFile(@"C:\Lib\ClassLibrary1.dll"); var types = assm.GetExportedTypes(); // Get object type informaiton var class1 = types.FirstOrDefault(t => t.Name == "Class1"); Assert.IsNotNull(class1); var wasWorkDone = class1.GetProperty("WasWorkDone"); Assert.IsNotNull(wasWorkDone); var doWork = class1.GetMethod("DoWork"); Assert.IsNotNull(doWork); // Create Object var class1Instance = Activator.CreateInstance(class1.UnderlyingSystemType); // Do Work bool wasDoneBeforeInvoking = (bool)wasWorkDone.GetValue(class1Instance, null); doWork.Invoke(class1Instance, null); bool wasDoneAfterInvoking = (bool)wasWorkDone.GetValue(class1Instance, null); // Assert Assert.IsFalse(wasDoneBeforeInvoking); Assert.IsTrue(wasDoneAfterInvoking); } ```
If its a managed dll: Use reflection If its unmanaged: You need to enumerate the DLL export table
Enumerating DLL functions?
[ "", "c#", "dll", "function", "enums", "dllimport", "" ]
I would like to have users click a link, then it selects the HTML text in another element (*not* an input). By "select" I mean the same way you would select text by dragging your mouse over it. This has been a bear to research because everyone talks about "select" or "highlight" in other terms. Is this possible? My code so far: HTML: ``` <a href="javascript:" onclick="SelectText('xhtml-code')">Select Code</a> <code id="xhtml-code">Some Code here </code> ``` JS: ``` function SelectText(element) { $("#" + element).select(); } ``` Am I missing something blatantly obvious?
### Plain Javascript ``` function selectText(nodeId) { const node = document.getElementById(nodeId); if (document.body.createTextRange) { const range = document.body.createTextRange(); range.moveToElementText(node); range.select(); } else if (window.getSelection) { const selection = window.getSelection(); const range = document.createRange(); range.selectNodeContents(node); selection.removeAllRanges(); selection.addRange(range); } else { console.warn("Could not select text in node: Unsupported browser."); } } const clickable = document.querySelector('.click-me'); clickable.addEventListener('click', () => selectText('target')); ``` ``` <div id="target"><p>Some text goes here!</p><p>Moar text!</p></div> <p class="click-me">Click me!</p> ``` Here is a [working demo](http://jsfiddle.net/edelman/KcX6A/1507/). For those of you looking for a jQuery plugin, I made [one of those too](http://jsfiddle.net/edelman/KcX6A/1506/). --- ### jQuery (original answer) I have found a solution for this in [this thread](https://www.codingforums.com/archive/index.php/t-105808.html). I was able to modify the info given and mix it with a bit of jQuery to create a totally awesome function to select the text in any element, regardless of browser: ``` function SelectText(element) { var text = document.getElementById(element); if ($.browser.msie) { var range = document.body.createTextRange(); range.moveToElementText(text); range.select(); } else if ($.browser.mozilla || $.browser.opera) { var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(text); selection.removeAllRanges(); selection.addRange(range); } else if ($.browser.safari) { var selection = window.getSelection(); selection.setBaseAndExtent(text, 0, text, 1); } } ```
Here's a version with no browser sniffing and no reliance on jQuery: ``` function selectElementText(el, win) { win = win || window; var doc = win.document, sel, range; if (win.getSelection && doc.createRange) { sel = win.getSelection(); range = doc.createRange(); range.selectNodeContents(el); sel.removeAllRanges(); sel.addRange(range); } else if (doc.body.createTextRange) { range = doc.body.createTextRange(); range.moveToElementText(el); range.select(); } } selectElementText(document.getElementById("someElement")); selectElementText(elementInIframe, iframe.contentWindow); ```
Selecting text in an element (akin to highlighting with your mouse)
[ "", "javascript", "jquery", "" ]
I have googled this and keep coming up with "No it is not possible" but these posts were dated 2005-2007 so I'm wondering if this has been changed. A code example: ``` CREATE PROCEDURE `blah` ( myDefaultParam int = 0 -- This breaks the code for some reason ) BEGIN -- Do something here END ``` One of the solutions has been to pass null and then check for null and set the variable. I don't want to do that and I shouldn't have to. If this is true then MySql devs need to wake up because there is so much more I could do with MSSQL.
It's still not possible.
We worked around this limitation by adding a simple IF statement in the stored procedure. Practically we pass an empty string whenever we want to save the default value in the DB. ``` CREATE DEFINER=`test`@`%` PROCEDURE `myProc`(IN myVarParam VARCHAR(40)) BEGIN IF myVarParam = '' THEN SET myVarParam = 'default-value'; END IF; ...your code here... END ```
Is it possible to have a default parameter for a mysql stored procedure?
[ "", "sql", "mysql", "stored-procedures", "default-value", "" ]
i got a program that needs to check if a chunk of a file is zeroed or has data. This alg runs for the whole file for sizes upto a couple of gigs and takes a while to run. Is there a better way to check to see if its zeroed? Platform: Linux and windows ``` bool WGTController::isBlockCompleted(wgBlock* block) { if (!block) return false; uint32 bufSize = (uint32)block->size; uint64 fileSize = UTIL::FS::UTIL_getFileSize(m_szFile); if (fileSize < (block->size + block->fileOffset)) return false; char* buffer = new char[bufSize]; FHANDLE fh=NULL; try { fh = UTIL::FS::UTIL_openFile(m_szFile, UTIL::FS::FILE_READ); UTIL::FS::UTIL_seekFile(fh, block->fileOffset); UTIL::FS::UTIL_readFile(fh, buffer, bufSize); UTIL::FS::UTIL_closeFile(fh); } catch (gcException &) { SAFE_DELETEA(buffer); UTIL::FS::UTIL_closeFile(fh); return false; } bool res = false; for (uint32 x=0; x<bufSize; x++) { if (buffer[x] != 0) { res = true; break; } } SAFE_DELETEA(buffer); return res; } ```
How long is 'a while'? ... I'd say attempting to compare as many values in parallel as possible will help, maybe use some SIMD instructions to compare more than 4 bytes at a time? Do keep in mind though, that no matter how fast you make the comparison, ultimately the data still needs to be read from the file. If the file is not already in a cache somewhere in memory, then you may be limited to in the order of 100-150 MB/s at a maximum before the bandwidth of the disk is saturated. If you have already hit this point, then you may first need to look at an approach that avoids having to load the file, or just accept the fact that it's not going to be faster than that.
Are there places in the file/chunk where it is more likely to have non-zero values? You only have to find **one** non-zero value (your break condition), so look in places first where you most probably find them - which doesn't have to be the beginning of a file/chunk. It might make sense to start at the end, or check the 1/3 in the middle, depending on the actual application. However, I would not recommend to jump randomly to different positions; reading from disk might become incredibly ;) ..
fastest way to check if memory is zeroed
[ "", "c++", "windows", "linux", "" ]
This must be an easy question but I can't find a properly answer to it. I'm coding on VS-C++. I've a custom class 'Person' with attribute 'height'. I want to call class method Grow() that starts a timer that will increment 'height' attribute every 0.5 seconds. I'll have a StopGrow() that stops the timer and Shrink() that decrements instead of increment. I really need a little push on which timer to use and how to use it within Grow() method. Other methods must be straight forward after knowing that. That's my first question here so please be kind (and warn me if I'm doing it wrong :) Forgive my English, not my first language.
Do you really need to call the code every half second to recalculate a value? For most scenarios, there is another much simpler, faster, effective way. Don't expose a height member, but use a method such as GetHeight(), which will calculate the height at the exact moment you need it. Your Grow() method would set a base height value and start time and nothing else. Then, your GetHeight() method would subtract the starting time from the current time to calculate the height "right now", when you need it. No timers needed!
Since you're on Windows, the simplest solution is probably to use the GetTickCount() function supplied by Windows. There isn't a good timer function in the C++ language with a precision guaranteed to be less than a second. So instead, include the `windows.h` header, and then call `GetTickCount()` to get a number of milliseconds. The next time you call it, you simlpy subtract the two values, and if the result is over 500, half a second has elapsed. Alternatively, if you want to block the thread for half a second, use the `Sleep(n)` function, where `n` is the number of milliseconds you want the thread to sleep. (500 in your case)
C++ class - Increment and decrement attribute every N milliseconds
[ "", "c++", "visual-studio", "timer", "" ]
I want to get into more template meta-programming. I know that SFINAE stands for "substitution failure is not an error." But can someone show me a good use for SFINAE?
Heres one example ([from here](http://blog.olivierlanglois.net/index.php/2007/09/01/what_is_the_c_sfinae_principle)): ``` template<typename T> class IsClassT { private: typedef char One; typedef struct { char a[2]; } Two; template<typename C> static One test(int C::*); // Will be chosen if T is anything except a class. template<typename C> static Two test(...); public: enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 }; enum { No = !Yes }; }; ``` When `IsClassT<int>::Yes` is evaluated, 0 cannot be converted to `int int::*` because int is not a class, so it can't have a member pointer. If SFINAE didn't exist, then you would get a compiler error, something like '0 cannot be converted to member pointer for non-class type int'. Instead, it just uses the `...` form which returns Two, and thus evaluates to false, int is not a class type.
I like using `SFINAE` to check boolean conditions. ``` template<int I> void div(char(*)[I % 2 == 0] = 0) { /* this is taken when I is even */ } template<int I> void div(char(*)[I % 2 == 1] = 0) { /* this is taken when I is odd */ } ``` It can be quite useful. For example, i used it to check whether an initializer list collected using operator comma is no longer than a fixed size ``` template<int N> struct Vector { template<int M> Vector(MyInitList<M> const& i, char(*)[M <= N] = 0) { /* ... */ } } ``` The list is only accepted when M is smaller than or equal to N, which means that the initializer list has not too many elements. The syntax `char(*)[C]` means: Pointer to an array with element type char and size `C`. If `C` is false (0 here), then we get the invalid type `char(*)[0]`, pointer to a zero sized array: SFINAE makes it so that the template will be ignored then. Expressed with `boost::enable_if`, that looks like this ``` template<int N> struct Vector { template<int M> Vector(MyInitList<M> const& i, typename enable_if_c<(M <= N)>::type* = 0) { /* ... */ } } ``` In practice, i often find the ability to check conditions a useful ability.
What are good uses of SFINAE?
[ "", "c++", "templates", "metaprogramming", "sfinae", "" ]
In SQL, how can I remove the first 4 characters of values of a specific column in a table? Column name is `Student Code` and an example value is `ABCD123Stu1231`. I want to remove first 4 chars from my table for all records Please guide me
``` SELECT RIGHT(MyColumn, LEN(MyColumn) - 4) AS MyTrimmedColumn ``` Edit: To explain, RIGHT takes 2 arguments - the string (or column) to operate on, and the number of characters to return (starting at the "right" side of the string). LEN returns the length of the column data, and we subtract four so that our RIGHT function leaves the leftmost 4 characters "behind". Hope this makes sense. Edit again - I just read Andrew's response, and he may very well have interperpereted correctly, and I might be mistaken. If this is the case (and you want to UPDATE the table rather than just return doctored results), you can do this: ``` UPDATE MyTable SET MyColumn = RIGHT(MyColumn, LEN(MyColumn) - 4) ``` He's on the right track, but his solution will *keep* the 4 characters at the start of the string, rather than discarding said 4 characters.
``` Stuff(someColumn, 1, 4, '') ``` This says, starting with the first `1` character position, replace `4` characters with nothing `''`
How do I remove the first characters of a specific column in a table?
[ "", "sql", "sql-server", "string", "t-sql", "" ]
I have been a .NET developer since I started coding. I would like to learn Win32 programming. Need advice on where to start. What are the best resources /books for learining Win32 programming. I know a bit 'college C++'.
If you are interested in UI development, the best book for direct Win32 development in C or C++ (no MFC) is [Programming Windows](https://rads.stackoverflow.com/amzn/click/com/157231995X) by Charles Petzold For other sorts of Win32 development, such as threading, memory, DLL's, etc., [Windows via C/C++](https://rads.stackoverflow.com/amzn/click/com/0735624240) by Jeffrey Richter is a great book. For general Windows architecture, [Windows Internals](https://rads.stackoverflow.com/amzn/click/com/0735625301) by David Solomon and Mark Russinovich is a great resource.
Hands down, best book for Win32 programming is Charles Petzold's book "Programming Windows". Amazon link [here](http://www.amazon.com/exec/obidos/ISBN=157231995X).
Shifting from .NET to Win32 development
[ "", ".net", "c++", "winapi", "" ]
On my `FORM`, for some reason, I can get my form input variable via `onsubmit` but not using `action`. This works: ``` <form onsubmit="javascript:myFunc(this.city.value);"> <p><input type="text" id="city-field" name="city" onfocus="this.select();" /> <input type="submit" value="Find" /></p> </form> ``` This doesn't work (`this.city.value` is found to be null) ``` <form action="javascript:myFunc(this.city.value);"> <p><input type="text" id="city-field" name="city" onfocus="this.select();" /> <input type="submit" value="Find" /></p> </form> ``` Why is it that `onsubmit` can get the `this.city.value` but the `action` event cannot?
The form action tag doesn't reference anything with `this` Instead, use an absolute location ``` action="javascript:myFnc(document.getElementById('city-field').value)" ```
**Edit**: Thanks to Christoph's comment, below, I realized my huge oversight. Here is the final solution with his suggestion implemented. ``` <form action="" onsubmit="myFunc(this.city.value); return false;"> <p><input type="text" id="city-field" name="city" onfocus="this.select();" /> <input type="submit" value="Find" /></p> </form> ``` This should do what you need. I apologize for not giving you my full attention in my previous responses.
JavaScript - Form OnSubmit works but Action doesn't
[ "", "javascript", "html", "xhtml", "onsubmit", "" ]
we have a dotnet 2.0 desktop winforms app and it seems to randomly crash. no stack trace, vent log, or anything. it just dissapears. There are a few theories: 1. machine simply runs out of resources. some people have said you will always get a window handle exception or a gdi exception but others say it might simply cause crashes. 2. we are using wrappers around non managed code for 2 modules. exceptions inside either of these modules could cause this behavior. again, this is not reproducible so i wanted to see if there were any suggestions on how to debug better or anything i can put on the machine to "catch" the crash before it happens to help us understand whats going on.
Your best bet is to purchase John Robbins' book ["Debugging Microsoft .NET 2.0 Applications"](https://rads.stackoverflow.com/amzn/click/com/0735622027). Your question can go WAY deeper than we have room to type here.
Sounds for me like you need to log at first - maybe you can attach with PostSharp a logger to your methods ([see Log4PostSharp](http://code.google.com/p/postsharp-user-plugins/wiki/Log4PostSharp)) . This will certainly slow you down a lot and produce tons of messages. But you should be able to narrow the problematic code down ... Attach there more logs - remove others. Maybe you can stress-test this parts, later. If the suspect parts are small enough you might even do a code review there. I know, your question was about debugging - but this could be an approach, too.
How to debug random crashes?
[ "", "c#", "winforms", "" ]
I have to use a GUI Element that draws a picture at a specific screen position. If the user selects this picture there is a border drawn around the Image. Now we want to include another border that identifies pictures with a specific value for the user. At the moment the Element looks at his internal state if it is selected and then decides how to draw itself. ``` graphic.drawImage(icon, x, y, null); if (selected) { drawBorder(); } ``` I don't like the idea of adding another if else to this drawing method. I thought about creating a new class that inherits the behavior of the element and overwrites the draw method but that means duplicating the whole selected code in every inherited class. Is there a nice possibility so solve this problem without creating a subclass?
Since you tagged this with design-patterns and you seem to be looking for a pattern-oriented approach, I'd suggest taking a look at the [state pattern](http://en.wikipedia.org/wiki/State_pattern). The example on the wikipedia page even mentions keeping state while drawing a GUI. Unfortunately, this would mean you'd have to create another class with subclasses and overridden methods. Is this going to be something that is likely to change? I.e. do you realistically think you're going to be adding new behavior to the drawing (e.g. if the user double clicks, draw a different type of border; if the user right clicks, change the color of the border), or is this it? If you see more behavior being added, I think going ahead and taking a more OO approach is wise. If it's just these two cases, I'd say just add and `else if` statement.
What do you have against if-else? It makes less sense to me to create a whole new object for the selected item than to check a flag in the drawing function.
Splitting up the drawing of a GUI Element
[ "", "java", "design-patterns", "" ]
Hello I'm stuck on a simple Java exercise, I hope someone can help. Sorry if this is really simple I'm a java newbie. What I'm having trouble with: if the user enters a string other than "help" such as "foo" then I get the following error: ``` Exception in thread "main" java.lang.NumberFormatException: For input string: "foo" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:447) at java.lang.Integer.parseInt(Integer.java:497) at NumberGuess.main(NumberGuess.java:10) ``` What I think is happening: "foo" is not being caught by "else" because args[0] is an object reference and not really a string. What I want to know: How to catch everything other than "help" or the numbers "1" to "5"? Here is the code... ``` public class NumberGuess { public static void main(String args[]){ int r; int g; if ((args[0].compareTo("help")) == 0){ System.out.println("Enter a number between 1-5 to play."); } else if (Integer.parseInt(args[0]) > 0 && Integer.parseInt(args[0]) <= 5){ r = ((int)(Math.random())); g = Integer.parseInt(args[0]); if (r == g){ System.out.println("YOU WON!"); } else { System.out.println("Wrong: number was " + r); } } else { System.out.println("Something went horribly wrong."); }}} ```
The program logic is essentially, "if argument zero is not 'help', parse it as an integer…" At that point, the exception is thrown, because "foo" is not a valid integer. The simplest approach is to catch the `NumberFormatException` and print a more helpful message. ``` if ("help".equals(args[0])) { System.out.println("Enter a number between 1 and 5 to play."); } else { int number; try { number = Integer.parseInt(args[0]); } catch (NumberFormatException ex) { System.out.println("Input is not an integer: " + args[0]); return; } if ((number < 1) || (number > 5)) { System.out.println("Number out of bounds: " + number); return; } int r = new java.util.Random().nextInt(5) + 1; if (number == r) System.out.println("You won!"); else System.out.println("You lost!"); } ```
The first thing it does after looking for "Help" is trying to parse it as a number: ``` g = Integer.parseInt(args[0]); ``` What you can try to do is catch this exception by changing that line to: ``` try { g = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("The first parameter was supposed to be a number!"); System.exit(1); } ``` If you meant to accept parameters like "foo 1", then you should be parsing args[1] as the number, and args[0] you should test to see if it's "foo" like this: ``` if(args[0].equalsIgnoreCase("foo")) { // now we know foo is the first arg. Parse args[1]! ... } ``` Oh, by the way. "Random" numbers in most languages are a number between 0 and 1. They generally look like ".108937190823..." If you want to check for a number like 1-10, you need to do something like this: ``` Random().nextInt(10) + 1; // (Thanks @mmyers) ``` (Not totally sure that's the right way to do it, but it's close.
Parsing java main args[] array errors
[ "", "java", "command-line", "" ]
Given a standard piece of scheduling information, such as "the second Tuesday in June 2009" or "the last Friday in July 2009", what's the simplest and most efficient formula to translate that into a date? **Inputs:** * `w` = Week of month, enumeration (1st, 2nd, 3rd, 4th or Last) * `d` = Day of week, enum Sun through Sat * `m` = Month, integer * `y` = Year, integer **EDIT (again)** - It doesn't matter what day the week begins on; I want to get the *w*th instance of *d* in the given month. Thus the 2nd Sunday in June 2009 is 14 June, even though that technically falls in the 3rd week of June; similarly the 1st Sunday in June is 7 June, not null/exception.
Something like: ``` static DateTime GetDate(int year, int month, DayOfWeek dayOfWeek, int weekOfMonth) { // TODO: some range checking (>0, for example) DateTime day = new DateTime(year, month, 1); while (day.DayOfWeek != dayOfWeek) day = day.AddDays(1); if (weekOfMonth > 0) { return day.AddDays(7 * (weekOfMonth - 1)); } else { // treat as last DateTime last = day; while ((day = day.AddDays(7)).Month == last.Month) { last = day; } return last; } } ```
EDITED to fix bug when weekday asked for was same as dayof week of first of month. 2nd edit to fix issue disc' by Marc ``` static DateTime GetDate(int year, int month, DayOfWeek weekDay, int week) { DateTime first = new DateTime(year, month, 1); int iDow = (int)weekday, iFirst = (int)first.DayOfWeek; int adjust = (7+iDow-iFirst)%7 - 7; return first.AddDays(7*week + adjust); } ```
Simple formula for determining date using week of month?
[ "", "c#", "datetime", "calendar", "formula", "" ]
I have a tabbed html form. Upon navigating from one tab to the other, the current tab's data is persisted (on the DB) even if there is no change to the data. I would like to make the persistence call only if the form is edited. The form can contain any kind of control. Dirtying the form need not be by typing some text but choosing a date in a calendar control would also qualify. One way to achieve this would be to display the form in read-only mode by default and have an 'Edit' button and if the user clicks the edit button then the call to DB is made (once again, irrespective of whether data is modified. This is a better improvement to what is currently existing). I would like to know how to write a generic javascript function that would check if any of the controls value has been modified ?
In pure javascript, this would not be an easy task, but jQuery makes it very easy to do: ``` $("#myform :input").change(function() { $("#myform").data("changed",true); }); ``` Then before saving, you can check if it was changed: ``` if ($("#myform").data("changed")) { // submit the form } ``` In the example above, the form has an id equal to "myform". If you need this in many forms, you can easily turn it into a plugin: ``` $.fn.extend({ trackChanges: function() { $(":input",this).change(function() { $(this.form).data("changed", true); }); } , isChanged: function() { return this.data("changed"); } }); ``` Then you can simply say: ``` $("#myform").trackChanges(); ``` and check if a form has changed: ``` if ($("#myform").isChanged()) { // ... } ```
I am not sure if I get your question right, but what about addEventListener? If you don't care too much about IE8 support this should be fine. The following code is working for me: ``` var form = document.getElementById("myForm"); form.addEventListener("input", function () { console.log("Form has changed!"); }); ```
Generic way to detect if html form is edited
[ "", "javascript", "jquery", "html", "" ]
I have the following LINQ query which always results in an error when my "Remark" column in dtblDetail is null, even though I test if it is NULL. ``` var varActiveAndUsedElementsWithDetails = from e in dtblElements join d in dtblDetails on e.PK equals d.FK into set from d in set.DefaultIfEmpty() where (e.ElementActive == true) select new { ElementPK = e.PK, Remark = d.IsRemarkNull() ? null : d.Remark }; ``` The error message was: "The value for column 'Remark' in table 'dtblDetails' is DBNull." After adding the test for d.IsRemarkNull() a null reference exception is thrown. Can you help me with this? I've already checked the following websites but didn't find anything useful other than that I have to test for DBNULL. But as said this doesn't solve my problem. * <http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/3d124f45-62ec-4006-a5b1-ddbb578c4e4d> * <http://blogs.msdn.com/adonet/archive/2007/02/13/nulls-linq-to-datasets-part-3.aspx> * <http://www.vbforums.com/showthread.php?t=506645>
The problem was that the whole 'd' item was empty. So calling 'd.IsRemarkNull()' resulted in the null reference exception. The following code fixed the problem: ``` var varActiveAndUsedElementsWithDetails = from e in dtblElements join d in dtblDetails on e.PK equals d.FK into set from d in set.DefaultIfEmpty() where (e.ElementActive == true) select new { ElementPK = e.PK, Remark = d == null? null : (d.IsRemarkNull() ? null : d.Remark) }; ```
maybe this field doesn't allow null in db, get a default value for it, and avoid handling null values
LINQ to Dataset DBNULL problem / null reference exception
[ "", "c#", "linq", "dbnull", "" ]
I guess the question says it all. I want to fork on Windows. What is the most similar operation and how do I use it.
[Cygwin](http://www.cygwin.com/) has fully featured fork() on Windows. Thus if using Cygwin is acceptable for you, then the problem is solved in the case performance is not an issue. Otherwise you can take a look at how Cygwin implements fork(). From a quite old Cygwin's architecture [doc](http://www.redhat.com/support/wpapers/cygnus/cygnus_cygwin/architecture.html): > 5.6. Process Creation > The fork call in Cygwin is particularly interesting > because it does not map well on top of > the Win32 API. This makes it very > difficult to implement correctly. > Currently, the Cygwin fork is a > non-copy-on-write implementation > similar to what was present in early > flavors of UNIX. > > The first thing that happens when a > parent process forks a child process > is that the parent initializes a space > in the Cygwin process table for the > child. It then creates a suspended > child process using the Win32 > CreateProcess call. Next, the parent > process calls setjmp to save its own > context and sets a pointer to this in > a Cygwin shared memory area (shared > among all Cygwin tasks). It then fills > in the child's .data and .bss sections > by copying from its own address space > into the suspended child's address > space. After the child's address space > is initialized, the child is run while > the parent waits on a mutex. The child > discovers it has been forked and > longjumps using the saved jump buffer. > The child then sets the mutex the > parent is waiting on and blocks on > another mutex. This is the signal for > the parent to copy its stack and heap > into the child, after which it > releases the mutex the child is > waiting on and returns from the fork > call. Finally, the child wakes from > blocking on the last mutex, recreates > any memory-mapped areas passed to it > via the shared area, and returns from > fork itself. > > While we have some ideas as to how to > speed up our fork implementation by > reducing the number of context > switches between the parent and child > process, fork will almost certainly > always be inefficient under Win32. > Fortunately, in most circumstances the > spawn family of calls provided by > Cygwin can be substituted for a > fork/exec pair with only a little > effort. These calls map cleanly on top > of the Win32 API. As a result, they > are much more efficient. Changing the > compiler's driver program to call > spawn instead of fork was a trivial > change and increased compilation > speeds by twenty to thirty percent in > our tests. > > However, spawn and exec present their > own set of difficulties. Because there > is no way to do an actual exec under > Win32, Cygwin has to invent its own > Process IDs (PIDs). As a result, when > a process performs multiple exec > calls, there will be multiple Windows > PIDs associated with a single Cygwin > PID. In some cases, stubs of each of > these Win32 processes may linger, > waiting for their exec'd Cygwin > process to exit. Sounds like a lot of work, doesn't it? And yes, it is slooooow. EDIT: the doc is outdated, please see this excellent [answer](https://stackoverflow.com/questions/985281/what-is-the-closest-thing-windows-has-to-fork/985525#985525) for an update
I certainly don't know the details on this because I've never done it it, but the native NT API has a capability to fork a process (the POSIX subsystem on Windows needs this capability - I'm not sure if the POSIX subsystem is even supported anymore). A search for ZwCreateProcess() should get you some more details - for example [this bit of information from Maxim Shatskih](https://groups.google.com/forum/#!topic/comp.os.ms-windows.programmer.nt.kernel-mode/hoN_RYtnp58): > The most important parameter here is SectionHandle. If this parameter > is NULL, the kernel will fork the current process. Otherwise, this > parameter must be a handle of the SEC\_IMAGE section object created on > the EXE file before calling ZwCreateProcess(). Though note that [Corinna Vinschen indicates that Cygwin found using ZwCreateProcess() still unreliable](https://groups.google.com/forum/#!topic/microsoft.public.win32.programmer.kernel/ejtHCZmdyaI): > Iker Arizmendi wrote: > > ``` > > Because the Cygwin project relied solely on Win32 APIs its fork > > implementation is non-COW and inefficient in those cases where a fork > > is not followed by exec. It's also rather complex. See here (section > > 5.6) for details: > > > > http://www.redhat.com/support/wpapers/cygnus/cygnus_cygwin/architecture.html > ``` > > This document is rather old, 10 years or so. While we're still using > Win32 calls to emulate fork, the method has changed noticably. > Especially, we don't create the child process in the suspended state > anymore, unless specific datastructes need a special handling in the > parent before they get copied to the child. In the current 1.5.25 > release the only case for a suspended child are open sockets in the > parent. The upcoming 1.7.0 release will not suspend at all. > > One reason not to use ZwCreateProcess was that up to the 1.5.25 > release we're still supporting Windows 9x users. However, two > attempts to use ZwCreateProcess on NT-based systems failed for one > reason or another. > > It would be really nice if this stuff would be better or at all > documented, especially a couple of datastructures and how to connect a > process to a subsystem. While fork is not a Win32 concept, I don't > see that it would be a bad thing to make fork easier to implement.
What is the closest thing Windows has to fork()?
[ "", "c++", "c", "windows", "fork", "" ]
I have a weird typedef statement in a C++ program, generated by Py++. ``` double radius(int); // function to be wrapped typedef double (*radius_function_type)(int); bp::def("radius", radius_function_type(&radius)); // bp::def is a function for wrapping ``` What I figured out so far is that the above typedef statemnt is not of the type, most of us are familiar with, ``` typedef complex_type simple_alias; ``` Rather it is a way to declare pointer to a function which takes int as argument and returns double (same as the prototype). So my question now is that, how come pointer to a function **(without dereferencing)** be **called** with address of a function as an argument? This also doesn't match with the prototype. Somebody please explain!
Your question is confusing. Are you asking what this does: ``` radius_function_type(&radius)" ``` This is just a C++ typecast, a bit like: ``` radius (int (42)); ``` but since radius is already of type radius\_function\_type then you can just as easily do: ``` bp::def("radius", radius); ``` but as this is code generated by Py++, it's probably being extra careful with the output.
It doesn't declare a function pointer variable but a function pointer typedef called `radius_function_type`. `radius_function_type(&radius)` is just a (redundant) cast for the function pointer itself. (The unary `&` address-of operator is also redundant; for a function, `radius` and `&radius` are the same thing.) On a low level, calling a function is just placing the arguments somewhere according to the underlying calling convention (usually on the stack) and then jumping to a memory address. So the compiler can call a function with just a pointer if it knows the function pointer type (function signature) and the pointer value itself.
How come pointer to a function be called without dereferencing?
[ "", "c++", "function-pointers", "typedef", "" ]
What is the best method to parse a User-Agent string in Python to reliably detect 1. Browser 2. Browser version 3. OS Or perhaps any helper library that does it
I finally decided to write my own, and I am happy with the outcome. Please feel free to use/modify/send me patches, etc. It's here: <http://pypi.python.org/pypi/httpagentparser> Usage example: ``` >>> import httpagentparser >>> s = "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/532.9 (KHTML, like Gecko) \ Chrome/5.0.307.11 Safari/532.9" >>> print(httpagentparser.simple_detect(s)) ('Linux', 'Chrome 5.0.307.11') >>> print(httpagentparser.detect(s)) {'os': {'name': 'Linux'}, 'browser': {'version': '5.0.307.11', 'name': 'Chrome'}} >>> s = "Mozilla/5.0 (Linux; U; Android 2.3.5; en-in; HTC_DesireS_S510e Build/GRJ90) \ AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1" >>> print(httpagentparser.simple_detect(s)) ('Android Linux 2.3.5', 'Safari 4.0') >>> print(httpagentparser.detect(s)) {'dist': {'version': '2.3.5', 'name': 'Android'}, 'os': {'name': 'Linux'}, 'browser': {'version': '4.0', 'name': 'Safari'}} ```
[UASparser for Python](http://user-agent-string.info/download/UASparser-for-Python) by Hicro Kee. Auto updated datafile and cache from remote server with version checking.
Parsing HTTP User-Agent string
[ "", "python", "http", "http-headers", "user-agent", "" ]
Is there any SQL subquery syntax that lets you define, literally, a temporary table? For example, something like ``` SELECT MAX(count) AS max, COUNT(*) AS count FROM ( (1 AS id, 7 AS count), (2, 6), (3, 13), (4, 12), (5, 9) ) AS mytable INNER JOIN someothertable ON someothertable.id=mytable.id ``` This would save having to do two or three queries: creating temporary table, putting data in it, then using it in a join. I am using MySQL but would be interested in other databases that could do something like that.
I suppose you could do a subquery with several `SELECT`s combined with `UNION`s. ``` SELECT a, b, c, d FROM ( SELECT 1 AS a, 2 AS b, 3 AS c, 4 AS d UNION ALL SELECT 5 , 6, 7, 8 ) AS temp; ```
You can do it in PostgreSQL: ``` => select * from (values (1,7), (2,6), (3,13), (4,12), (5,9) ) x(id, count); id | count ----+------- 1 | 7 2 | 6 3 | 13 4 | 12 5 | 9 ``` <http://www.postgresql.org/docs/8.2/static/sql-values.html>
Can you define "literal" tables in SQL?
[ "", "sql", "mysql", "subquery", "temp-tables", "" ]
I want to get contents of a .php file in a variable on other page. I have two files, `myfile1.php` and `myfile2.php`. **myfile2.php** ``` <?PHP $myvar="prashant"; // echo $myvar; ?> ``` Now I want to get the value echoed by the myfile2.php in an variable in myfile1.php, I have tried the follwing way, but its taking all the contents including php tag () also. ``` <?PHP $root_var .= file_get_contents($_SERVER['DOCUMENT_ROOT']."/myfile2.php", true); ?> ``` Please tell me how I can get contents returned by one PHP file into a variable defined in another PHP file. Thanks
You can use the [include](http://www.php.net/include) directive to do this. File 2: ``` <?php $myvar="prashant"; ?> ``` File 1: ``` <?php include('myfile2.php'); echo $myvar; ?> ```
You have to differentiate two things: * Do you want to capture the output (`echo`, `print`,...) of the included file and use the output in a variable (string)? * Do you want to return certain values from the included files and use them as a variable in your *host* script? Local variables in your included files will always be moved to the current scope of your *host* script - this should be noted. You can combine all of these features into one: `include.php` ``` $hello = "Hello"; echo "Hello World"; return "World"; ``` `host.php` ``` ob_start(); $return = include 'include.php'; // (string)"World" $output = ob_get_clean(); // (string)"Hello World" // $hello has been moved to the current scope echo $hello . ' ' . $return; // echos "Hello World" ``` The `return`-feature comes in handy especially when using configuration files. `config.php` ``` return array( 'host' => 'localhost', .... ); ``` `app.php` ``` $config = include 'config.php'; // $config is an array ``` **EDIT** To answer your question about the performance penalty when using the output buffers, I just did some quick testing. 1,000,000 iterations of `ob_start()` and the corresponding `$o = ob_get_clean()` take about 7.5 seconds on my Windows machine (arguably not the best environment for PHP). I'd say that the performance impact should be considered quite small...
How to execute and get content of a .php file in a variable?
[ "", "php", "file", "return", "file-get-contents", "" ]
> **Possible Duplicate:** > [What is dependency injection?](https://stackoverflow.com/questions/130794/what-is-dependency-injection) Other developers on my team keep talking about dependency injection. I have looked it up on Wikipedia but I still don't understand exactly what it is or when I would want to use it in my designs. If you have any good examples of when you have used it or when you shouldn't that would really help me out. Thanks
The basic idea is that when an object needs some other other to do it's work (say for example, a database connection), instead of creating that object internally, the object is "injected" into the object, usually either as a constructor parameter, or by a public property that is set before the object is used. The advantage of that is that the value of the used object can be changed externally (this is especially true if the object is declared as an interface). One common use of this is to replace concrete object with mock object for unit testing.
Another term of reference which might be of assistance is "Inversion of Control". Rather than constructing your software with dependencies and assumptions about the libraries you will continue to use with that application forever, IoC or DI allow you to specify an interface which must be satisfied by some other component, then at runtime supply a mapping of interface-satisfying components for the executing application (usually in a service container which provides the IoC satisfying service as some variety of service-resolution service). This abstraction allows you to more readily replace an implementation which no longer meets your organization's needs with a new version, or even an entirely new backing technology, with a smaller footprint of change and thus lower risk. [Castle Windsor](http://www.castleproject.org/container/index.html) is one .Net implementation of an IoC container.
What is dependency injection and why would I want to use it?
[ "", "c#", "dependency-injection", "" ]
I am working on a circular problem. In this problem, we have objects that are put on a ring of size `MAX`, and are assigned IDs from (0 to MAX-1). I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is *i inRange(j,k)*). And I have the same for ranges ]j,k[ and ]j,k]. Code in those three methods look duplicated from one method to another: ``` def inRange(i,j,k): """ Returns True if i in [j, k[ * 0 <= i, j, k < MAX * no order is assumed between j and k: we can have k < j """ if j <= k: return j <= i < k # j > k : return j <= i or i < k def inStrictRange(i,j,k): """ Returns True if i in ]j, k[ * 0 <= i, j, k < MAX * no order is assumed between j and k: we can have k < j """ if j <= k: return j < i < k # j > k : return j < i or i < k def inRange2(i,j,k): """ Returns True if i in ]j, k] * 0 <= i, j, k < MAX * no order is assumed between j and k: we can have k < j """ if j <= k: return j < i <= k # j > k : return j < i or i <= k ``` Do you know any cleaner way to implement those three methods? After all, only the operators are changing?! After thinking of a better solution, I came up with: ``` from operator import lt, le def _compare(i,j,k, op1, op2): if j <= k: return op1(j,i) and op2(i,k) return op1(j,i) or op2(i,k) def inRange(i,j,k): return _compare(i,j,k, le, lt) def inStrictRange(i,j,k): return _compare(i,j,k, lt, lt) def inRange2(i,j,k): return _compare(i,j,k, lt, le) ``` Is it any better? Can you come up with something more intuitive? In short, *what would be the Pythonic way to write these three operators?* Also, I hate the inRange, inStrictRange, inRange2 names, but I can't think of crystal-clear names. Any ideas? Thanks.
Now I am thinking of something such as: ``` def comparator(lop, rop): def comp(i, j, k): if j <= k: return lop(j, i) and rop(i,k) return lop(j, i) or rop(i,k) return comp from operator import le, lt inRange = comparator(le, lt) inStrictRange = comparator(lt, lt) inRange2 = comparator(lt, le) ``` Which looks better indeed.
Two [Zen of Python](http://www.python.org/dev/peps/pep-0020/ "PEP 20: The Zen of Python") principles leap to mind: * Simple is better than complex. * There should be one—and preferably only one—obvious way to do it. # `range` The Python built-in function `range(start, end)` generates a list from `start` to `end`.1 The first element of that list is `start`, and the last element is `end - 1`. There is no `range_strict` function or `inclusive_range` function. This was very awkward to me when I started in Python. ("I just want a list from `a` to `b` inclusive! How hard is that, Guido?") However, the convention used in calling the `range` function was simple and easy to remember, and the lack of multiple functions made it easy to remember exactly how to generate a range every time. # Recommendation As you've probably guessed, my recommendation is to only create a function to test whether *i* is in the range [*j*, *k*). In fact, my recommendation is to keep only your existing `inRange` function. (Since your question specifically mentions Pythonicity, I would recommend you name the function as `in_range` to better fit with the [Python Style Guide](http://www.python.org/dev/peps/pep-0008/ "PEP 8: Style Guide for Python Code").) # Justification Why is this a good idea? * *The single function is easy to understand. It is very easy to learn how to use it.* Of course, the same could be said for each of your three starting functions. So far so good. * *There is only one function to learn. There are not three functions with necessarily similar names.* Given the similar names and behaviours of your three functions, it is somewhat possible that you will, at some point, use the wrong function. This is compounded by the fact that the functions return the same value except for edge cases, which could lead to a hard-to-find off-by-one bug. By only making one function available, you know you will not make such a mistake. * *The function is easy to edit.* It is unlikely that you'll need to ever debug or edit such an easy piece of code. However, should you need to do so, you need only edit this one function. With your original three functions, you have to make the same edit in three places. With your revised code in your self-answer, the code is made slightly less intuitive by the operator obfuscation. * *The "size" of the range is obvious.* For a given ring where you would use `inRange(i, j, k)`, it is obvious how many elements would be covered by the range [*j*, *k*). Here it is in code. ``` if j <= k: size = k - j if j > k: size = k - j + MAX ``` So therefore ``` size = (k - j) % MAX ``` # Caveats I'm approaching this problem from a completely generic point of view, such as that of a person writing a function for a publicly-released library. Since I don't know your problem domain, I can't say whether this is a practical solution. Using this solution may mean a fair bit of refactoring of the code that calls these functions. Look through this code to see if editing it is prohibitively difficult or tedious. --- 1: Actually, it is `range([start], end, [step])`. I trust you get what I mean though.
Pythonic way to implement three similar integer range operators?
[ "", "python", "operators", "" ]
I'm developing a java servlet web application that manages information from multiple databases (all structurally the same) each corresponding to a different "business". The user selects "the current business" which is stored in the session and the application can display or modify that "current business". I would like to use tomcat Resources in a dynamic way to have access to these businesses using jndi. In this way I can use the jstl sql tags or context lookups in servlets. I can not define each Resource in the web.xml file because they are stored in a SQL table. The end result is to be able to write simple jsp that has lines like these: ``` <%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %> <sql:query var = "users" dataSource="sources/${sessionScope.currentBusiness}"> select id, firstName, lastName FROM user </sql:query> ``` or servlets that can have lines like these ``` String request.getSession().getAttribute("currentBusiness"); Context initial = new InitialContext(); Context context = (Context) initial.lookup("java:comp/env"); DataSource source = (DataSource) context.lookup("sources/" + currentBusiness); ``` where I can get the correct datasource for the "current business". I have experimented with writing my own ObjectFactories derived from javax.naming.spi.ObjectFactory without success. Any pointers on how to easily do this?
I finally settled for the following solution consisting on a SessionListener and a Servlet that work as follows. The SessionListener has the following form: ``` public class SessionListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent event) { HttpSession session = event.getSession(); // get list of possible data sources available to this session List<DataSource> sources = new ArrayList<DataSource>(); ... code to get the available sources // get the current data source DataSource source = null; ... code to get the current source source = sources.get(0); // for example // setup the session attributes session.setAttribute("availableSources", sources); session.setAttribute("currentSource", source); } } ``` Whenever a user logs in and a session is created, the list of available DataSources, and the current one, are placed into the session. This is done at the Session level because DataSources depend on the user login in. It is now possible to have access at them from within the application. To change the current DataSource I created a Servlet with this simplified version: ``` public abstract class BoxletServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); String s = request.getParameter("source"); // based on 's' choose from the available DataSource List<DataSource> sources = (List<DataSource>) session.getParameter("availableSources"); Source source = chooseFrom(sources, s); session.setParameter("currentSource", source); // forward to a page saying that the DataSource changed } ``` } With this implementation it is now possible to create the following jsps: ``` <%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %> <sql:query var = "users" dataSource="${sessionScope.currentSource}"> select id, firstName, lastName FROM user </sql:query> ``` Hope it helps someone else.
Create the data sources in a [ServletContextListener](http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContextListener.html) and place them in the [ServletContext](http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContext.html).
Multiple dynamic data sources for a servlet context
[ "", "java", "tomcat", "jdbc", "jndi", "" ]
Sometimes I am looking at complex SQL Server SQL statements and wondered if there's a tool which can represent the query into a graphical model. For example: You have a select query which joins (could be inner + left and right joins) with 10 tables. Is there a tool to take this query, represent the 10 tables graphically and draw the different joins as relationships? And better yet, if you modify the joins and conditions graphically, it automatically updates the generated sql. Think of it like a reverse query builder. You start from the sql query and end at the model.
The Query Designer in Management Console is actually two-way. You can use it to draw your query graphically, or you can paste or type in your t-sql and it will show a graphic display. Just open a query window, then hit Ctrl-Shift-Q or choose "Design Query in Editor" from the Query menu.
It's not a perfect solution but you can always view the [query execution plan](http://www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx).
Tool to convert T-SQL to graphical model?
[ "", "sql", "sql-server", "" ]
I have to update a field with a value which is returned by a join of 3 tables. Example: ``` select im.itemid ,im.sku as iSku ,gm.SKU as GSKU ,mm.ManufacturerId as ManuId ,mm.ManufacturerName ,im.mf_item_number ,mm.ManufacturerID from item_master im, group_master gm, Manufacturer_Master mm where im.mf_item_number like 'STA%' and im.sku=gm.sku and gm.ManufacturerID = mm.ManufacturerID and gm.manufacturerID=34 ``` I want to update the `mf_item_number` field values of table `item_master` with some other value which is joined in the above condition. How can I do this in MS SQL Server?
``` UPDATE im SET mf_item_number = gm.SKU --etc FROM item_master im JOIN group_master gm ON im.sku = gm.sku JOIN Manufacturer_Master mm ON gm.ManufacturerID = mm.ManufacturerID WHERE im.mf_item_number like 'STA%' AND gm.manufacturerID = 34 ``` To make it clear... The `UPDATE` clause can refer to an table alias specified in the `FROM` clause. So `im` in this case is valid ### Generic example ``` UPDATE A SET foo = B.bar FROM TableA A JOIN TableB B ON A.col1 = B.colx WHERE ... ```
Adapting this to MySQL -- there is no `FROM` clause in `UPDATE`, but this works: ``` UPDATE item_master im JOIN group_master gm ON im.sku=gm.sku JOIN Manufacturer_Master mm ON gm.ManufacturerID=mm.ManufacturerID SET im.mf_item_number = gm.SKU --etc WHERE im.mf_item_number like 'STA%' AND gm.manufacturerID=34 ```
SQL update query using joins
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "sql-update", "" ]
I've been writing code for ASP.NET since the start, and today I encountered something I've never seen before. Typically I've looked for line breaks in C# (when posted in ASP.NET from a textarea, for example) by expecting "\r\n". Now I'm using the MVC framework, and the text coming over the wire from a textarea simply has "\n" for line breaks. Is there something going on in old school TextBox controls that normalizes the line breaks? Since MVC just uses the form data as-is, is this normal? Would love to get some insight.
I have made observation that the actual line break sequence differs from browser to browser. If you have a multiline textarea on a page and the page is submitted then: IE returns "\r\n" to indicate newlines. FF returns "\n" in this case. I tested it somewhere along the end of 2006, so it may be different now. I do not believe it could have anything to do with WebForms vs. MVC. Both just process submitted input and return it to you as it is. If you wish to somehow process and replace these characters it would make sense doing it in the long-to-short order: ``` string userText = form["Text"]; userText = userText.Replace ("\r\n", "<br/>").Replace ("\r", "<br/>"); ```
\n is the line ending variant on \*nix-style systems. \r\n is Windows-specific line-ending behaviour. If you're checking for line-endings and expose your interface to non-Windows environments, be sure to check not only for \r\n but also for \n alone. Fore more background, check out the [Newline](http://en.wikipedia.org/wiki/Newline) article at Wikipedia.
What's with the line break variations in C# and ASP.NET? (\r\n vs.\n)
[ "", "c#", "asp.net", "asp.net-mvc", "newline", "" ]
I have a text file that is being written to as part of a very large data extract. The first line of the text file is the number of "accounts" extracted. Because of the nature of this extract, that number is not known until the very end of the process, but the file can be large (a few hundred megs). What is the BEST way in C# / .NET to open a file (in this case a simple text file), and replace the data that is in the first "line" of text? **IMPORTANT NOTE**: - I do not need to replace a "fixed amount of bytes" - that would be easy. The problem here is that the data that needs to be inserted at the top of the file is variable. **IMPORTANT NOTE 2**: - A few people have asked about / mentioned simply keeping the data in memory and then replacing it... however that's completely out of the question. The reason why this process is being updated is because of the fact that sometimes it crashes when loading a few gigs into memory.
If you can you should insert a placeholder which you overwrite at the end with the actual number and spaces. If that is not an option write your data to a cache file first. When you know the actual number create the output file and append the data from the cache.
BEST is very subjective. For any smallish file, you can easily open the entire file in memory and replace what you want using a string replace and then re-write the file. Even for largish files, it would not be that hard to load into memory. In the days of multi-gigs of memory, I would consider hundreds of megabytes to still be easily done in memory. Have you tested this naive approach? Have you seen a real issue with it? If this is a really large file (gigabytes in size), I would consider writing all of the data first to a temp file and then write the correct file with the header line going in first and then appending the rest of the data. Since it is only text, I would probably just shell out to DOS: ``` TYPE temp.txt >> outfile.txt ```
What is the BEST way to replace text in a File using C# / .NET?
[ "", "c#", ".net", "file-io", "replace", "" ]
Its been a while since my Database Design classes in my sophomore year at Uni. and I haven't done any designs in the interim so my skills are at best rusty at the moment. I have begun working on a personal project involving the railway timetable system and seem to be stuck at the table design which resembles something like this - ``` StationTbl ------------ StnName StnCity StnCode - {Primary Key} TrainTbl --------- TrnName TrnNumber - {Primary Key} SourceStn DestStn DaysofWeek TrainHopTbl -------------- TrnNumber - {Primary Key} StationCode - {Primary Key} ArrTime DepTime HopIndex ``` Most fields are alphanumberic with the exception of the Time fields and the HopIndex in TrainHopTbl. As you can see the preliminary design is very crude and far from finished. Users will be able to find trains based on either the train name/number or by specifying the source and destination station. The first query can be easily dealt with but I am having problems writing a query for the second search where the user gives the src/dest pair and the server returns a list of trains which run on that route. This information will be extracted from TrainHopTbl which contains the list of hops for the particular train, like so - ``` TrainHopTbl -------------- Num StnCode ArrTime DepTime HopIndex 121 WDC 0900 0910 1 121 BAL 1005 1010 2 121 NYC 1145 - 3 ``` If the user enters **WDC/NYC** as the src/dest pair then the query should return Train Number 121 since it is a valid route. Any pointers/links/book suggestions on database design would be helpful. Heck, at this point even runnable queries or entire re-designs would be helpful since I seem to be stuck in a rut that I am finding hard to get out of and this has completely stalled my progress.
I'd take your SourceStn and DestStn out of your TrainTbl -- it's needless clutter. Anyway, you can get what you're looking for with: ``` select src.TrnNumber, srcSt.StnName as SourceStation, srcSt.StnCity as SourceCity, src.DepTime, destSt.StnName as DestinationStation, destSt.StnCity as DestinationCity, dest.ArrTime, (abs(dest.HopIndex - src.HopIndex)) as Stops from TrainHopTbl src inner join TrainHopTbl dest on src.TrnNumber = dest.TrnNumber inner join StationTbl srcSt on src.StnCode = srcSt.StationCode inner join StationTbl destSt on dest.StnCode = destSt.StationCode where src.StnCode = 'WDC' and dest.StnCode = 'NYC' and src.HopIndex < dest.HopIndex order by Stops asc, DepTime asc ``` Edit: I haven't taken into account transfers here. Your question mentioned just straight route trains. Let me know if you want transfers, as well.
I haven't thought this through at all yet, so this response could be way off. I think the TrainHopTbl records the nodes in a network, where it would be more useful to record the edges in a network. An edge would have a train number, a departure station, a departure time, an arrival station, and an arrival time. And maybe a hop index like the you have. So, Num: 121, Hopindex: 1, DepStnCode: WDC, DepTime: 910, ArrStnCode: BAL, ArrTime: 1005 Would describe the "hop" from Washington to Baltimore, an edge in the network of hops. (Also, I would call a hop a "leg", but that's just naming choice.) By having the hops tie two stations together, it becomes possible link up a series of hops that gets you from one place to another in a single trip. Some trips could even involve changing trains a some station, provided the arrival time is a little before the departure time for the next hop. The down side to this is that there's a little more redundancy in the station codes. I haven't figured out whether this redundancy is harmful or not.
Database Design for Transport timetable system
[ "", "sql", "database-design", "timetable", "" ]
I have a table in SQL Server 2000 that I am trying to query in a specific way. The best way to show this is with example data. Behold, `[Addresses]`: ``` Name Street City State -------------------------------------------------------- Bob 123 Fake Street Peoria IL Bob 234 Other Street Fargo ND Jim 345 Main Street St Louis MO ``` This is actually a simplified example of the structure of the actual table. The structure of the table is completely beyond my control. I need a query that will return a single address per name. It doesn't matter which address, just that there is only one. The result could be this: ``` Name Street City State -------------------------------------------------------- Bob 123 Fake Street Peoria IL Jim 345 Main Street St Louis MO ``` I found a similar question [here](https://stackoverflow.com/questions/715804/query-to-return-1-instance-of-a-record-with-duplicates), but none of the solutions given work in my case because I do not have access to `CROSS APPLY`, and calling `MIN()` on each column will mix different addresses together, and although I don't care which record is returned, it must be one intact row, not a mix of different rows. Recommendations to change the table structure will not help me. I agree that this table is terrible, (it's worse than shown here) but this is part of a major ERP database that I can not change. There are about 3000 records in this table. There is no primary key. Any ideas?
Well, this will give you pretty bad performance, but I think it'll work ``` SELECT t.Name, t.Street, t.City, t.State FROM table t INNER JOIN ( SELECT m.Name, MIN(m.Street + ';' + m.City + ';' + m.State) AS comb FROM table m GROUP BY m.Name ) x ON x.Name = t.Name AND x.comb = t.Street + ';' + t.City + ';' + t.State ```
If you can use a temp table: ``` select * -- Create and populate temp table into #Addresses from Addresses alter table #Addresses add PK int identity(1, 1) primary key select Name, Street, City, State -- Explicitly name columns here to not return the PK from #Addresses A where not exists (select * from #Addresses B where B.Name = A.Name and A.PK > B.PK) ``` This solution would not be advisable for much larger tables.
SQL query to return one single record for each unique value in a column
[ "", "sql", "t-sql", "sql-server-2000", "" ]
I have 3 home PCs that have 2008 SQL Server Express instances installed on each one of them... but right now only one has my database and I'm also running an application on that machine that requests a bunch of data from the database. I don't know a whole lot about server architecture, but I have read some guides from Microsoft's website on how execute a query on multiple servers (<http://msdn.microsoft.com/en-us/library/bb964743.aspx>) I have all of my queries going through stored procedures, so if the changes are all in the queries, then I don't think it's going to be difficult to do it. I need general information on what's the best way to set it up, here is some more details: 1. My PCs are a bit weak, so I'm trying to use as many of my home PCs as possible to balance the load. Right now I have only one PC that has the database and I'm running an application on the same PC. 2. My database is about 4GB. a. I have one stored proc that looks for specific rows. b. I have several stored procs that use temporary tables to calculate results based on the data obtained from about 20-30 rows. c. I already have an index on the columns which I'm searching. 3. I run an application on one the same PC as the DB that creates about 500 entities and each entity can have about 50 nodes, each node requests data from the database the request can be to any of the single value stored procedures, or they could be to the stored procedures that build a table (obviously the latter would be slower). Nodes are executed as fast as the database can handle the load. 4. Currently it looks like the bottleneck is the SQL server, so I'd like to distribute the load to my other PCs. **And my questions are:** 1. If I put the database on the other PCs will that increase the performance? 2. What's the best way to set up my SQL Servers in this case? 3. Any other tips/references? Is there a better way to solve my problem? FYI: I don't want to buy any hardware yet... I'm hoping for a software solution, I'm also waiting to see if I can get a free server from a friend, but even if I get a bigger server I'd still like to know how I can do load balancing.
Buy a server. Seriously. Lots of RAM, RAID disks, Server OS, no memory limit... Scaling up is preferable to scaling out, especially at this low level.
> Any other tips/references? Is there a better way to solve my problem? IMHO throw hardware at it. Before you waste time trying to configure systems/software always be running on something you could at least describe as 'adequate' rather than 'weak'.
2008 SQL Server Express Load Balancing
[ "", "sql", "sql-server", "performance", "load-balancing", "" ]
I am trying to dynamically update a tooltip made with Prototip and Prototype. The way I am trying to do this is probably not the best way (so if you know a better way that would be helpful), but the only way i could think to do it would be to hold the javascript in a div element and update the javascript inside the div element in order to update the tooltip. However, this seems to be a memory leak since each time the javascript is updated, a new Tip object is created and stored in the memory. If there isn't a better way of doing this, how can I clear the memory? I made this simple script to test the memory leak, now I need to figure out how to make it so that the memory leak is patched in this example. ``` for (i=0; i<1000; i++) { $('testdiv').update("<script type='text/javascript'> new Tip('chips_tip', 'Your Chips', {style: 'creamy',stem: 'topLeft',hook: { mouse: true, tip: 'topLeft' },offset: { x: 10, y: 16 },delay: 0.04,width: 85}); <\/script>"); } ``` Here is what the javascript for the tooltip is normally: ``` new Tip('element', "Description", { style: 'creamy', stem: 'topLeft', hook: { mouse: true, tip: 'topLeft' }, offset: { x: 10, y: 16 }, delay: 0.04, width: 85 }); ```
It seems that the new Tip construct can take an element instead of the tooltip text as a parameter. You might want to try to use that. I haven't done this so you'll have to try it by yourself. First, create the tooltip layout (div tag containing tooltip text) and style it as usual. Set the style attribute of this div to "display:none". Then try to create the tip like this: ``` new Tip('source', $('tooltip_container')); ``` You can then change the tooltip's text using: ``` $('tooltip_container').update('new tooltip text'); ``` It's not enough to assign the tooltip construct to a variable in the global space, since it seems to me that prototip inserts it's own tooltip html stuff into the dom. My guess is that every time you call "new Tip" you are adding extra html into the dom. These object's then reference dom nodes, so they are never garbage collected. Should be easy for you to check that out using your test code and firebug to inspect the dom. The final option you have is to look at the prototip source code to see if it has some sort of a setTooltipText function. Then you might be able to do something like this: ``` var tooltip = new Tip('element', 'text'); // snip tooltip.setText('some new text'); ``` If that doesn't help, just email the author of prototip. I am sure he will be glad to help.
As you have noticed, simply instantiating a new Tip will mean a new Tip object is created and stored in memory. To get around this, you need to assign the Tip to a unique variable in the global scope. i.e. instantiate the variable "tooltip", and then use "tooltip = new Tip" in your routine (this will allow for only 1 tooltip to be in use at a time, which I would assume is what you want as only one can be displayed). Garbage collection should take care of the rest.
How to free memory from a looped object
[ "", "javascript", "memory-leaks", "javascript-framework", "" ]
I have the below table with the below records in it ``` create table employee ( EmpId number, EmpName varchar2(10), EmpSSN varchar2(11) ); insert into employee values(1, 'Jack', '555-55-5555'); insert into employee values (2, 'Joe', '555-56-5555'); insert into employee values (3, 'Fred', '555-57-5555'); insert into employee values (4, 'Mike', '555-58-5555'); insert into employee values (5, 'Cathy', '555-59-5555'); insert into employee values (6, 'Lisa', '555-70-5555'); insert into employee values (1, 'Jack', '555-55-5555'); insert into employee values (4, 'Mike', '555-58-5555'); insert into employee values (5, 'Cathy', '555-59-5555'); insert into employee values (6 ,'Lisa', '555-70-5555'); insert into employee values (5, 'Cathy', '555-59-5555'); insert into employee values (6, 'Lisa', '555-70-5555'); ``` I dont have any primary key in this table .But i have the above records in my table already. I want to remove the duplicate records which has the same value in EmpId and EmpSSN fields. Ex : Emp id 5 How can I frame a query to delete those duplicate records?
Add a Primary Key (code below) Run the correct delete (code below) Consider WHY you woudln't want to keep that primary key. --- Assuming MSSQL or compatible: ``` ALTER TABLE Employee ADD EmployeeID int identity(1,1) PRIMARY KEY; WHILE EXISTS (SELECT COUNT(*) FROM Employee GROUP BY EmpID, EmpSSN HAVING COUNT(*) > 1) BEGIN DELETE FROM Employee WHERE EmployeeID IN ( SELECT MIN(EmployeeID) as [DeleteID] FROM Employee GROUP BY EmpID, EmpSSN HAVING COUNT(*) > 1 ) END ```
It is very simple. I tried in SQL Server 2008 ``` DELETE SUB FROM (SELECT ROW_NUMBER() OVER (PARTITION BY EmpId, EmpName, EmpSSN ORDER BY EmpId) cnt FROM Employee) SUB WHERE SUB.cnt > 1 ```
Delete duplicate records from a SQL table without a primary key
[ "", "sql", "t-sql", "sql-server-2005", "duplicates", "" ]
I have a method that uses an `IList<T>` as a parameter. I need to check what the type of that `T` object is and do something based on it. I was trying to use the `T` value, but the compiler does not not allow it. My solution is the following: ``` private static string BuildClause<T>(IList<T> clause) { if (clause.Count > 0) { if (clause[0] is int || clause[0] is decimal) { //do something } else if (clause[0] is String) { //do something else } else if (...) //etc for all the types else { throw new ApplicationException("Invalid type"); } } } ``` There has to be a better way to do this. Is there some way I can check the type of `T` that is passed in and then use a `switch` statement?
You could use overloads: ``` public static string BuildClause(List<string> l){...} public static string BuildClause(List<int> l){...} public static string BuildClause<T>(List<T> l){...} ``` Or you could inspect the type of the generic parameter: ``` Type listType = typeof(T); if(listType == typeof(int)){...} ```
You can use `typeof(T)`. ``` private static string BuildClause<T>(IList<T> clause) { Type itemType = typeof(T); if(itemType == typeof(int) || itemType == typeof(decimal)) ... } ```
C# Generics and Type Checking
[ "", "c#", "generics", "types", "" ]
Currently I am using following function to get the temporary folder path for current user: ``` string tempPath = System.IO.Path.GetTempPath(); ``` On some machines it gives me temp folder path of current user like: > C:\Documents and Settings\administrator\Local Settings\Temp\ On some machines it gives me system temp folder path like: > C:\Windows\TEMP MSDN Documentation also says that above API returns current system's temporary folder. Is there any other API available which gives me current user's temporary folder path like this: > C:\Documents and Settings\administrator\Local Settings\Temp\
`System.IO.Path.GetTempPath()` is just a wrapper for a native call to `GetTempPath(..)` in Kernel32. Have a look at [http://msdn.microsoft.com/en-us/library/aa364992(VS.85).aspx](http://msdn.microsoft.com/en-us/library/aa364992%28VS.85%29.aspx) Copied from that page: > The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found: > > * The path specified by the TMP environment variable. > * The path specified by the TEMP environment variable. > * The path specified by the USERPROFILE environment variable. > * The Windows directory. It's not entirely clear to me whether "The Windows directory" means the temp directory under windows or the windows directory itself. Dumping temp files in the windows directory itself sounds like an undesirable case, but who knows. So combining that page with your post I would guess that either one of the TMP, TEMP or USERPROFILE variables for your Administrator user points to the windows path, or else they're not set and it's taking a fallback to the windows temp path.
**DO NOT** use this: ``` System.Environment.GetEnvironmentVariable("TEMP") ``` Environment variables can be overridden, so the `TEMP` variable is not necessarily the directory. The correct way is to use `System.IO.Path.GetTempPath()` as in the accepted answer.
How to get temporary folder for current user
[ "", "c#", ".net", "temporary-directory", "" ]
I want to retain a variable between postbacks, so I write an accessor to put it into viewstate. Which one of these is the best way to access it? Or is there a better option? Option 1: ``` private int Status { get { try { return (int)ViewState[@"__Status"]; } catch { return 0; } } set { ViewState[@"__Status"] = value; } } ``` Option 2: ``` private int Status { get { if (ViewState[@"__Status"] is int) { return (int)ViewState[@"__Status"]; } else { return 0; } } set { ViewState[@"__Status"] = value; } } ``` Thanks Edit: I'm using C# 2.0
Here's the way that I tend to do it: ``` private int Status { get { return (ViewState["MYSTATUS"] != null) ? (int)ViewState["MYSTATUS"] : 0; } set { ViewState["MYSTATUS"] = value; } } ```
Well, option 2 won't compile, but I think it's the right direction. ;-) Try not to use an exception for this. Inspect the ViewState variable instead.
Syntax to access variables in viewstate
[ "", "c#", "asp.net", "" ]
I am just wondering if there would be any loss of speed or efficiency if you did something like this: ``` int i = 0; while(i < 100) { int var = 4; i++; } ``` which declares `int var` one hundred times. It seems to me like there would be, but I'm not sure. would it be more practical/faster to do this instead: ``` int i = 0; int var; while(i < 100) { var = 4; i++; } ``` or are they the same, speedwise and efficiency-wise?
Stack space for local variables is usually allocated in function scope. So no stack pointer adjustment happens inside the loop, just assigning 4 to `var`. Therefore these two snippets have the same overhead.
For primitive types and POD types, it makes no difference. The compiler will allocate the stack space for the variable at the beginning of the function and deallocate it when the function returns in both cases. For non-POD class types that have non-trivial constructors, it WILL make a difference -- in that case, putting the variable outside the loop will only call the constructor and destructor once and the assignment operator each iteration, whereas putting it inside the loop will call the constructor and destructor for every iteration of the loop. Depending on what the class' constructor, destructor, and assignment operator do, this may or may not be desirable.
Is there any overhead to declaring a variable within a loop? (C++)
[ "", "c++", "loops", "variable-declaration", "" ]