input
stringlengths
51
42.3k
output
stringlengths
18
55k
Conditions for a meta-circular evaluator <p>Are there any conditions that a language must satisfy so that a meta-circular evaluator can be written for that language? Can I write one for BASIC, or for Python? </p>
<p>To quote <a href="http://weblog.raganwald.com/2006/11/significance-of-meta-circular%5F22.html" rel="nofollow">Reg Braithwaite</a>:</p> <blockquote> <p>The difference between self-interpreters and meta-circular interpreters is that the latter restate language features in terms of the features themselves, instead of actually implementing them. (Circular definitions, in other words; hence the name). They depend on their host environment to give the features meaning.</p> </blockquote> <p>Given that, one of the key features of a language that allows meta-circular interpreters to be written for them is <a href="http://en.wikipedia.org/wiki/Homoiconicity" rel="nofollow">homoiconicity</a>, that is, that the primary representation of the program is a primitive datastructure of the language itself. Lisp exhibits this by virtue of the fact that programs are themselves expressed as lists.</p>
Photoshop Undo System <p>The question probably applies to drawing systems in general. I was wondering how the undo functionality is implemented in PS. Does the program take snapshots of the canvas before each operation? If so, wouldn't this lead to huge memory requirements? I've looked into the Command pattern, but I can't quite see how this would be applied to drawing.</p> <p>Regards, Menno</p>
<p>It's called the <a href="http://en.wikipedia.org/wiki/Command%5Fpattern" rel="nofollow">command pattern</a>. It's simple to implement as useful for any sort of editor.</p> <p>Photoshop applies stacked transformations upon the original image. One opetation one command. It simply unapplies the transformation when you undo. So it just keeps the original and latest versions, but I guess it might cache the last few versions just for performance. </p>
Smooth screen recording software <p>I am preparing for my senior thesis presentation. I'd like to back myself up in case there is no internet connection available. Therefore I want to record a video showing the functionality of my software. I have tried Camtasia but all the smooth and slick animations I've created, do not look that appealing. Is there an alternative. Something that will capture my screen 1 to 1, or near that. Camtasia is great, but it does not serve the purpose.</p> <p>Any help would be greatly appreciated.</p> <p>Best Regards, Kiril</p>
<p>List of <a href="http://en.wikipedia.org/wiki/List%5Fof%5Fscreencasting%5Fsoftware" rel="nofollow">screencasting</a> software</p> <p>Also, this <a href="http://www.screentoaster.com/" rel="nofollow">ScreenToaster</a> <a href="http://www.lifehacker.com.au/2009/01/screentoaster%5Frecords%5Fscreencasts%5Fand%5Faudio%5Fno%5Fsoftware%5Frequired-2/" rel="nofollow">demo</a> looks pretty smooth, and it just came out this year. Another <a href="http://www.screentoaster.com/watch/demo/screentoaster" rel="nofollow">demo</a>. Thats pretty slick. You can download the video later as a .mov file.</p>
efficient java object graph serialization <p>What is the best approach for serializing java object graphs?</p> <p>My requirements for serialization library are 1) speed of deserialization 2) size - as small as possible (smaller than in java default serialization) 3) flexibility - annotation based definitions of what has to be serialized would be nice.</p> <p>the underlying file format is not important.</p> <p>I looked at Protocol Buffers and XStream, but the former is not flexible enough due to the need for mapping files and the later produces big files.</p> <p>Any help appreciated.</p>
<p>For small objects, the Java serialised form is likely to be dominated by the description of the serialised classes.</p> <p>You may be able to write out serialised data for commonly used classes, and then use that as a common prefix for a series of serialised streams. Note that this is very fragile, and you'll probably want to recompute and check it for each class loader instance.</p>
extract title tag from html <p>I want to extract contents of title tag from html string. I have done some search but so far i am not able to find such code in VB/C# or PHP. Also this should work with both upper and lower case tags e.g. should work with both <code>&lt;title&gt;&lt;/title&gt;</code> and &lt;<code>TITLE&gt;&lt;/TITLE&gt;</code>. Thank you.</p>
<p>You can use regular expressions for this but it's not completely error-proof. It'll do if you just want something simple though (in PHP):</p> <pre><code>function get_title($html) { return preg_match('!&lt;title&gt;(.*?)&lt;/title&gt;!i', $html, $matches) ? $matches[1] : ''; } </code></pre>
Python's subprocess.Popen returns the same stdout even though it shouldn't <p>I'm having a very strange issue with Python's subprocess.Popen. I'm using it to call several times an external exe and keep the output in a list. </p> <p>Every time you call this external exe, it will return <strong>a different string</strong>. However, if I call it several times using Popen, it will always <strong>return the SAME string</strong>. =:-O </p> <p>It looks like Popen is returning always the same value from stdout, without recalling the exe. Maybe doing some sort of caching without actually calling again the exe.</p> <p>This is my code:</p> <pre><code>def get_key(): from subprocess import Popen, PIPE args = [C_KEY_MAKER, '/26', USER_NAME, ENCRYPTION_TEMPLATE, '0', ] process = Popen(args, stdout=PIPE) output = process.communicate()[0].strip() return output if __name__ == '__main__': print get_key() # Returns a certain string print get_key() # Should return another string, but returns the same! </code></pre> <p>What on Earth am I doing wrong?!</p>
<p>It is possible (if <code>C_KEY_MAKER</code>'s random behaviour is based on the current time in seconds, or similar) that when you run it twice on the command line, the time has changed in between runs and so you get a different output, but when python runs it, it runs it twice in such quick succession that the time hasn't changed and so it returns the same value twice in a row.</p>
Configure Log4Net for NHibernate <p>This has got to be a lamer question:</p> <p>In my test project I am attempting to configure log4net. The following method call gives the error.</p> <p>BasicConfigurator.Configure();</p> <p>"type name expected but method found"</p> <p>What am I overlooking?</p> <p>Thanks, Nick</p>
<p>Is this a compile time error or runtime error? Do you have a <code>using log4net.Config</code> statement in your class file? Does it still happen if you change it to reference the full class name?</p> <pre><code>log4net.Config.BasicConfigurator.Configure(); </code></pre>
Comparing HTTP and FTP for transferring files <p>What are the advantages (or limitations) of one over the other for transferring files over the Internet?</p> <p>(I am aware of secure forms of both protocols. I'd like to hear comparisons through personal experiences in terms of performance, reliability, file size limitations etc.)</p>
<p>Here's a <a href="http://www.isi.edu/lsam/publications/http-perf/">performance comparison</a> of the two. HTTP is more responsive for request-response of small files, but FTP may be better for large files if tuned properly. FTP used to be generally considered faster. FTP requires a control channel and state be maintained besides the TCP state but HTTP does not. There are 6 packet transfers before data starts transferring in FTP but only 4 in HTTP.</p> <p>I think a properly tuned TCP layer would have more effect on speed than the difference between application layer protocols. The Sun Blueprint <a href="http://www.security-science.com/mastering-internet-security/internet-security-ebooks-and-documents/item/understanding-tuning-tcp">Understanding Tuning TCP</a> has details.</p> <p>Heres another <a href="http://daniel.haxx.se/docs/ftp-vs-http.html">good comparison</a> of individual characteristics of each protocol.</p>
Debugging flash with gdb-mode in Emacs <p>I'm trying to debug a swf using fdb, the flash debugger that comes with the flex SDK, on Linux. Debugging from a terminal works, but if I do it from within Emacs by doing</p> <pre><code>M-x gdb fdb -f myswf.swf RET </code></pre> <p>fdb seems to hang as soon as I issue any commands (e.g "help" or "c"). I get no output in the fdb buffer and the flash player hangs waiting for the debugger.</p> <p><a href="http://www.emacswiki.org/emacs/EmacsFlexDebugger" rel="nofollow">This page</a> seems to indicate that using fdb with gd-mode should be possible, has anyone else had any luck?</p>
<p>I realize this one is a bit late, but I'm leaving it here for posterity: The command to use is <code>gud-gdb</code>. You should then run fdb with <code>fdb -f</code>. Once you're inside fdb, point the debugger to the swf using <code>run &lt;path_to_swf&gt;</code>.</p>
Best way to offload heavy processing (like image resizing) out of PHP request <p>I'm working on a PHP web interface that will receive huge traffic. Some insert/update requests will contain images that will have to be resized to some common sizes to speed up their further retrieval.</p> <p>One way to do it is probably to set up some asynchronous queue on the server. Eg. set up a table in a db with a tasks queue that would be populated by PHP requests and let some other process on the server watch the table and process any waiting tasks. How would you do that? What would be the proper environment for that long running process? Java, or maybe something lighter would do?</p>
<p>If what you're doing is really high volume then what you're looking for is something like <a href="http://xph.us/software/beanstalkd/" rel="nofollow">beanstalkd</a>. It is a distributed work queue processor. You just put a job on the queue and then forget about it.</p> <p>Of course then you need something at the other end reading the queue and processing the work. There are multiple ways of doing this.</p> <p>The easiest is probably to have a cron job that runs sufficiently often to read the work queue and process the requests. Alternatively you can use some kind of persistent daemon process that is woken up by work becoming available.</p> <p>The advantage of this kind of approach is you can tailor the number of workers to how much work needs to get done and beanstalkd handles distributed prorcessing (in the sense that the listners can be on different machines).</p>
When to use asynchronous operations in asio <p>When should I use asynchronous operations in boost::asio instead of synchronous operations in seperate threads?</p>
<p>Does the <a href="http://www.boost.org/doc/libs/1%5F37%5F0/doc/html/boost%5Fasio/overview/rationale.html">Rationale</a> section help?</p> <blockquote> <p>Most programs interact with the outside world in some way, whether it be via a file, a network, a serial cable, or the console. Sometimes, as is the case with networking, individual I/O operations can take a long time to complete. This poses particular challenges to application development.</p> <p>Boost.Asio provides the tools to manage these long running operations, without requiring programs to use concurrency models based on threads and explicit locking. </p> </blockquote>
input and output without a library in C <p>I'm writing a small kernel for my programs in C.</p> <p>This is not (at the moment) an OS kernel, it's merely a way for me to keep track of input and output in programs without relying on external source (i.e. stdio.h). You might ask me why I'd ever want to do this; it's just so I know how this works, and so that I have more, and more (end goal is total) control of program flow.</p> <p>I was wondering if anyone knows some tutorials on input and output in C (with inline asm?) without relying on any other code.</p>
<p>There is a lot of room between the bare metal and stdio. You have said you aren't writing an OS kernel, but not whether or not you are running under an OS.</p> <p>Running directly on hardware without an OS, you will still want to encapsulate all of your I/O operations in a module, even if you don't formally define a device driver interface and framework for all of your I/O modules to follow. This is hugely architecture dependent, and makes you responsible for knowing all of the details of interaction with every I/O device you might ever use. For some devices, this can quickly become a huge development effort. That isn't a problem for embedded systems, but running on commercial hardware this way is neither easy nor recommended.</p> <p>Running within an OS, you probably don't get (and shouldn't want to get) access to the actual hardware registers and interrupts. If you are developing a custom I/O device, the best practice is to make it conform to existing standards so that you need as little low level custom software for it as possible. This is why you see a lot of custom user interface gadgets connecting via USB and identifying themselves as HIDs (Human Interface Devices). As a HID, the existing USB drivers take care of the physical layer, and the OS-supplied HID driver takes care of the logical interface, providing a very simple high level access API to the application.</p> <p>One of the operating system's key roles is to provide a consistent I/O API across all devices. Generally, that takes the form of <code>open()</code>, <code>close()</code>, <code>read()</code>, <code>write()</code>, and <code>ioctl()</code> functions (the names vary, but some form of at least the first four will always exist). The OS layer is quite raw, however. Typically, an OS call is forwarded without much processing to a device driver, which then forwards the data on to the device. Usually, the OS low level calls block the caller until they complete, and often they have restrictions on the sizes of the buffers that make sense. For instance, raw access to a disk device is usually required to be for an integral number of disk blocks at a time.</p> <p>And don't forget about things like file systems and network protocols... all of which are made much more reliable and compatible by encapsulation within an operating system.</p> <p>Even if it is acceptable to call <code>read()</code> and <code>write()</code> for single characters, that is usually not the best performance possible. Operating system calls are relatively expensive, and if you can read multiple characters in a single call, your performance can go way up.</p> <p>That is the origin of the stdio library for C, and various other buffering libraries in other environments. The stdio library provides a buffering layer that isolates the C code from the block size of the underlying hardware. Even on an entirely home-grown operating system where you have full control over all the devices, something like C stdio will still be valuable.</p> <p>Writing your own stdio replacement is a highly valuable exercise, even if you don't use it in production code, and is one I would recommend to anyone wanting to learn about what really goes on between <code>printf()</code> and <code>scanf()</code> and the terminal or files.</p> <p>One valuable resource is the book <strong><a href="http://rads.stackoverflow.com/amzn/click/0131315099" rel="nofollow">The Standard C Library</a></strong> by P.J. Plauger. In it, the author presents an implementation of the complete C runtime library specified in the ANSI standard. His discussion of the specific implementation choices he made is valuable and apropos to the context of this question, and the discussions of why some of the standard library features were specified is interesting as well.</p>
Trouble using sandbox of symfony <p>I'm new to symfony and I am trying to run a simple command on the command line but I get an error message.</p> <p>When I try to execute the command:</p> <pre><code>d:\new_xam\xampp\htdocs\sf_sandbox_1_2\sf_sandbox&gt;symfony propel:build-model " </code></pre> <p>I get the error:</p> <blockquote> <p>'php.exe' is not recognized as an internal or external command,operable program or batch file.</p> </blockquote> <p>Can anybody help me?</p>
<p>This is a fairly common issue on Windows systems for people new to Symfony and/or PHP. It seems to be an issue with the PHP path. See here: <a href="http://forum.symfony-project.org/index.php/m/44895/?srch=php.exe%2Bcommand#msg%5F4489" rel="nofollow">http://forum.symfony-project.org/index.php/m/44895/?srch=php.exe+command#msg_44895</a></p>
Is Ruby really an interpreted language if all of its implementations are compiled into bytecode? <p>In the chosen answer for <a href="http://stackoverflow.com/questions/716543/what-is-the-significance-for-ruby-programmers-of-saps-new-implementation-of-ruby">this question about Blue Ruby</a>, Chuck says:</p> <blockquote> <p>All of the current Ruby implementations are compiled to bytecode. Contrary to SAP's claims, as of Ruby 1.9, MRI itself includes a bytecode compiler, though the ability to save the compiled bytecode to disk disappeared somewhere in the process of merging the YARV virtual machine. JRuby is compiled into Java .class files. I don't have a lot of details on MagLev, but it seems safe to say it will take that road as well.</p> </blockquote> <p>I'm confused about this compilation/interpretation issue with respect to Ruby.</p> <p>I learned that Ruby is an interpreted language and that's why when I save changes to my Ruby files I don't need to re-build the project.</p> <p>But if all of the Ruby implementations now are compiled, is it still fair to say that Ruby is an interpreted language? Or am I misunderstanding something?</p>
<p>Yes, Ruby's still an interpreted language, or more precisely, Matz's Ruby Interpreter (MRI), which is what people usually talk about when they talk about Ruby, is still an interpreter. The compilation step is simply there to reduce the code to something that's faster to execute than interpreting and reinterpreting the same code time after time.</p>
Running a stubborn executable in Dos Batch file <p>I've got a pretty stubborn executable that I would like to execute sequentially multiple times from within a Dos batch file. (Due to IT constrains currently constrained to using Dos batch files.)</p> <p>I am able to use START to launch the executable, however, it seems the executable is expecting the user to hit return prior to "really" running/executing.</p> <p>In a DOS Batch script is there anyway work with an executable that is expecting the user to hit return prior to running? I would like for the "return" to be in the script and not have to actually click on the window and manually hit return.</p> <p>Thank you for any feedback provided.</p> <p>P.S. Figured out that /wait option in START so that the next execution will start right up once the first one is finished and so on, but having trouble figuring out how to input a "return". </p>
<p>You can pipe the input from other file, for example,</p> <p>Write a text file with one carriage return and call it like..</p> <p>start "YourExe.exe &lt; text.txt",</p>
java.lang.OutOfMemoryError: Java heap space with NetBeans <p>This is the error I get when I run my web application in an instance of the Tomcat servlet container started by NetBeans. To fix this I even changed the heap size in netbeans.conf, but still it shows the same error. How can I keep this from happening?</p> <pre> HTTP Status 500 - -------------------------------------------------------------------------------- type Exception report message description The server encountered an internal error () that prevented it from fulfilling this request. exception javax.servlet.ServletException: Servlet execution threw an exception org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362) root cause java.lang.OutOfMemoryError: Java heap space note The full stack trace of the root cause is available in the Apache Tomcat/5.5.9 logs. </pre>
<p>Changing the heap size in netbeans.conf only changes the heap for NetBeans itself, not for applications run through NetBeans.</p> <p>The correct way is to right-click on the project and select "Properties" and then "Run"; there you can set the VM options appropriately (<code>-Xmx256m</code>, for instance). It should look something like this:</p> <p><img src="http://i.stack.imgur.com/AcUj8.png" alt="setting the heap size"><br> (Thanks to <a href="http://stackoverflow.com/users/6309/vonc">VonC</a> for finding this picture.)</p>
request.getresponse() giving error bad username and password <p>Im trying to access a file using request.getstream() on a server A and I have also given the network credentials.Those credentials have the admin rights on that server. But while using request.getresponse() it is showing me error Login failure: bad username and password. Can anybody suggest what could be the problem?</p>
<p>You may have to supply the domain as well in the username for instance "DOMAIN\USERNAME"</p>
ASP.NET MVC - Pass array object as a route value within Html.ActionLink(...) <p>I have a method that returns an array (string[]) and I'm trying to pass this array of strings into an Action Link so that it will create a query string similar to:</p> <pre><code>/Controller/Action?str=val1&amp;str=val2&amp;str=val3...etc </code></pre> <p>But when I pass new { str = GetStringArray() } I get the following url:</p> <pre><code>/Controller/Action?str=System.String%5B%5D </code></pre> <p>So basically it's taking my string[] and running .ToString() on it to get the value. </p> <p>Any ideas? Thanks!</p>
<p>Try creating a RouteValueDictionary holding your values. You'll have to give each entry a different key.</p> <pre><code>&lt;% var rv = new RouteValueDictionary(); var strings = GetStringArray(); for (int i = 0; i &lt; strings.Length; ++i) { rv["str[" + i + "]"] = strings[i]; } %&gt; &lt;%= Html.ActionLink( "Link", "Action", "Controller", rv, null ) %&gt; </code></pre> <p>will give you a link like</p> <pre><code>&lt;a href='/Controller/Action?str=val0&amp;str=val1&amp;...'&gt;Link&lt;/a&gt; </code></pre> <p><strong>EDIT</strong>: MVC2 changed the ValueProvider interface to make my original answer obsolete. You should use a model with an array of strings as a property.</p> <pre><code>public class Model { public string Str[] { get; set; } } </code></pre> <p>Then the model binder will populate your model with the values that you pass in the URL.</p> <pre><code>public ActionResult Action( Model model ) { var str0 = model.Str[0]; } </code></pre>
Does the Python library httplib2 cache URIs with GET strings? <p>In the following example what is cached correctly? Is there a Vary-Header I have to set server-side for the GET string?</p> <pre><code>import httplib2 h = httplib2.Http(".cache") resp, content = h.request("http://test.com/list/") resp, content = h.request("http://test.com/list?limit=10") resp, content = h.request("http://test.com/list?limit=50") </code></pre>
<p>httplib2 uses the full URI for the cache key, so in this case each of the URLs you have in your example will be cached separately by the client.</p> <p>For the chapter and verse from the <code>__init__.py</code> file for httplib2, if you would like proof, have a look at call to the cache on around line 1000:</p> <pre><code>cachekey = defrag_uri cached_value = self.cache.get(cachekey) </code></pre> <p>The defrag_uri is defined by the function <code>urlnorm</code> (line 170ish) and includes the scheme, authority, path, and query.</p> <p>Of course, as you know, the server may interpret the definition of "resource" quite differently and, so, may still return cached content. Since it sounds like you're controlling the server in this case, you have full control there, so no issues. Either way, on the client side, there would be no client-cached values used for the first call to each of the 3 URLs in your examples.</p>
Getting the last record inserted into a select query <p>I am creating a small message board and I am stuck</p> <p>I can select the subject, the original author, the number of replies but what I can't do is get the username, topic or date of the last post.</p> <p>There are 3 tables, boards, topics and messages.</p> <p>I want to get the author, date and topic of the last message in the message table. The author and date field are already fields on the messages table but i would need to join the messages and topics table on the topicid field.</p> <p>this is my query that selects the subject, author, and number of replies</p> <pre><code>SELECT t.topicname, t.author, count( message ) AS message FROM topics t INNER JOIN messages m ON m.topicid = t.topicid INNER JOIN boards b ON b.boardid = t.boardid WHERE b.boardid = 1 GROUP BY t.topicname </code></pre> <p>Can anyone please help me get this finished?</p> <p>This is what my tables look like</p> <pre><code>CREATE TABLE `boards` ( `boardid` int(2) NOT NULL auto_increment, `boardname` varchar(255) NOT NULL default '', PRIMARY KEY (`boardid`) ); CREATE TABLE `messages` ( `messageid` int(6) NOT NULL auto_increment, `topicid` int(4) NOT NULL default '0', `message` text NOT NULL, `author` varchar(255) NOT NULL default '', `date` timestamp(14) NOT NULL, PRIMARY KEY (`messageid`) ); CREATE TABLE `topics` ( `topicid` int(4) NOT NULL auto_increment, `boardid` int(2) NOT NULL default '0', `topicname` varchar(255) NOT NULL default '', `author` varchar(255) NOT NULL default '', PRIMARY KEY (`topicid`) ); </code></pre>
<p>if your SQL supports the LIMIT clause, </p> <pre><code>SELECT m.author, m.date, t.topicname FROM messages m JOIN topics t ON m.topicid = t.topicid ORDER BY date desc LIMIT 1 </code></pre> <p>otherwise:</p> <pre><code>SELECT m.author, m.date, t.topicname FROM messages m JOIN topics t ON m.topicid = t.topicid WHERE m.date = (SELECT max(m2.date) from messages m2) </code></pre> <p>EDIT: if you want to combine this with the original query, it has to be rewritten using subqueries to extract the message count and the date of last message:</p> <pre><code>SELECT t.topicname, t.author, (select count(message) from messages m where m.topicid = t.topicid) AS messagecount, lm.author, lm.date FROM topics t INNER JOIN messages lm ON lm.topicid = t.topicid AND lm.date = (SELECT max(m2.date) from messages m2) INNER JOIN boards b ON b.boardid = t.boardid WHERE b.boardid = 1 GROUP BY t.topicname </code></pre> <p>also notice that if you don't pick any field from table boards, you don't need the last join:</p> <pre><code>SELECT t.topicname, t.author, (select count(message) from messages m where m.topicid = t.topicid) AS messagecount, lm.author, lm.date FROM topics t INNER JOIN messages lm ON lm.topicid = t.topicid AND lm.date = (SELECT max(m2.date) from messages m2) WHERE t.boardid = 1 GROUP BY t.topicname </code></pre> <p>EDIT: if mysql doesn't support subqueries in the field list, you can try this:</p> <pre><code>SELECT t.topicname, t.author, mc.messagecount, lm.author, lm.date FROM topics t JOIN (select m.topicid, count(*) as messagecount from messages m group by m.topicid) as mc ON mc.topicid = t.topicid JOIN messages lm ON lm.topicid = t.topicid AND lm.date = (SELECT max(m2.date) from messages m2) WHERE t.boardid = 1 GROUP BY t.topicname </code></pre>
Can I call a Stored Procedure from an EntityDataSource? <p>(ASP.net 3.5, C#, SQL Express 2008)</p> <p>I want to have a Web Form, where I can search for "Solutions" (my table) using a keyword entered by the user and after the result comes back and populates a GridView. </p> <p>I already have parts of this search via a stored procedure that is hooked up to my Entity Data Model. On this page I have an EntityDataSource. <strong>How can I make this EntityDataSource grab data from my stored procedure?</strong></p> <p>I realize I could just fetch the result via the Entity context (which works), and bind it to the grid, but if I don't hook it up to the EntityDataSource I won't get automatic paging and sorting (which has been another struggle of mine in the past)</p>
<p>Try using the <code>Function Import</code>.</p> <ol> <li>Right click on the EntitySet Name (the heading part)</li> <li>Choose Add->Function Import</li> </ol> <p>Here is a good blog post for you to check out. <a href="http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/12/17/ado-net-entity-framework-tools-stored-procedures.aspx" rel="nofollow">ADO.NET Entity Framework Tools: Stored Procedures, by Guy Burstein</a></p> <p><strong>Update:</strong> Sorry I missed the part about the <code>EntityDataSource</code> so I don't know of any property exposed to access a function import from the EDS, but your can try to use the CommandText property.</p> <pre><code>&lt;asp:EntityDataSource ID="SolutionsDataSource" runat="server" CommandText="DataModel.SearchFunction(@Keywords)" ConnectionString="name=AdventureWorksEntities"&gt; &lt;CommandParameters&gt; &lt;asp:ControlParameter Name="Keywords" ControlID="SearchTextbox" Type="String"/&gt; &lt;/CommandParameters&gt; &lt;/asp:EntityDataSource&gt; </code></pre> <p><strong>Update:</strong> Well it seems that I have some bad news. After using <a href="http://www.red-gate.com/products/reflector/" rel="nofollow">Reflector</a> to dive deep into the <code>EntityDataSource</code>. The <code>EntityDataSourceView</code> is constructed using <code>QueryBuilderUtils.ConstructQuery</code>, which then in turn calls <code>context.CreateQuery&lt;T&gt;</code>. What you would need to execute the function import is a call to <code>context.ExecuteFunction&lt;T&gt;</code>. There doesn't seem to be any support for the ExecuteFunction in this release, the blogs I was reading did mention that it was planned, but it didn't make it into this release, whether or not it will be in future releases I can't say.</p> <p>That being said I would recommend using an <code>ObjectDataSource</code>, which you can construct in a way that still supports paging, sorting, etc. If you open an ObjectDataSource question on this topic send me a comment here and I'll take a look.</p>
Jquery passing variable problem <pre><code> for(var n=0;n&lt;10;n++) { $('#content-scroll'+n).mousewheel(function(event, delta) { if (delta &gt; 0) sliderUp(n-1); else if (delta &lt; 0) sliderDown(n-1); return false; // prevent default }); n++; } </code></pre> <p>I have a problem with this code, variable "n" is not passed right to the mouswheel function which will add mousewheel only to number 9 (last number) and not to all 10 elements. Can anyone explain how to pass a variable to this function so that it stays?</p>
<p>My take on this using a fully jQuery solution.</p> <pre><code>$("[id^='content-scroll']").mousewheel( function(event,delta) { var n = this.id.replace(/content-scroll/,''); if (delta &gt; 0) sliderUp(n); else if (delta &lt; 0) sliderDown(n); event.preventDefault(); }); </code></pre> <p><strong>EDIT</strong>: Actually, I may even try to figure out a way to pass the actual matching control to the slider* functions, but not knowing what they actually do I have no idea how or if that would work.</p>
How to install SimpleJson Package for Python <p><a href="http://pypi.python.org/pypi/simplejson">http://pypi.python.org/pypi/simplejson</a></p> <p>I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working..</p> <p>I am on a Windows System</p>
<p>I would recommend <a href="http://pypi.python.org/pypi/setuptools#windows">EasyInstall</a>, a package management application for Python.</p> <p>Once you've installed EasyInstall, you should be able to go to a command window and type:</p> <pre><code>easy_install simplejson </code></pre> <p>This may require putting easy_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like <code>C:\Python25\Scripts</code>).</p>
Pass by name and pass by value-result languages <p>For my programming languages course, I'm trying to write some code snippets in languages that use pass by name or pass by value-result, preferably by default, but any language that even supports either of those would be fine. However, I haven't been able to find a single language that supports either of them. Does anyone know of a language that uses pass by value-result or pass by name? Preferably an imperative language.</p>
<p>The <a href="http://en.wikipedia.org/wiki/Evaluation%5Fstrategy" rel="nofollow">wikipedia article on evaluation strategy</a> suggests that call-by-value-result is supported by fortran. Call-by-name is supported by algol 68.</p>
Downloading webpage image from SSL + WatiN <p>I've been thinking about this and can't seem to find a way to do this: I've got some code running on WatiN 2.0 which connects to a site via an SSL tunnel, and after performing certain tasks (which there're no other feasible ways to automate without relying on a browser) should be able to download an image from the very same SSL connection. The image is served dynamically depending on some state generated during navigation, and is not served but through the SSL connection associated with the aforementioned state, so I really need to stick with WatiN + IE.</p> <p>Thanks in advance</p>
<p>If I understand you correctly, you are trying to go to a web page (via multiple steps) and then save a copy of an image (dynamically generated) on that page right?</p> <p>If so, I don't think there's a way to do this built in to WatiN, but I stumbled across <a href="http://sourceforge.net/mailarchive/forum.php?thread%5Fname=57812bec0807240650y711588c9td91f47c7f90c4267%40mail.gmail.com&amp;forum%5Fname=watin-users" rel="nofollow">a thread on the WatiN mail list archive</a> which may help.</p> <p>Basically it looks like you can use WatiN to dynamically generate some javascript to run against your page and copy the image to the clipboard &amp; then grab the image from the clipboard in your test code.</p> <p>Hope that is of some help to you...</p>
How can you find the polynomial for a decimated LFSR? <p>I know that it if you decimate the series generated by a linear feedback shift register, you get a new series and a new polynomial. For example, if you sample every fifth element in the series generated by a LFSR with polynomial x<sup>4</sup>+x+1, you get the series generated by x<sup>2</sup>+x+1. I can find the second polynomial (x<sup>2</sup>+x+1) by brute force, which is fine for low-order polynomials. However, for higher-order polynomials, the time required to brute force it gets unreasonable.</p> <p>So the question is: is it possible to find the decimated polynomial analytically?</p>
<p>Recently read this article and thought of it when seeing your question, hope it helps.. :oÞ</p> <p>Given a primitive polynomial over GF(q), one can obtain another primitive polynomial by decimating an LFSR sequence obtained from the initial polynomial. This is demonstrated in the code below. </p> <blockquote> <p>K := GF(7); C := PrimitivePolynomial(K, 2); C; D^2 + 6*D + 3 In order to generate an LFSR sequence, we must first multiply this polynomial by a suitable constant so that the trailing coefficient becomes 1. </p> <p>C := C * Coefficient(C,0)^-1; C; 5*D^2 + 2*D + 1 We are now able to generate an LFSR sequence of length 72 - 1. The initial state can be anything other than [0, 0]. </p> <p>t := LFSRSequence (C, [K| 1,1], 48); t; [ 1, 1, 0, 2, 3, 5, 3, 4, 5, 5, 0, 3, 1, 4, 1, 6, 4, 4, 0, 1, 5, 6, 5, 2, 6, 6, 0, 5, 4, 2, 4, 3, 2, 2, 0, 4, 6, 3, 6, 1, 3, 3, 0, 6, 2, 1, 2, 5 ] We decimate the sequence by a value d having the property gcd(d, 48)=1. </p> <p>t := Decimation(t, 1, 5); t; [ 1, 5, 0, 6, 5, 6, 4, 4, 3, 1, 0, 4, 1, 4, 5, 5, 2, 3, 0, 5, 3, 5, 1, 1, 6, 2, 0, 1, 2, 1, 3, 3, 4, 6, 0, 3, 6, 3, 2, 2, 5, 4, 0, 2, 4, 2, 6, 6 ] B := BerlekampMassey(t); B; 3*D^2 + 5*D + 1 To get the corresponding primitive polynomial, we multiply by a constant to make it monic. </p> <p>B := B * Coefficient(B, 2)^-1; B; D^2 + 4*D + 5 IsPrimitive(B); true</p> </blockquote>
How to apply <p></p> tags to a text field <p>I've got a varchar() field in SQL Server that has some carriage return/linefeeds between paragraph marks. </p> <p>I'd like to turn it into properly formatted HTML. </p> <p>For instance:</p> <p>---------- before ----------</p> <p>The quick brown fox jumped over the lazy dog. Then he got bored and went to bed. After that, he played with his friends.</p> <p>The next day, he and his friends had a big party.</p> <p><hr /></p> <p>---------- after -----------</p> <p>&lt;p&gt;The quick brown fox jumped over the lazy dog. Then he got bored and went to bed. After that, he played with his friends.&lt;/p&gt;</p> <p>&lt;p&gt;The next day, he and his friends had a big party.&lt;/p&gt;</p> <p><hr /></p> <p>What's the right way to do this? Obviously regular expressions would be a good way to go, but I can't figure out how to trap the beginning of field along with the crlf (carriage return/linefeed) combo in a sane way.</p> <p>Any regex geniuses out there? Would love some help. Thanks if so!</p>
<p>A regular expression is not required for something like this. Plain string operations can do it. (Example in C#):</p> <pre><code>text = "&lt;p&gt;" + text.Replace("\r\n", "&lt;/p&gt;&lt;p&gt;") + "&lt;/p&gt;"; </code></pre> <p>(Depending on if the line breaks are system dependent or not you should use either a specific string like <code>"\r\n"</code> or the property <code>Environment.NewLine</code>.)</p> <p>If the string initially comes from user input so that you don't have total control over it, you have to properly html encode it before putting the paragraph tags in, to prevent cross site scripting attacks.</p>
What version of SQL Server do I need to move database to production server? <p>I have just finished developing an ASP.NET on my local Windows XP machine. I used Visual Studio 2008 and SQL Server express to develop the site.</p> <p>My problem is that now I would like to move the SQL Server database from my XP machine to my production server.</p> <p>I have been reading that SQL Server express cannot export my database. Is this correct? What would be the best way to export my SQL Server Express database so that I can deploy it on my production server.</p> <p>IE Do I need to download and install the full blown version of SQL Server? If so what version would be best.</p> <p>This is very frustating as I have added informaton already to the database and I do no twant to loose all this information if possible.</p> <p>Any help would be greatly appreciated...</p>
<p>SQL Server Express will be just fine for this- it uses the same native file format as the more-expensive editions. All you need to do is detach the db file, copy it to production, attach the production server to the copied file, and you're good... well, mostly good. This won't cover certain things, like logins or maintenance jobs, but all the data, stored procedures, and indexes will be there.</p> <p>What SQL Server Express will <em>not</em> do is export your database into a format like csv. And even that's not entirely true. It's just the express management studio that lacks the capability: IIRC if you connect the full edition of the sql server management studio to an express server db you can use the Export features. </p> <p>Going a step further, if you <em>really</em> need to export data from management studio express you can still just set the query window to save query results to file and write a set of export queries.</p>
Trying to upload a file with ASP.NET MVC <p>I am trying to upload a file with ASP.NET MVC.</p> <p>The following code work perfectly fine:</p> <pre><code>// Read in the image data. byte[] binaryData = null; HttpPostedFileBase uploadedFile = Request.Files["ImageFileName"]; if (uploadedFile != null &amp;&amp; uploadedFile.ContentLength &gt; 0) { binaryData = new byte[uploadedFile.ContentLength]; uploadedFile.InputStream.Read(binaryData, 0, uploadedFile.ContentLength); } </code></pre> <p>But what I am trying to do is use the new <code>FileCollectionModelBinder</code> found in the <em>futures</em> assembly.</p> <p>I've found these two blog posts <a href="http://msmvps.com/blogs/luisabreu/archive/2009/03/17/the-mvc-framework-working-with-uploaded-files.aspx" rel="nofollow">here</a> and <a href="http://www.hanselman.com/blog/ASPNETMVCBetaReleasedCoolnessEnsues.aspx" rel="nofollow">here</a> explaining what to do. I follow these instructions but havne't had any luck -> the <code>file</code> object is always <code>null</code>.</p> <p>Here is my method.</p> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([Bind(Include = "Subject, Content")] Post post, HttpPostedFileBase file) { UpdateModel(post); ... } </code></pre> <p>Notice how i'm trying to upload a file AND upload some post information, to a Post object.</p> <p>Can anyone make any suggestions?</p> <p>For the record, I have wired up the ModelBinder in my global.asax.cs. I've also made sure the form is a post with the enctype added:-</p> <pre><code>&lt;form method="post" enctype="multipart/form-data" action="/post/create"&gt; </code></pre>
<p>No bloody way :(</p> <p>I figured out that answer and it's pretty lame.</p> <p>I had to have the argument <em>NAME</em> being identical to the Id/Name values of the input type="file" element!!! (not sure if it's either or both element values ... i didn't check that bit out).</p> <p>so this is the answer.</p> <h3>Html input element. (note the value of the Id/Name)</h3> <pre><code>&lt;input type="file" id="imageFileName" name="imageFileName" class="upload" /&gt; </code></pre> <h3>Controller method</h3> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([Bind(Include = "Subject, Content")]Post post, HttpPostedFileBase imageFileName) { ... } </code></pre> <p>shees!</p>
Segmentation fault in strcpy <p>consider the program below</p> <pre><code> char str[5]; strcpy(str,"Hello12345678"); printf("%s",str); </code></pre> <p>When run this program gives segmentation fault.</p> <p>But when strcpy is replaced with following, program runs fine.</p> <pre><code>strcpy(str,"Hello1234567"); </code></pre> <p>So question is it should crash when trying to copy to str any other string of more than 5 chars length.</p> <p>So why it is not crashing for "Hello1234567" and only crashing for "Hello12345678" ie of string with length 13 or more than 13.</p> <p>This program was run on 32 bit machine .</p>
<p>There are three types of standards behaviour you should be interested in.</p> <p>1/ <em>Defined behaviour</em>. This will work on all complying implementations. Use this freely.</p> <p>2/ <em>Implementation-defined behaviour</em>. As stated, it depends on the implementation but at least it's still defined. Implementations are required to document what they do in these cases. Use this if you don't care about portability.</p> <p>3/ <em>Undefined behaviour</em>. Anything can happen. And we mean <em>anything</em>, up to and including your entire computer collapsing into a naked singularity and swallowing itself, you and a large proportion of your workmates. Never use this. Ever! Seriously! Don't make me come over there.</p> <p>Copying more that 4 characters and a zero-byte to a <code>char[5]</code> is undefined behaviour.</p> <p>Seriously, it doesn't matter why your program crashes with 14 characters but not 13, you're almost certainly overwriting some non-crashing information on the stack and your program will most likely produce incorrect results anyway. In fact, the crash is better since at least it stops you relying on the possibly bad effects.</p> <p>Increase the size of the array to something more suitable (<code>char[14]</code> in this case with the available information) or use some other data structure that can cope.</p> <hr> <p><em>Update:</em></p> <p>Since you seem so concerned with finding out why an extra 7 characters doesn't cause problems but 8 characters does, let's envisage the possible stack layout on entering <code>main()</code>. I say "possible" since the actual layout depends on the calling convention that your compiler uses. Since the C start-up code calls <code>main()</code> with <code>argc</code> and <code>argv</code>, the stack at the start of <code>main()</code>, after allocating space for a <code>char[5]</code>, could look like this:</p> <pre><code>+------------------------------------+ | C start-up code return address (4) | | argc (4) | | argv (4) | | x = char[5] (5) | +------------------------------------+ </code></pre> <p>When you write the bytes <code>Hello1234567\0</code> with:</p> <pre><code>strcpy (x, "Hello1234567"); </code></pre> <p>to <code>x</code>, it overwrites the <code>argc</code> and <code>argv</code> but, on return from <code>main()</code>, that's okay. Specifically <code>Hello</code> populates <code>x</code>, <code>1234</code> populates <code>argv</code> and <code>567\0</code> populates <code>argc</code>. Provided you don't actually try to <em>use</em> <code>argc</code> and/or <code>argv</code> after that, you'll be okay:</p> <pre><code>+------------------------------------+ Overwrites with: | C start-up code return address (4) | | argc (4) | '567&lt;NUL&gt;' | argv (4) | '1234' | x = char[5] (5) | 'Hello' +------------------------------------+ </code></pre> <p>However, if you write <code>Hello12345678\0</code> (note the extra "8") to <code>x</code>, it overwrites the <code>argc</code> and <code>argv</code> <em>and also</em> one byte of the return address so that, when <code>main()</code> attempts to return to the C start-up code, it goes off into fairy land instead:</p> <pre><code>+------------------------------------+ Overwrites with: | C start-up code return address (4) | '&lt;NUL&gt;' | argc (4) | '5678' | argv (4) | '1234' | x = char[5] (5) | 'Hello' +------------------------------------+ </code></pre> <p>Again, this depends entirely on the calling convention of your compiler. It's possible a different compiler would always pad out arrays to a multiple of 4 bytes and the code wouldn't fail there until you wrote another three characters. Even the same compiler may allocate variables on the stack frame differently to ensure alignment is satisfied.</p> <p>That's what they mean by undefined: you don't <em>know</em> what's going to happen.</p>
Maintaining page breaks <p>In my Rails app, I have a lot of data that is declared as <code>text</code> in the migration file. But when I print these attributes/fields out in the view, all the line breaks are lost and I get one large chunk of text. How do I maintain the line breaks?</p>
<p>This is an HTML problem. Its rules state that consecutive whitespace is converted to a single space.</p> <p>Rails has a <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M001719" rel="nofollow"><code>simple_format</code></a> function that wraps blocks of text in <p> tags so you get the separation you want </p>
C# dictionary<> missing key <p>When i do val = dict["nonexistent key"] i get System.Collections.Generic.KeyNotFoundException Is there a way i have my dictionary call a member function with the key as a param to generate a value?</p> <p>-edit- Maybe i should of been more specific. I want to AUTOMATICALLY call a member function to do what it needs create the proper value for that key. In this case it makes an entry in my DB then gives me back its unique handle. I'll post below what my solution was.</p>
<p>Use an extension method:</p> <pre><code>static class DictionaryExtensions { public static TValue GetValueOrDefault&lt;TKey, TValue&gt;(this Dictionary&lt;TKey,TValue&gt; dic, TKey key, Func&lt;TKey, TValue&gt; valueGenerator) { TValue val; if (dic.TryGetValue(key, out val)) return val; return valueGenerator(key); } } </code></pre> <p>You can call it with:</p> <pre><code>dic.GetValueOrDefault("nonexistent key", key =&gt; "null"); </code></pre> <p>Or pass a member function:</p> <pre><code>dic.GetValueOrDefault("nonexistent key", MyMemberFunction); </code></pre>
Not nullable types <p>Is there a way to create a non nullable type in C# (like DateTime or TimeSpan).?</p> <p>Also is there a way (an attribute maybe) to enforce that not null arguments wouldn't be passed to methods and properties without adding </p> <pre><code>if(arg1 == null) { throw new ArgumentNullException("this attribute is null") } </code></pre>
<p><code>DateTime</code> and <code>TimeSpan</code> are not-nullable since they are <code>struct</code>s rather than <code>class</code>es. </p> <p>As for your second question, there is no standard way you can do this in C#. You can do this using PostSharp, which is an AOP framework, or with <a href="http://research.microsoft.com/SpecSharp">Spec#</a>, which is a whole new language (an extension of C#) which allows for some of desired behavior.</p>
How to traverse a binary tree in O(n) time without extra memory <p>Given a binary tree with an integer, Left &amp; Right pointers, how can one traverse the tree in O(n) time and O(1) extra memory (no stack/queue/recursion)?</p> <p><a href="http://nandacumar.blogspot.com/2006/06/traversing-tree.html">This guy</a> gave a solution which is not O(n) total time that encoded the current path as an integer (and thus works on for trees of limited depth).</p> <p>I am looking for the classical solution</p> <p>(SPOILER)</p> <p>that encoded the parent of each node in the children.</p>
<p>Any good algorithm book will have this algorithm, look e.g. in Knuth (TAOCP I.2.3.1 Traversing binary trees, excercise 21). However, because this algorithm modifies the tree in place, you must use <em>extreme</em> caution in a multi-threaded environment.</p> <p>You might also use threaded trees (see in Knuth).</p>
Stretch right float div width? <p>I have 2 float:left div, the first is fixed and i want the second div stretch the remain space.</p> <pre><code>&lt;div id="container"&gt; &lt;div id="leftform"&gt; &lt;/div&gt; &lt;div id="rightform"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Any idea? Thanks</p>
<p>In CSS2:</p> <pre><code>#container {display:table; table-layout:fixed;} #leftform, #rightform {display:table-cell;} #leftform {width:100px;} </code></pre> <p>In world of IE hacks:</p> <pre><code>#container {padding-left:100px;} #leftform {float:left; width:100px; margin-left:-100px;} </code></pre>
Visual Studio add-in API resources <p>Where can I find examples and API information, besides the MSDN, on creating add-ins for Visual Studio .net 2008?</p>
<ol> <li>Download the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=30402623-93ca-479a-867c-04dc45164f5b&amp;DisplayLang=en">Visual Studio SDK</a>.</li> <li>Go to the <a href="http://msdn.microsoft.com/en-us/vsx/default.aspx">Visual Studio Extensibility</a> Developer Center</li> <li>Visit the <a href="http://social.msdn.microsoft.com/Forums/en-US/vsx/threads">Visual Studio Extensibility Forum</a></li> </ol>
Conversion tool comparisons for visual basic 6.0 <p>Has anyone here used either of the following (or any other tool) to convert your vb6 code to a .net language?</p> <p><a href="http://www.artinsoft.com/pr%5Fvbcompanion.aspx"><strong>Artinsoft's upgrade companion</strong> </a> (converts to c# and vb.net)</p> <p><a href="http://www.vbmigration.com/"><strong>vbmigration partner</strong> </a> (converts to vb.net)</p> <p>How effective were they and what size project did you convert?</p> <p>How much work was left to do afterwards? How happy are you with the resultant .net project. What was the support like? Is there a support forum anywhere for users of tools like these, neither vendor seems to offer one.</p> <p>What did they charge, their prices are not published and I have heard wildly differing prices from different sources for both the above examples</p>
<p>I am Eugenio La Mesa, general manager at Code Architects. I read a few comments on our VB Migration Partner and conversion tools in general, and thought I might add some hopefully useful hints.</p> <p>First, our conversion software does support all VB6 graphic properties and methods – with the only exception of DrawMode and ClipControls. We even support the AutoRedraw property and user-defined ScaleMode coordinates, therefore the migration of a CAD-like program to VB.NET is quite in the reach of our software. The Code Sample section at www.vbmigration.com contains many examples of graphic-intensive VB6 apps that have been converted to .NET with minimal effort.</p> <p>Second, let me clarify our price structure. We sell two different editions of VB Migration Partner: the Professional Edition can convert VB6 apps with max. 50,000 lines of code, whereas the Enterprise Edition has no size limitation and supports a few additional advanced features, such as integration with source code control software and generation of .NET components that are binary-compatible with the original VB6 DLL, which allows you to implement staged migrations of N-tiered COM-based applications.</p> <p>The price of the Professional Edition for £399 is a special promotion up to June 30th 2009, during a Microsoft UK marketing campaign, for UK only and for applications up to 50K lines of code (LOCs). The price of the Enterprise Edition may vary because it depends on several factors, including number of licenses and number of LOCs to be migrated. This explains why you may see different price quotations. Also, we have recently slightly decreased the list price as our answer to the economic situation. We are also planning to take a few features out of the main product and offer them separately, which would result in a more flexible price structure. </p> <p>Quite honestly, for applications with 25-50K LOCs we usually recommend a manual rewrite. In fact, our focus is on the enterprise market segment, where you often finds VB6 apps with several hundred thousand LOCs, if not millions. In those cases, a manual rewrite is seldom a viable option: it requires too many skilled VB6/.NET developers, it takes too long, or just costs too much. We have recently published a case study related to an application with 650K LOCs; one of our customers is currently migrating a monster app with about 15 million LOCs!</p>
Quick sort in GLSL? <p>I'm considering porting a large chunk of processing to the GPU using a GLSL shader. One of the immediate problems I stumbled across is that in one of the steps, the algorithm needs to maintain a list of elements, sort them and take the few largest ones (which number is dependent on the data). On the CPU this is simply done using an STL vector and qsort() but in GLSL I don't have such facilities. Is there a way to deal with this deficiency?</p>
<p>Disclosure: I really don't know GLSL -- I've been doing GPGPU programming with the AMD Stream SDK, which has different programming language.</p> <p>From you comment on Bjorn's answer, I gather that you are <strong>not</strong> interested in using the GPU to sort a huge database -- like creating a reverse phone book or whatever, but instead, you have a small dataset and each fragment has it's own dataset to sort. More like trying to do median pixel filtering?</p> <p>I can only say in general:</p> <p>For small datasets, the sort algorithm really doesn't matter. While people have spent careers worrying about which is the best sort algorithm for very large databases, for small N it really doesn't matter whether you use Quick sort, Heap Sort, Radix Sort, Shell Sort, Optimized Bubble Sort, Unoptimized Bubble sort, etc. At least it doesn't matter much on a CPU.</p> <p>GPUs are SIMD devices, so they like to have each kernel executing the same operations in lock step. Calculations are cheap but branches are expensive and data-dependent branches where each kernel branchs a different way is very, very, very, expensive.</p> <p>So if each kernel has it's own small dataset to sort, and the # of data to sort is data dependent and it could be a different number for each kernel, you're probably better off picking a maximum size (if you can), padding the arrays with Infinity or some large number, and having each kernel perform the exact same sort, which would be an unoptimized branchless bubble sort, something like this:</p> <p>Pseudocode (since I don't know GLSL), sort of 9 points </p> <pre><code>#define TwoSort(a,b) { tmp = min (a, b); b = a + b - tmp; a = tmp; } for (size_t n = 8; n ; --n) { for (size_t i = 0; i &lt; n; ++i) { TwoSort (A[i], A[i+1]); } } </code></pre>
Why POP3 protocol survives? <p>I am getting some basic knowledge e-mail protocol. It seems that IMAP is more powerful than POP3. Then, why POP3 protocol survives? and it is still supported by popular email service like GMail?</p> <p>Thanks.</p>
<p>Read the IMAP specification(s) and you know. POP3 is more KISS than IMAP.</p>
ASP.NET Workflow CallExternalMethod <p>I'm not sure if im missing something obvious, with Windows Workflow used from within ASP.NET I don't really know how to get output from the Workflow back to the ASP.NET workflow. </p> <p>I have my workflow setup to handle external event, so my web page can invoke it, which works fine, but how do I get the information out again? Do I have to query the Workflow object to find the information I want? This just seems wrong...What I thought I could do was use the CallExternalMethod in the workflow, but since there can only be one instance of the Workflow External Data service in the runtime, i'm not sure how it can be 'attached' to the individual pages?</p> <p>All examples I have found seem to use the Page Workflow example in which the output from the workflow (when it calls CallExternalMethod) just calls the static redirect method. If for example I didnt want to redirect, but print the result from the workflow to the page, how do i 'capture' that information so it can be used in the page? (assuming that the runtime is called from a wrapper like the examples, so cant just do Label1.Text = bla since there is no access to that variable).</p> <p>Edit: Or is it a matter of using the workflow to persist anything to the database and have the ASP.NET app qiery the given data from there (since instance GUID can be used as PK?)</p>
<p>This link has information about passing information in and out of workflows:</p> <p><a href="http://books.google.com/books?id=s5eVXpNmQxgC&amp;pg=PA32&amp;dq=pro%2Bwindows%2Bworkflow%2Bfoundation#PPA241,M1" rel="nofollow">http://books.google.com/books?id=s5eVXpNmQxgC&amp;pg=PA32&amp;dq=pro+windows+workflow+foundation#PPA241,M1</a></p> <p>In respect to a web page:<br/> The only difference to a webpage and the WinForm example in the link above is that you need to use the MaualWorkflowSchedulerService (this donates the thread the webpage used instead of making a new one for the workflow runtime). <br/></p> <p>So, say you are invoking the ExternalMethod in a button click with somthing like this (DataEvents being the service you add to the run time for your Handle / Call external methods):</p> <pre><code> AddHandler DataEvents.DataReceived, AddressOf workflowEventsDataReceived manualScheduler = WorkflowrunTime.GetService(GetType(Hosting.ManualWorkflowSchedulerService)) DataEvents.OnGetDataReceived(New ExternalDataEventArgs(WorkflowInstance.InstanceId)) manualScheduler.RunWorkflow(WorkflowInstance.InstanceId) </code></pre> <p>Then the method at workflowEventsDataReceived, which is the target of a CallExternalMethod inside the workflow (via the service you added to the WorkflowrunTime) will be able to update all the labels you want.</p> <p>Not sure if any of that is clear, but let me know if need more help, was going through the same problem myself last weekend.</p>
NSArray with Custom Objects in NSTableDataSource <p>I am trying to make NSTableDataSource compatible object and give this object to NSTableView as DataSource, however when table tries to display data, it crashes. </p> <pre><code>@interface NSArrayDataSource : NSObject{ NSArray* internalArray; } -(id) initWithArray: (NSArray*) objects; -(int)numberOfRowsInTableView:(NSTableView *)aTableView; -(id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex; -(void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex; @end @implementation NSArrayDataSource -(id) initWithArray: (NSArray*) objects{ if(self = [super init]) { internalArray = [[NSArray alloc] initWithArray:objects]; } return self; } -(int)numberOfRowsInTableView:(NSTableView *)aTableView{ return [internalArray count]; } -(id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex{ id obj = [internalArray objectAtIndex:rowIndex]; // when I debug, I get same pointers with invalid data // each object has "name" message // this following line gives invalid pointer and // it crashes return [obj name]; } -(void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex{ } @end </code></pre> <p>Can anyone tell me what could be the problem?</p> <p>Right now I have removed every release and dealloc messages from my class, so no object is removed, I have done retain message call everywhere when I transfer data.</p> <pre><code>NSArrayDataSource* nsds = [[NSArrayDataSource alloc] initWithArray: myArray]; [tableView setDataSource:nsds]; </code></pre> <p>I have one doubt, does NSArray does call [retain] for every objects while creating new object or it is just storing pointer values?</p> <p>Suppose my object's name is "SLProject" then when I debug, in init method I see values under debug window correctly but in tableView delegation method the internalArray's debugger displays object of type "NSKVONotifying_SLProject" and they point to invalid data, however the addresses are correct.</p>
<p>In answer to your question about <code>NSArray</code> object creation, yes, each object receives a <code>retain</code> message when it is added to the array, and a <code>release</code> message when it is removed. From the Apple docs:</p> <blockquote> <p>In general, objects that you add to an array aren’t copied; rather, each object receives a retain message before its id is added to the array. When an object is removed from an array, it’s sent a release message.</p> </blockquote> <p>As for your object's <code>name</code> function, how is it implemented? If you replace <code>[obj name]</code> with <code>[obj description]</code> does this still crash your application?</p>
Is there an async version of DirectoryInfo.GetFiles / Directory.GetDirectories in dotNet? <p>Is there an asynchronous version of DirectoryInfo.GetFiles / Directory.GetDirectories in dotNet? I'd like to use them in an F# async block, and it'd be nice to have a version that can be called with AsyncCallbacks. </p> <p>Problem is I'm trying to suck in a bunch of directories, probably on SMB mounts over slow network connections, and I don't want a bunch of thread pool threads sitting around waiting for network reads when they could be doing other work.</p>
<p>I didn't find an async version of GetFiles, however if you look at the sourcecode for other Async operations, they're defined as follows:</p> <pre><code>module FileExtensions = let UnblockViaNewThread f = async { //let ctxt = System.Threading.SynchronizationContext.Current do! Async.SwitchToNewThread () let res = f() do! Async.SwitchToThreadPool () //do! Async.SwitchTo ctxt return res } type System.IO.File with static member AsyncOpenText(path) = UnblockViaNewThread (fun () -&gt; System.IO.File.OpenText(path)) static member AsyncAppendText(path) = UnblockViaNewThread (fun () -&gt; System.IO.File.AppendText(path)) static member AsyncOpenRead(path) = UnblockViaNewThread (fun () -&gt; System.IO.File.OpenRead(path)) static member AsyncOpenWrite(path) = UnblockViaNewThread (fun () -&gt; System.IO.File.OpenWrite(path)) static member AsyncOpen(path,mode,?access,?share) = let access = match access with Some v -&gt; v | None -&gt; System.IO.FileAccess.ReadWrite let share = match share with Some v -&gt; v | None -&gt; System.IO.FileShare.None UnblockViaNewThread (fun () -&gt; System.IO.File.Open(path,mode,access,share)) static member OpenTextAsync(path) = System.IO.File.AsyncOpenText(path) static member AppendTextAsync(path) = System.IO.File.AsyncAppendText(path) static member OpenReadAsync(path) = System.IO.File.AsyncOpenRead(path) static member OpenWriteAsync(path) = System.IO.File.AsyncOpenWrite(path) static member OpenAsync(path,mode,?access,?share) = System.IO.File.AsyncOpen(path, mode, ?access=access, ?share=share) </code></pre> <p>In other words, the Async file, streamreader, and WebClient operations are just wrappers around the syncronous operations, so you should be able to write your own wrapper around GetFiles/GetDirectories as follows:</p> <pre><code>module IOExtensions = type System.IO.Directory with static member AsyncGetFiles(directory) = async { return System.IO.Directory.GetFiles(directory) } static member AsyncGetDirectories(path) = async { return System.IO.Directory.GetDirectories(path) } </code></pre>
Kohana - where do you put AJAX scripts? <p>I am using <a href="http://kohanaphp.com/">Kohana</a> but this question applies to Rails, CI, or any other MVC web development framework. Where is the best place to stick one's server side AJAX scripts? </p> <p>I was <em>planning</em> on creating an Ajax_Controller and using a method/action per individual script.</p> <p>For example, a login form on the home page <strong><code>index.php/home</code></strong> would send an XMLHttpRequest to <strong><code>index.php/ajax/login</code></strong>, and the edit profile form <strong><code>index.php/profile/edit</code></strong> would send an XMLHttpRequest to <strong><code>index.php/ajax/editprofile</code></strong>. What's the best practice?</p>
<p>I tend to put my ajax actions in the same controller as the non-ajax actions for any given model.</p> <p>When I can, I try to use the same actions and only change the output type. Most tasks should have a non-ajax version anyway, so this tends to work quite well. Very handy for reducing logic duplication.</p>
Is it possible to deploy a Common Lisp (or other dialect) desktop application for several platforms? <p>I would like to develop a graphical application in Common Lisp or other Lisp dialect that could be deployed in Mac, Windows and Linux as a way of improving my knowledge of this language. Ideally:</p> <ol> <li>would compile the code</li> <li>would use a common graphical library</li> <li>wouldn't need installation of the runtime environment.</li> </ol> <p>I would like to make a little game or graphical app, and to be able to show it with a simple installation in a computer with any of these operating systems.</p> <p>Someone has experience with similar situations or could point me to best choices of graphical libraries and compilers, runtime environments, etc...</p> <p>Thanks!</p>
<p>I'm one of the developers of lispbuilder-sdl which is currently hosted on google code.</p> <p><img src="http://img10.imageshack.us/img10/7664/mandelbrot.jpg" alt="alt text" /></p> <p><a href="http://code.google.com/p/lispbuilder/">http://code.google.com/p/lispbuilder/</a></p> <p>This gives you a way of running common lisp programs on linux, windows and mac machines without modification. We use the SDL library and various extensions of it. </p> <p>A minimal program looks like this:</p> <pre><code>(sdl:with-init () (sdl:window 320 240) (sdl:draw-surface (load-image "lisp.bmp")) (sdl:with-events () (:quit-event () t) (:video-expose-event (sdl:update-display)))) </code></pre> <p>The wiki also explains how to build self contained exe's for various of the common lisp implementations.</p>
Why won't this Javascript Function Work? <p>I have a JavaScript function that is not working now that I put in a new one under it. Here is what is in the head of my document.</p> <pre><code> &lt;head&gt; &lt;link rel="stylesheet" href="9j3nz/style.css" type="text/css"&gt; &lt;script src="jquery.js"&gt;&lt;/script&gt; &lt;script src="processing.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode &gt; 31 &amp;&amp; (charCode &lt; 48 || charCode &gt; 57)) return false; return true; } &lt;/script&gt; &lt;script type="text/javascript"&gt; function stopRKey(evt) { var evt = (evt) ? evt : ((event) ? event : null); var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); if ((evt.keyCode == 13) &amp;&amp; (node.type=="text")) $("label#enter_error").show(); {return false;} } document.onkeypress = stopRKey; &lt;/script&gt; &lt;/head&gt; </code></pre> <p>Everything is working fine except the isnumberkey function that was previously working. Nothing has changed in my HTML. Any help is appreciated. Thanks!</p> <p>I am calling the isnumberkey function as follows:</p> <pre><code> onkeypress="return isNumberKey(event)" </code></pre> <p>What might be keeping this from working? It has only started acting up since I put in the Stop Enter Key function.</p> <p>EDIT:</p> <p>After removing the Stop Enter Key function the isnumberkey event works again. I think they are interfering with each other some how.</p>
<p>Seems like your stopRKey is always returning false which could be blocking your isNumberKey.</p> <p>Try re-arranging your parens.</p> <pre><code>if ((evt.keyCode == 13) &amp;&amp; (node.type=="text")) $("label#enter_error").show(); {return false;} </code></pre> <p>Should be</p> <pre><code>if ((evt.keyCode == 13) &amp;&amp; (node.type=="text")) { $("label#enter_error").show(); return false; } </code></pre> <p><strong>Update:</strong> There are two ways of using the if statement.</p> <p>You can call <code>if</code> with a single operation: eg.</p> <pre><code>if (true) alert('always true'); // or if (true) alert('always true'); </code></pre> <p>or you can call an <code>if</code> statement with a block of code</p> <pre><code>if (true) { alert('one alert'); alert('another alert'); } </code></pre> <p>Since your parens were out of order your code was only executing the <code>show()</code> if the user pressed enter and then continued processing the remaining code. So return false was always called.</p>
Where is the log file when I'm using svn+ssh? <p>Title is pretty much the question. I have a post-commit that has taken me ages to get permissions working correctly.</p> <p>I can run it manually and it works, however, when I actually make a commit (as the same user that I know works manually) nothing happens.</p> <p>Will anything be logged anywhere? Or can I set up pseudo-logging or something?</p>
<p>Did you try debugging the hook per the subversion directions? </p> <p><a href="http://subversion.tigris.org/faq.html#hook-debugging" rel="nofollow">Why aren't my repository hooks working?</a></p> <blockquote> <p>They're supposed to invoke external programs, but the invocations never seem to happen.</p> <p>Before Subversion calls a hook script, it removes all variables -- including $PATH on Unix, and %PATH% on Windows -- from the environment. Therefore, your script can only run another program if you spell out that program's absolute name.</p> <p>Debugging tips:</p> <p>If you're using Linux or Unix, try running the script "by hand", by following these steps:</p> <ol> <li>Use "su", "sudo", or something similar, to become the user who normally would run the script. This might be httpd or www-data, for example, if you're using Apache; it might be a user like svn if you're running svnserve and a special Subversion user exists. This will make clear any permissions problems that the script might have.</li> <li><p>Invoke the script with an empty environment by using the "env" program. Here's an example for the post-commit hook:</p> <pre><code> $ env - ./post-commit /var/lib/svn-repos 1234 </code></pre></li> </ol> <p>Note the first argument to "env" is a dash; that's what ensures the environment is empty. 3. Check your console for errors.</p> </blockquote>
SciFi-HiFi Keychain problem - SecKeychainItemRef undeclared error <p>I'm trying to use this class:</p> <p><a href="http://log.scifihifi.com/post/55837387/simple-iphone-keychain-code" rel="nofollow">http://log.scifihifi.com/post/55837387/simple-iphone-keychain-code</a></p> <p>to save data to the keychain on the iPhone. I've included the header and the .m file in my application and included the security framework, however I'm still getting these undeclared errors.</p> <p>I can't seem to find any tutorials or help file for setting up this class within a project, so I'm led to believe that it's not that difficult. Just causing me problems.</p> <p>I'm running the 3.0 sdk, though I don't think that will affect things much.</p> <p>Cheers in advance!</p>
<p>I believe the full iPhone Keychain API is now available in the simulator (as of 3.0)... just make sure any #ifdefs that refer to <pre>TARGET_ IPHONE_SIMULATOR</pre> are disabled, and you should be fine.</p>
Updating ModelState with model object <p>The problem: How to update ModelState in posting+validation scenario.</p> <p>I've got a simple form:</p> <pre><code>&lt;%= Html.ValidationSummary() %&gt; &lt;% using(Html.BeginForm())%&gt; &lt;%{ %&gt; &lt;%=Html.TextBox("m.Value") %&gt; &lt;input type="submit" /&gt; &lt;%} %&gt; </code></pre> <p>When user submits I want to validate input and in some circumstances I want to fix the error for user, letting him know that he made an error that is already fixed:</p> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(M m) { if (m.Value != "a") { ModelState.AddModelError("m.Value", "should be \"a\""); m.Value = "a"; return View(m); } return View("About"); } </code></pre> <p>Well the problem is, MVC will simply ignore the model passed to the view and will re-render whatever the user typed -- and not my value ("a"). This happens, because the TextBox renderer checkes if there is a ModelState and if it's not null - ModelState's value is used. That value is of course the one user typed before posting.</p> <p>Since I can't change the behaviour of TextBox renderer the only solution I found would be to update the ModelState by myself. The quick'n'dirty way is to (ab)use the DefaultModelBinder and override the method that assigns the values from forms to model by simply changing the assignment direction ;). Using DefaultModelBinder I don't have to parse the ids. The following code (based on original implementation of DefaultModelBinder) is my solution to this:</p> <pre><code>/// &lt;summary&gt; /// Updates ModelState using values from &lt;paramref name="order"/&gt; /// &lt;/summary&gt; /// &lt;param name="order"&gt;Source&lt;/param&gt; /// &lt;param name="prefix"&gt;Prefix used by Binder. Argument name in Action (if not explicitly specified).&lt;/param&gt; protected void UpdateModelState(object model, string prefix) { new ReversedBinder().BindModel(this.ControllerContext, new ModelBindingContext() { Model = model, ModelName = prefix, ModelState = ModelState, ModelType = model.GetType(), ValueProvider = ValueProvider }); } private class ReversedBinder : DefaultModelBinder { protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor) { string prefix = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name); object val = typeof(Controller) .Assembly.GetType("System.Web.Mvc.DictionaryHelpers") .GetMethod("DoesAnyKeyHavePrefix") .MakeGenericMethod(typeof(ValueProviderResult)) .Invoke(null, new object[] { bindingContext.ValueProvider, prefix }); bool res = (bool)val; if (res) { IModelBinder binder = new ReversedBinder();//this.Binders.GetBinder(propertyDescriptor.PropertyType); object obj2 = propertyDescriptor.GetValue(bindingContext.Model); ModelBindingContext context2 = new ModelBindingContext(); context2.Model = obj2; context2.ModelName = prefix; context2.ModelState = bindingContext.ModelState; context2.ModelType = propertyDescriptor.PropertyType; context2.ValueProvider = bindingContext.ValueProvider; ModelBindingContext context = context2; object obj3 = binder.BindModel(controllerContext, context); if (bindingContext.ModelState.Keys.Contains&lt;string&gt;(prefix)) { var prefixKey = bindingContext.ModelState.Keys.First&lt;string&gt;(x =&gt; x == prefix); bindingContext.ModelState[prefixKey].Value = new ValueProviderResult(obj2, obj2.ToString(), bindingContext.ModelState[prefixKey].Value.Culture); } } } } </code></pre> <p>So the question remains: am I doing something extremely uncommon or am I missing something? If the former, then how could I implement such functionality in a better way (using existing MVC infrastructure)?</p>
<p>I know this post is fairly old but it's a problem I've had before and I just thought of a simple solution that I like - just clear the ModelState after you've got the posted values.</p> <pre><code>UpdateModel(viewModel); ModelState.Clear(); viewModel.SomeProperty = "a new value"; return View(viewModel); </code></pre> <p>and the view has to use the (possibly modified) view model object rather than the ModelState.</p> <p>Maybe this is really obvious. It seems so in hindsight!</p>
Finding duplicate iPhone apps <p>How do I most efficiently determine whether my idea for an iPhone app has been done already? iTunes's search isn't great for this purpose, and the websites I've seen covering iPhone apps are not comprehensive in their coverage. (Perhaps I just haven't found THE website that does it.) I'm not yet signed up in the iPhone developer program; perhaps this search tool is in that walled garden.</p>
<p>The following blog post</p> <p><a href="http://theappleblog.com/2008/12/26/one-juicer-managing-the-app-store-beast/" rel="nofollow">One Juicer: Managing the App Store Beast</a></p> <p>has some hints how you could achieve this. For example by using AppShopper's RSS feed. Maybe you're able to scrape some data off there.</p>
Eclipse RCP: Communication between elements created in different ViewPart? <p>what's the best way to make communications between page widgets residing on differents ViewPart?</p> <p>via listener or via shared object instances like "getViewSite().getPart()/getPage()" ? what pro/contra and what's the best strategy for You?</p> <p>Thanks, regards</p>
<p>The answer depends on the nature of the changes. Why is one ViewPart causing changes in another ViewPart?</p> <p>For example, if the change is because one ViewPart is changing the model data and the other ViewPart is displaying the same data then you should be going through the model. One ViewPart updates the model and the other is listening to the model for changes. This is basic MVC.</p> <p>If, on the other hand, the change is caused because of a selection (for example, a change in the selection in the navigation view causes another view to display the contents of that selection) then you should be using the global selection handler.</p> <p>The question needs to be updated to be more specific to get the correct answer.</p>
Purity of methods in C#, evaulation and custom compiler? <p>Have you ever been frustrated by Visual Studio not re-evaluating certain watch expressions when stepping through code with the debugger?</p> <p>I have and does anyone here care about pure methods? Methods with no side-effects? There's so many great things about C# that I love, but I can't write pure functions, that is, static methods with no side-effects.</p> <p>What if you were to build your own C# compiler where you could write something like this.</p> <pre><code>function int func(readonly SomeRefType a, int x, int y) { return /*...*/; } </code></pre> <p>Not only is the above a free function, alas, I don't call it a method, the function is assured to not have any side-effects. The C# keyword <code>readonly</code> could here be used to indicate just that, and provide a contract for pure functions. These kind of functions can always be evulated, without causing side effects. This being a way for Visual Studio to always evaulate my functions in the watch, despite the faulty assumpation that all method calls and user operators have side effects. A method where all the parameters are copy by value can never have side effects, yet, Visual Studio fails to recognize this.</p> <p>I love C++ for what you can do at compile-time and I miss these things in C#, I think C# is dumbing down on the user a bit and basically not allowing certain expressiveness, hurting programmers. Many things which actually relate what you can do at compile time, I'd like to actually see more meta programs which are programs run by the compiler to compiler your original program.</p> <p>e.g. While C# has booleans and don't allow things like <code>if (var a = obj as MyRefType)</code>, it doesn't generate the approriate code. I did some digging around and noticed how C# fails to generate approriate IL for branchless conditionals, for example <code>x &gt; y ? 1 : 0</code>, there's an IL instruction for just that which the C# compiler dosen't use.</p> <p>Would you want, or be instrested in an open-source .NET compiler? Which looks like C# but is something entierly different, more expressive, and more flexible, and totally whaack, in terms what you can do with it?</p>
<p>Not really. If I want different language options I've already got:</p> <ul> <li>F# for a functional bent</li> <li>Boo for a DSL helper with custom compilation stages</li> </ul> <p>The chances of a "design by committee" (or even "design by single amateur language designer") language ending up as well thought out as C# are pretty slim, IMO.</p> <p>Would it be nice to be able to express a few more things? Absolutely.</p> <p>Is it rather handy having hundreds of thousands of people who understand the same language, built-in Visual Studio integration from the people who really know it, etc? Absolutely!</p> <p>For me, "looks like C# but is something entirely different" sounds like a problem, not a solution.</p>
Linq - How to aggregate the results of another query <p>I want to take the results of a where clause on a list and then take that result set and create just one new type that has all its fields constructed from aggregates of the original query. So given the basic example below, is there anyway to combine the 2 linq statements into one? If the original where has no rows then it should return null. Thanks!</p> <pre><code> class Foo { public int A { get; set; } public int B { get; set; } } List&lt;Foo&gt; lst = GetFooList(); var q = (from f in lst where f.A &gt; 3 select f).ToList(); if (q.Count != 0) { var qq = new { MinA = q.Min(l =&gt; l.A), MaxB = q.Max(h =&gt; h.B), }; // now do something with qq } </code></pre> <p>Update: For my situation, the original set has lots of items but after the where clause the result set is very small. Enumerating over the second set several times should not be a problem. Also I need to use first and last on the set to get a value from those records. The group by answer will work best for me. The aggregate way is very interesting and I think have another use for that.</p>
<p>This solution iterates the list only once with <code>Aggregate()</code>, but for empty lists it will return the seed value. By the way, the seed values are <code>int.MaxValue</code> and <code>int.MinValue</code> because <code>Math.Min(int.MaxValue, C)</code> will always return C and likewise <code>Math.Max(int.MinValue, C)</code> will always return C.</p> <pre><code>var b = lst.Where(f =&gt; f.A &gt; 3) .Aggregate( // seed, initial values new { MinA = int.MaxValue, MaxB = int.MinValue }, // accumulator function (a,f) =&gt; new { MinA = Math.Min(a.MinA , f.A), MaxB = Math.Max(a.MaxB , f.B) }); </code></pre>
Sending values with jQuery's Get function <p>I am currently coding something to check my database to check for duplicate errors. It is a form and I am having the following function check for duplicate values using jQuery.get. </p> <pre><code>function makeAjaxRequest() { $("label#bad_error").hide(); $("label#good_error").hide(); $("label#checkingdb_error").show(); $.get(url,{sheetnum: '$("input#sheetnum").val()'},verifyDb); } function verifyDb(response) { if (response==1) { $("label#checkingdb_error").hide(); $("label#bad_error").show(); } else { $("label#checkingdb_error").hide(); $("label#good_error").show(); } } </code></pre> <p>I am having it do this onBlur of a text field. My php file is as follows:</p> <pre><code>&lt;? $sheetnum = $_GET['sheetnum']; if($sheetnum == "1234"){ echo "1"; } ?&gt; </code></pre> <p>I used "1234" instead of the mysql string for now, just to test that the javascript side of it is working. </p> <p>When I type 1234 in the text box it returns that there are no errors (the good_error label). Am I putting the value wrong in the .get string? Please help.</p>
<p>I believe</p> <pre><code>$.get(url,{sheetnum: '$("input#sheetnum").val()'},verifyDb); </code></pre> <p>should be</p> <pre><code>$.get(url,{sheetnum: $("input#sheetnum").val()},verifyDb); </code></pre>
open source dev environment for C++: what's better? <p>I want to do some coding in my spare time, but the thing is, I don't want to spend the money on this.</p> <p>Would the following set of development tools be The Right Thing, or is there something I'm forgetting?</p> <ul> <li>Eclipse for C++</li> <li>SVN for source control</li> <li>Qt for UI development (since it's C++, and I believe it's now opened by Nokia)</li> <li>hudson for continuous integration</li> </ul> <p>I'd like to write a little image processing application that can run on any platform, but the main platform at the moment will be Windows with a possible movement to the Mac-- hence all the cross-platform tools.</p> <p>Is there anything really obvious I'm forgetting? Like something like fxcop for style checking in C++?</p> <p>If I use any libraries, I'd like to avoid GPL libraries; if things go south with my current employer, I'll want to monetize this.</p>
<p>Microsoft Visual C++ Express is free and easily the best IDE for Windows. Furthermore, you can use it to work on cross-platform code - it more depends on writing standards-adhering code and using portable libraries.</p> <p>If you want to write cross-platform code, I recommend a cross-platform build tool. I use CMake, which generates Visual Studio solutions on Windows, but there are others too, such as SCons. </p> <p>As for libraries, it depends on what exactly you need to do. Qt is an excellent GUI library. libpng/libjpeg and others are good for loading/saving images at a low level, but there are probably other higher-level image libraries as well.</p> <p><strong>[edit]</strong> A response to the comment about MSVC and Qt: A quick search brings up Trolltech's Qt Visual Studio Integration page: <a href="http://doc.trolltech.com/vs-integration-1.4/index.html" rel="nofollow">Qt Visual Studio .NET Integration</a> A comment points out that this is actually not free (a free addon is available at <a href="http://www.qtsoftware.com/downloads/visual-studio-add-in" rel="nofollow">this link</a>, but this runs Qt designer outside of Visual Studio. Also, the Express version of Visual Studio does not support plugins.</p> <p>For coding specifically in Qt there is another new IDE created by Qt: <a href="http://www.qtsoftware.com/products/developer-tools" rel="nofollow">Qt Creator</a>. I've heard good things about it, and it is also portable across Windows, Linux, and Mac. </p>
How do I set Session name with Cherrypy? <p>In PHP I would do it like this:</p> <pre><code>session_name("special_session_name"); </code></pre> <p>So how do I do it with Cherrypy? Just need to find exact equivalent for it. PHP manual page: <a href="http://fi2.php.net/session_name" rel="nofollow">http://fi2.php.net/session_name</a></p>
<p>Reading the docs and the source most probably you have to set "tools.sessions.name" in your config file:</p> <pre><code>cherrypy.config.update({'tools.sessions.name': "special_session_name"}) </code></pre>
C#: Streaming an Audio file from a Server to a Client <p>I am currently writing an application that will allow a user to install some form of an application (maybe a Windows Service) that will open a port on it's PC and given a particular destination on the hard disk, will then be able to stream mp3 files.</p> <p>I will then have another application that will connect to the server (being the user's pc) and be able to browse the hosted data by connecting to that PC (remotely ofcourse) given the port, and <strong>stream mp3 files from the server to the application</strong></p> <p><hr /></p> <p>I have found some tutorials online but most of them are about File Servers in C# and they download allow you to download a whole file. What I want is to stream an mp3 file so that it starts playing when a certain number of bytes are download (ie, whilst it is being buffered)</p> <p><hr /></p> <p>How do I go about in accomplishing such a task? What I need to know specifically is how to write this application (that I will turn into a Windows Service later on) that will listen on a specified port a stream files, so that I can then access the files by something of the sort: <code>http://&lt;serverip&gt;:65000/acdc/wholelottarosie.mp3</code> and hopefully be able to stream that file in a WPF <code>MediaPlayer</code>.</p> <p><hr /></p> <p><strong>[Update]</strong></p> <p>I was following <a href="http://www.dotnetspider.com/resources/4741-Building-Simple-File-download-server-using-C.aspx">this tutorial</a> about building a file server and sending the file from the server to the client. Is what I have to do something of the sort?</p> <p><strong>[Update]</strong></p> <p>Currently reading this post: <a href="http://stackoverflow.com/questions/184683/play-audio-from-a-stream-using-c">Play Audio from a Stream using C#</a> and I think it looks very promising as to how I can play streamed files; but I still don't know how I can actually stream the files from the server.</p>
<p>There is no effective difference between streaming and downloading. They're the same thing. Any difference is purely semantic.</p> <p>If you wanted to, you could "download" an MP3 from any web server and start playing it while you were downloading it. It just requires that you buffer some of the data and start sending it to your decoding and playback routines right away.</p> <p>Similarly, even so called "streaming" servers can be downloaded. You just have to save the bytes as they are being sent across the wire to a file. </p> <p>"Streaming" applications are just apps that are not designed to save the files to disk.</p> <p>EDIT:</p> <p>There is an exception. Two really:</p> <p>First, if you are streaming "live" audio, such as radio or other types where you don't need 100% reliability, then they stream using UDP. This can still be saved if you want, but it's more packet oriented than stream oriented.</p> <p>The second is when encryption is used, in which case you can still probably save the file, but it would be useless without the encryption algorithm and keys.</p>
Correcting a known bias in collected data <p>Ok, so here is a problem analogous to my problem (I'll elaborate on the real problem below, but I think this analogy will be easier to understand).</p> <p>I have a strange two-sided coin that only comes up heads (randomly) 1 in every 1,001 tosses (the remainder being tails). In other words, for every 1,000 tails I see, there will be 1 heads.</p> <p>I have a peculiar disease where I only notice 1 in every 1,000 tails I see, but I notice every heads, and so it appears to me that the rate of noticing a heads or tails is 0.5. Of course, I'm aware of this disease and its effect so I can compensate for it.</p> <p>Someone now gives me a new coin, and I noticed that the rate of noticing heads is now 0.6. Given that my disease hasn't changed (I still only notice 1 in every 1,000 tails), how do I calculate the actual ratio of heads to tails that this new coin produces?</p> <hr> <p>Ok, so what is the real problem? Well, I have a bunch of data consisting of input, and outputs which are 1s and 0s. I want to teach a supervised machine learning algorithm to predict the expected output (a float between 0 and 1) given an input. The problem is that the 1s are very rare, and this screws up the internal math because it becomes very susceptible to rounding errors - even with high-precision floating point math.</p> <p>So, I normalize the data by randomly omitting most of the 0 training samples so that it appears that there is a roughly equal ratio of 1s and 0s. Of course, this means that now the machine learning algorithm's output is no-longer predicting a probability, ie. instead of predicting 0.001 as it should, it would now predict 0.5.</p> <p>I need a way to convert the output of the machine learning algorithm back to a probability within the original training set.</p> <p><strong>Author's Note (2015-10-07):</strong> I later discovered that this technique is commonly known as "downsampling"</p>
<p>You are calculating the following</p> <pre><code>calculatedRatio = heads / (heads + tails / 1000) </code></pre> <p>and you need</p> <pre><code>realRatio = heads / (heads + tails) </code></pre> <p>Solving both equations for tails yields the following equations.</p> <pre><code>tails = 1000 / calculatedRatio - 1000 tails = 1 / realRatio - 1 </code></pre> <p>Combining both yields the following.</p> <pre><code>1000 / calculateRatio - 1000 = 1 / realRatio - 1 </code></pre> <p>And finally solving for realRatio.</p> <pre><code>realRatio = 1 / (1000 / calculatedRatio - 999) </code></pre> <p>Seems to be correct. calculatedRatio 0.5 yields realRatio 1/1001, 0.6 yields 3 / 2003.</p>
submit php variables with javascript (link?) <p>I'm creating a browser based game and at the moment I'm designing the script that updates the position of my character when he/she clicks on a different part of the map.</p> <p>I am using a bit of ajax to do this which send a request to a php file called position_update.php. But for it to work I need to send two values along with it so it knows what the new position is, how do I do this? Below is my link that send the request to php file.</p> <pre><code>&lt;a onClick="positionUpdate();"&gt;&lt;img src="images/transparent.gif" border="0" /&gt;&lt;/a&gt; </code></pre> <p>As a note, I'm using the php $_GET super global to retrieve the values when they're sent.</p> <p>Thanks, Stanni</p>
<p>You need to hit the URL:</p> <pre><code>position_update.php?var1=val1&amp;var2=val2 </code></pre> <p>PHP will parse the get string into $_GET</p>
IE Input Select Box <p>I'm looking for the easiest solution to fixing a problem I have in Internet Explorer (6,7 &amp; 8), be it CSS or using jQuery. I have a SELECT Input with a defined width (because of where it sits in the layout). Because of the defined width select is cut off from showing their full values, unlike in Firefox &amp; Safari where they are automatically resized to show the whole length of the value..</p> <p>Surely this is a common problem? Any ideas?</p> <p>example code:</p> <pre><code>&lt;select id="Grouping_662066" class="productSelectInput" name="AddToCart_Grouping" onchange="DrawProduct(36331,662066,this.value,'',true);"&gt; &lt;/select&gt; </code></pre> <p>I'm using a CMS system the class '<code>productSelectInput</code>' is the only identifier what will be consistand across the website. The <code>ID</code>, <code>name</code> and <code>onchange</code> properties will change.</p>
<p><a href="http://css-tricks.com/select-cuts-off-options-in-ie-fix/" rel="nofollow">Here</a> is information and a solution using jQuery.</p>
PHP immediate echo <p>I have quite a long data mining script, and in parts of it I echo some information to the page (during a foreach loop, actually.)</p> <p>However I am noticing that the information is being sent to the browse not immediately as I had hoped, but in 'segments'.</p> <p>Is there some function I can use after my echo to send all the data to the browser immediately?</p> <p>Thanks.</p>
<p>You probably want <code>flush()</code>. However, PHP may be using output buffering. There are a few ways that this can change things, but in a nutshell, you can <code>flush()</code>, then <code>ob_flush()</code>.</p>
Why doesn't this for-each loop work? <p>In this code, why isn't my array initialised as I want it to? Is the for-each loop not designed to do that, or am I just not using it correctly?</p> <pre><code> int[] array = new int[5]; //initialise array -&gt; Doesn't work! Array still full of 0's for(int i : array) i = 24; </code></pre>
<p>The for-each loop will not work for this case. You cannot use a for-each loop to initialize an array. Your code:</p> <pre><code>int[] array = new int[5]; for (int i : array) { i = 24; } </code></pre> <p>will translate to something like the following:</p> <pre><code>int[] array = new int[5]; for (int j = 0; j &lt; array.length; j++) { int i = array[j]; i = 24; } </code></pre> <p>If this were an array of objects, it would still fail. Basically, for-each assigns each entry in the collection or array, in turn, to the variable you provide, which you can then work with. The variable is <em>not</em> equivalent to an array reference. It is just a variable.</p> <p>For-each cannot be used to initialize <em>any</em> array or Collection, because it loops over the current contents of the array or Collection, giving you each <strong>value</strong> one at a time. The variable in a for-each is <em>not</em> a proxy for an array or Collection reference. The compiler does not replace your "<code>i</code>" (from "<code>int i</code>") with "<code>array[index]</code>".</p> <p>If you have an array of Date, for example, and try this, the code:</p> <pre><code>Date[] array = new Date[5]; for (Date d : array) { d = new Date(); } </code></pre> <p>would be translated to something like this:</p> <pre><code>Date[] array = new Date[5]; for (int i = 0; i &lt; array.length; i++) { Date d = array[i]; d = new Date(); } </code></pre> <p>which as you can see will not initialize the array. You will end up with an array containing all nulls.</p> <p>NOTE: I took the code above, compiled it into a <code>.class</code> file, and then used <a href="http://www.varaneckas.com/jad">jad</a> to decompile it. This process gives me the following code, generated by the Sun Java compiler (1.6) from the code above:</p> <pre><code>int array[] = new int[5]; int ai[]; int k = (ai = array).length; for(int j = 0; j &lt; k; j++) { int i = ai[j]; i = 5; } </code></pre>
Using value from related table in LINQ where clause <p>I was expecting the following LINQ query to retrieve all contacts with the specified phone number but instead it returns all contacts that don't have a phone number at all.</p> <pre><code>var query = from contact in dc.Contacts where contact.Phones.All(phone =&gt; phone.PhoneNumber == "5558675309") select contact; </code></pre> <p>What am I doing wrong here?</p>
<p>I should have been using the Any extension method, not All.</p> <p>The following code works just fine:</p> <pre><code>var query = from contact in dc.Contacts where contact.Phones.Any(p =&gt; p.PhoneNumber == "5558675309") select contact; </code></pre>
XML serialize annotations <p>I have a situation where I have an xml file that I don't want to modify. The AddAnnotation function in XElement class provides an option to add memory-only data which is not serialized and not part of the XML. </p> <p>I want to be able to save these annotations (for example: to another xml file) and then to deserialize both the xml and the annotations in order to get the same object I had. </p> <p>I don't want to change the original xml and that's the reason that I use annotations.</p> <p>To summarize, I want to be able to add custom data to an xml file. This data won't be a part of the xml when I serialize it or it will be a part of the xml but I would be able to retrieve the original xml easily.</p> <p>Do you have any recommendation how I can do such a thing? </p> <p><strong>Edit:</strong> Should I use xml processing instructions? Are processing instructions intended for this kind of usage?</p>
<p>It sounds to me like the simplest approach would be to use regular nodes, but in a different xml namespace - i.e.</p> <pre><code>&lt;foo standardAttrubute="abc" myData:customAttribute="def"&gt; &lt;standardElement&gt;ghi&lt;/standardElement &gt; &lt;myData:customElement&gt;jkl&lt;/myData:customElement&gt; &lt;/foo&gt; </code></pre> <p>(where <code>myData</code> is an <code>xmlns</code> alias for the namespace-uri)</p> <p>In many cases, readers are only checking for data in <em>their</em> namespace (or the default/blank namespace) - values in custom namespaces are generally skipped.</p> <p>To get pack the original xml, one simple approach would be to run it through an xslt that only respects the default/original namespace.</p> <p><hr /></p> <pre><code>XNamespace myData = XNamespace.Get("http://mycustomdata/"); XElement el = new XElement("foo", new XAttribute(XNamespace.Xmlns + "myData", myData.NamespaceName), new XAttribute("standardAttribute", "abc"), new XAttribute(myData + "customAttribute", "def"), new XElement("standardElement", "ghi"), new XElement(myData + "customAttribute", "jkl")); string s = el.ToString(); </code></pre> <p>To remove such data from an <code>XElement</code>, perhaps:</p> <pre><code> static void Strip(XElement el, XNamespace ns) { List&lt;XElement&gt; remove = new List&lt;XElement&gt;(); foreach (XElement child in el.Elements()) { if (child.Name.Namespace == ns) { remove.Add(child); } else { Strip(child, ns); } } remove.ForEach(child =&gt; child.Remove()); foreach (XAttribute child in (from a in el.Attributes() where a.Name.Namespace == ns select a).ToList()) { child.Remove(); } } </code></pre>
Visual C++ error C2143: syntax error: missing ')' before 'constant' <p>I'm getting an error in Visual C++ that is giving me a really hard time.</p> <p>The error is error c2143 reading: syntax error: missing ')' before 'constant'</p> <p>My code line is:</p> <pre><code>coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) 2 * depth); </code></pre> <p>I have #include at the beginning of the file which should define the floor(double) function.</p> <p>a bit more explanation of the variables.</p> <p>double depth is a member variable of the class which this line can be found in.<br /> int i is an incrementing index value.<br /> double t is an incrementing value.</p> <p>What they do is really unimportant, but I wanted to clarify that all three are already defined as variables of basic types.</p> <p>I've gone through and verified that all the parentheses match up. I'm kind of at a loss as to what 'constant' the compiler is referring to. Any ideas?</p>
<p>I'm not quite sure if this is the same error that the compiler is giving you, but you have to put a '*' sign in front of the second '2' so that this:</p> <pre><code>coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) 2 * depth); </code></pre> <p>Becomes this:</p> <pre><code>coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) * 2 * depth); </code></pre>
Internal and external interfaces and collections <p>What would be the best way to implement the following?</p> <p>I have a collection of objects that implement an interface, internally I want to be able to expose set and get on the properties and externally only get.</p> <p>Here's an example of the sort of thing I want... That does't compile.</p> <pre><code>public interface ITable { string Name { get; } } internal interface IInternalTable { string Name { get; set; } } internal class Table : ITable, IInternalTable { public string Name { get; set; } public string ITable.Name { get { return Name; } } } public class Database { private List&lt;IInternalTable&gt; tables; public List&lt;ITable&gt; { get { return this.tables; } } } </code></pre>
<h3>Use this:</h3> <pre><code>public interface ITable { string Name { get; } } public class Table : ITable { public string Name { get; internal set; } } public class Database { public List&lt;ITable&gt; Tables { get; private set; } } </code></pre> <p><strong>Note</strong>: The accessibility modifier used on a get or set accessor can only restrict visibility not increase it.</p>
Where does <_o3a_p> come from on a webpage? <p>i got a question from a webdeveloper in my company who got it from a client: when inserting (russian) text into a webpage <strong>&lt;_o3a_p></strong> tags appear on the website.</p> <p>I have (ofcourse) tried to google it but i only stumble upon websites that have these tags in them as well. No real good context for the how and why in other words.</p> <p>My first idea was that the client must have copy/paste'ed it from an editor into our editor and thus copying the text. There is however no way we can find out what the client pasted from.</p> <p>Anyone got any experience with this?</p>
<p>I can't find the cause, but the Google results show it happening on non-Russian pages too.</p> <p>I'd suggest therefore that internationalisation is <em>not</em> the cause, but that it may be something special about the editor used.</p> <p>Also, on each page I looked at these were written as HTML tags, but were rendered as text by Firefox and Safari. Maybe a naïve editor is using these as tags for its own use, not realising that browsers will show the tag instead of ignoring them like normal unknown tags.</p>
I cannot grok MVC, what it is, and what it is not? <p>I cannot grok what MVC is, what mindset or programming model should I acquire so MVC stuff can instantly "lightbulb" on my head? If not instantly, what simple programs/projects should I try to do first so I can apply the neat things MVC brings to programming.</p> <p>OOP is intuitive and easier, object is all around us, and the benefits of code reuse using OOP-paradigm instantly click to anyone. You can probably talk to anybody about OOP in a few minutes and lecture some examples and they would get it. While OOP somehow raise the intuitiveness aspect of programming, MVC seems to do the opposite. I'm getting negative thoughts that some future employers(or even clients) would look down upon me for not using MVC technology.</p> <p>Though I probably get the <a href="http://www.codinghorror.com/blog/archives/001112.html" rel="nofollow">skinnable</a> aspect of MVC, but when I try to apply it to my own project, I don't know where to start. </p> <p>And also some programmers even have diverging views on how to accomplish MVC properly. </p> <p>Take this for instance from Jeff's post about MVC:</p> <blockquote> <p>The view is simply how you lay the data out, how it is displayed. If you want a subset of some data, for example, my opinion is that is a responsibility of the model.</p> </blockquote> <p>So maybe some programmers use MVC, but they somehow inadvertently use the View or the Controller to extract a subset of data.</p> <p>Why we can't have a definitive definition of what and how to accomplish MVC properly?</p> <p>And also, when I search for MVC .NET programs, most of it applies to web programs, not desktop apps, this intrigue me further. My guess is, this is most advantageous to web apps, there's not much problem about intermixed view(html) and controller(program code) in desktop apps.</p>
<p>I like the way Martin Fowler puts it :)</p> <p><a href="http://martinfowler.com/eaaCatalog/modelViewController.html" rel="nofollow">http://martinfowler.com/eaaCatalog/modelViewController.html</a></p> <p>.. and from <a href="http://martinfowler.com/eaaDev/uiArchs.html" rel="nofollow">http://martinfowler.com/eaaDev/uiArchs.html</a> :</p> <blockquote> <p>Take Model-View-Controller as an example. It's often referred to as a pattern, but I don't find it terribly useful to think of it as a pattern because it contains quite a few different ideas. Different people reading about MVC in different places take different ideas from it and describe these as 'MVC'. If this doesn't cause enough confusion you then get the effect of misunderstandings of MVC that develop through a system of Chinese whispers.</p> </blockquote>
Better hashing than SHA1 <p>I'm working on an application and I need to store the users password, so I'm thinking I'll store it in the current-user class of the registry, but I also want to hash it for the obvious reason, and I've seen news items that state that SHA1 has been cracked, is there a better (uncracked) hashing algorithm available in the "standard" system or .net?</p>
<p>SHA1 is not <a href="http://en.wikipedia.org/wiki/Encryption" rel="nofollow">encryption</a>, it's a <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function" rel="nofollow">cryptographic hash function</a>. And yes it has been broken, which means it's possible to generate collisions faster than a brute force method. The SHA2 family has not been broken.</p> <p>But I would advise to use a custom seed per entry so that a <a href="http://en.wikipedia.org/wiki/Rainbow_table" rel="nofollow">rainbow table</a> could not be used for trying out passwords. If you're using the SQL Membership provider the <a href="http://msdn.microsoft.com/en-us/library/system.web.security.membershippasswordformat.aspx" rel="nofollow">password format "Hashed"</a> already uses a different seed for each user.</p> <p>More information about seeding your hash can be found in the article <a href="http://chargen.matasano.com/chargen/2007/9/7/enough-with-the-rainbow-tables-what-you-need-to-know-about-secure-password-schemes.html" rel="nofollow">What You Need To Know About Secure Password Schemes</a> by Thomas Ptacek.</p>
Pinning a delegate within a struct before passing to unmanaged code <p>I'm trying to use an unmanaged C dll for loading image data into a C# application. The library has a fairly simple interface where you pass in a struct that contains three callbacks, one to receive the size of the image, one that receives each row of the pixels and finally one called when the load is completed. Like this (C# managed definition):</p> <pre><code>[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct st_ImageProtocol { public st_ImageProtocol_done Done; public st_ImageProtocol_setSize SetSize; public st_ImageProtocol_sendLine SendLine; } </code></pre> <p>The types starting st_ImageProtocol are delgates:</p> <pre><code>public delegate int st_ImageProtocol_sendLine(System.IntPtr localData, int rowNumber, System.IntPtr pixelData); </code></pre> <p>With the test file that I'm using the SetSize should get called once, then the SendLine will get called 200 times (once for each row of pixels in the image), finally the Done callback gets triggered. What actually happens is that the SendLine is called 19 times and then a AccessViolationException is thrown claiming that the library tried to access protected memory.</p> <p>I have access to the code of the C library (though I can't change the functionality) and during the loop where it calls the SendLine method it does not allocate or free any new memory, so my assumption is that the delegate itself is the issue and I need to pin it before I pass it in (I have no code inside the delegate itself currently, besides a counter to see how often it gets called, so I doubt I'm breaking anything on the managed side). The problem is that I don't know how to do this; the method I've been using to declare the structs in unmanaged space doesn't work with delegates (Marshal.AllocHGlobal()) and I can't find any other suitable method. The delegates themselves are static fields in the Program class so they shouldn't be being garbage collected, but I guess the runtime could be moving them.</p> <p><a href="http://blogs.msdn.com/cbrumme/archive/2003/05/06/51385.aspx" rel="nofollow">This blog entry by Chris Brumme</a> says that delegates don't need to be pinned before being passed into unmanaged code:</p> <blockquote> <p>Clearly the unmanaged function pointer must refer to a fixed address. It would be a disaster if the GC were relocating that! This leads many applications to create a pinning handle for the delegate. This is completely unnecessary. The unmanaged function pointer actually refers to a native code stub that we dynamically generate to perform the transition &amp; marshaling. This stub exists in fixed memory outside of the GC heap.</p> </blockquote> <p>But I don't know if this holds true when the delegate is part of a struct. It does imply that it is possible to manually pin them though, and I'm interested in how to do this or any better suggestions as to why a loop would run 19 times then suddenly fail.</p> <p>Thanks.</p> <p><hr /></p> <p>Edited to answer Johan's questions...</p> <p>The code that allocates the struct is as follows:</p> <pre><code>_sendLineFunc = new st_ImageProtocol_sendLine(protocolSendLineStub); _imageProtocol = new st_ImageProtocol() { //Set some other properties... SendLine = _sendLineFunc }; int protocolSize = Marshal.SizeOf(_imageProtocol); _imageProtocolPtr = Marshal.AllocHGlobal(protocolSize); Marshal.StructureToPtr(_imageProtocol, _imageProtocolPtr, true); </code></pre> <p>Where the _sendLineFunc and the _imageProtocol variables are both static fields of the Program class. If I understand the internals of this correctly, that means that I'm passing an unmanaged pointer to a <em>copy</em> of the _imageProtocol variable into the C library, but that copy contains a reference to the static _sendLineFunc. This should mean that the copy isn't touched by the GC - since it is unmanaged - and the delegate won't be collected since it is still in scope (static).</p> <p>The struct actually gets passed to the library as a return value from another callback, but as a pointer:</p> <pre><code>private static IntPtr beginCallback(IntPtr localData, en_ImageType imageType) { return _imageProtocolPtr; } </code></pre> <p>Basically there is another struct type that holds the image filename and the function pointer to this callback, the library figures out what type of image is stored in the file and uses this callback to request the correct protocol struct for the given type. My filename struct is declared and managed in the same way as the protocol one above, so probably contains the same mistakes, but since this delegate is only called once and called quickly I haven't had any problems with it yet.</p> <p><hr /></p> <p>Edited to update</p> <p>Thanks to everybody for their responses, but after spending another couple of days on the problem and making no progress I decided to shelve it. In case anyone is interested I was attempting write a tool for users of the Lightwave 3D rendering application and a nice feature would have been the ability to view all the different image formats that Lightwave supports (some of which are fairly exotic). I thought that the best way to do this would be to write a C# wrapper for the plugin architecture that Lightwave uses for image manipulation so I could use their code to actually load the files. Unfortunately after trying a number of the plugins against my solution I had a variety of errors that I couldn't understand or fix and my guess is that Lightwave doesn't call the methods on the plugins in a standard way, probably to improve the security of running external code (wild stab in the dark, I admit). For the time being I'm going to drop the image feature and if I do decide to reinstate it I'll approach it in a different way.</p> <p>Thanks again, I learnt a lot through this process even though I didn't get the result I wanted. </p>
<p>I had a similar problem when registering a callback delegate (it would be called, then poof!). My problem was that the object with the method being delegated was getting GC'ed. I created the object in a more global place so as to keep it from being GC'ed.</p> <p>If something like that doesn't work, here are some other things to look at:</p> <p>As additional info, take a look at <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.getfunctionpointerfordelegate.aspx" rel="nofollow">GetFunctionPointerForDelegate</a> from the Marshal class. That is another way you could do this. Just make sure that the delegates are not GC'ed. Then, instead of delegates in your struct, declare them as IntPtr. </p> <p>That may not solve the pinning, but take a look at <a href="http://msdn.microsoft.com/en-us/library/f58wzh21%28VS.80%29.aspx" rel="nofollow"><code>fixed</code></a> keyword, even though that may not work for you since you are dealing with a longer lifetime than for what that is typically used.</p> <p>Finally, look at <a href="http://msdn.microsoft.com/en-us/library/cx9s2sy4%28VS.80%29.aspx" rel="nofollow"><code>stackalloc</code></a> for creating non-GC memory. These methods will require the use of <code>unsafe</code>, and might therefore put some other constraints on your Assemblies.</p>
calling externalinterface.call from embedded swf from another server is not working in Firefox <p>I have an index.html on server A. </p> <p>In index.html I embed a swf from server B.</p> <p>The swf contains a init with flash.external.ExternalInterface.call("alert", "externalalert"); </p> <p>When I run the swf on server B it works, when I run the swf through the index.html on server A I get an : Security sandbox violation: ExternalInterface caller...</p> <p>It does work in IE.</p> <p>Does anybody know what I'm doing wrong.</p> <p>Thanks!</p>
<p>The fix is to add</p> <pre><code>System.security.allowDomain("*"); </code></pre> <p>in your AS code. <code>ExternalInterface</code> requires the <code>allowDomain</code> to be set when HTML-SWF cross-scripting is performed.</p> <p>Note that you will also need to set <code>allowScriptAccess="always"</code> in the swf embed tags to allow cross-scripting.</p>
Removing specific items from Django's cache? <p>I'm using site wide caching with <a href="http://en.wikipedia.org/wiki/Memcached">memcached</a> as the backend. I would like to invalidate pages in the cache when the underlying database object changes. </p> <p>If the page name changes then I would invalidate the whole cache (as it affects navigation on every page. Clumsy but sufficient for my needs.</p> <p>If just the page content changes then I'd like to invalidate the cache of just that page.</p> <p>Is there an easy way to do this? </p>
<p>I haven't done a lot of caching with Django, but I think what you want here are <a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow"><code>signals</code></a>.</p> <p>You can set up a <code>post_save</code> signal on the underlying object, and have the callback function invalidate that page in the cache.</p> <pre><code>from django.core.signals import post_save from django.core.cache import cache def invalidate_cache(sender, **kwargs): # invalidate cache cache.delete(sender.get_absolute_url()) # or any other pertinent keys post_save.connect(invalidate_cache, sender=UnderlyingModel) </code></pre> <p>This should properly remove the item from the cache when it is updated.</p>
web service call returns html <p>I am calling web services from within Microsoft Access and getting html that looks like </p> <pre><code>" </code></pre> <p></p> <p></p> <pre><code>&lt;link rel="alternate" type="text/xml" href="pfp.asmx?disco"/&gt; &lt;style type="text/css"&gt; BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } c </code></pre> <p>Previously this has happened when calling a web service over https and I assumed just calling http would sort this out. It didn't, now Microsoft Access crashes with an out of memory exception. (I have checked and SSL certificate's is find and not expired) </p> <p>I've tried again and it now works (frustrating!). </p> <p>Calling the web service from .Net works almost always. </p> <p>Thanks </p>
<p>Generally in web services, you get HTML back when the server returns a fault like error 500 or 404. The reason is that the server returns a page with the error details. Is the above the whole text that you get back from the server, or was there an error pasting to StackOverflow??</p>
Do you know any real-world, useful WPF/Silverlight applications using MVVM? <p>I'm looking for code of full applications that <strong>(1) use the MVVM pattern</strong> and <strong>(2) are approachable for WPF/Silverlight/MVVM beginners</strong>. So far I have only found:</p> <ul> <li><a href="http://www.codeplex.com/cracknetproject/SourceControl/ListDownloadableCommits.aspx">Crack.NET</a> - A runtime debugging and scripting tool (useful but quite complicated)</li> <li><a href="http://www.codeproject.com/KB/WPF/ExploringWPFMVVM.aspx">CipherText</a> - WPF Password Manager (perfect but written in VB.NET)</li> </ul> <p>What are some others?</p> <p><em>preferably smaller helper apps or tools that use MVVM but that have a completed feel, perhaps with WPF/Silverlight graphic/animation goodness, etc. which show not only the MVVM concepts being used but in a context of a real-world, completed application</em></p> <h1>My Contribution</h1> <p>Thanks for all the tips, I collected together a list of 15+ MVVM code examples and posted the here: </p> <p><strong><a href="http://tanguay.info/web/index.php?pg=notesItems&amp;id=28">Overview of WPF/Silverlight code examples that help you learn MVVM</a></strong>.</p>
<p>I too class myself as a beginner in MVVM developing a large scale application for about a month now. I'm over most of the main hurdles, but keep getting confused up by a few things.</p> <p>Be careful with the suggestions from Kent. They'll get you started, but the subtle differences in Silverlight and WPF will trip you up occasionally (triggers are one).</p> <p>I don't know of any full sites, but I started with the Composite Application Guidance and PRISM libraries. These a little too cumbersome for a 'beginner' and just MVVM, but some of the concepts are very useful (event aggregator for example).</p> <p>I suggest that you read blogs by Josh Twist, Josh Smith, Shaun Wildermuth and Nikhil Kothari. These guys are very knowledgeable. They are also very open to answering questions too.</p> <p>What is your development background? Some of the concepts surrounding method calls, responses and delegation are a real break from "traditional sequential" coding techniques.</p>
Firefox not able to find iframe <p>This is the iframe I'm trying to access:</p> <pre><code> &lt;div class="mceBody" id="additionalTxt_b"&gt; &lt;iframe frameborder="0" id="additionalTxt_f" src='javascript:""' class="punymce"/&gt; &lt;/div&gt; </code></pre> <p>Using this line:</p> <pre><code>frames['additionalTxt_f'].document.getElementsByTagName("body")[0].innerHTML </code></pre> <p>For some reason I'm getting "frames.additionalTxt_f is undefined" from firebug. I have similar iframes (dynamically created by punyMCE plugin) on other pages, and they work perfectly fine. And IE7/8 has no problem accessing this iframe either.</p> <p>Just at a complete loss here. Any ideas on why Firefox can't find the iframe?</p>
<p>The <code>window.frames[]</code> array is indexed by the [i]frame's <code>name</code> attribute (aka frame target). <code>id</code> can't be relied upon to also work — although it may in IE &lt;8, which often thinks names and ids are the same thing.</p> <p>If you want to access a frame's content via ID, use the DOM Level 2 HTML <code>contentDocument</code> property instead of the old-school (“DOM Level 0”) <code>frames</code> array:</p> <pre><code>document.getElementById('additionalTxt_f').contentDocument.body.innerHTML </code></pre> <p>...but then, for compatibility with IE &lt;8, you also have to add some fallback cruft, since it doesn't support <code>contentDocument</code>:</p> <pre><code>var f= document.getElementById('additionalTxt_f'); var d= f.contentDocument? f.contentDocument : f.contentWindow.document; d.body.innerHTML </code></pre> <p>So it's up to you which method you think is less ugly: the extra script work, or just using the <code>name</code> attribute.</p>
ASP.NET Site Membership Fee Processing <p>I am building a site where people will sign up and pay to use an online web app (a yearly fee). What I've been looking for, but can't seem to find is a very simple checkout/order processing component for this type of scenario. I really don't want or need a full-blown shopping cart with product pages, etc., since we're really only selling one product. Just need to be able to have a simple checkout page to confirm they want the subscription and enter a coupon code (optional), and then provide a variety of payment options. Initially I only really need PayPal Web Payments Standard integration, but would like if it already has hooks for others like Authorize.NET in case we add that in future.</p> <p>Is there something out there like this, or am I going to have to roll my own? I don't want to re-invent the wheel if I don't have to. I realize I could dig into one of the open source carts like dashCommerce or nopCommerce and try to pull out the appropriate pieces, as well. My only problem is that they are pretty much tied to a data model that revolves around typical product/shopping cart situations.</p> <p>I look forward to any ideas you might have.</p>
<p>Sounds like you've already done the research you need. There isn't any "de-facto standard" library out there for this. But there are definitely a lot of them. Find one that fits your scenario and try it out.</p> <p>Not much help, I know. I was just going to suggest the two you mentioned already anyway, PayPal and Authorize.NET.</p>
What to return from a failed method and when to throw? <p>I´ve lately been thinking about the things i´m returning from methods and I noticed that there are 4 different things i return when the method fails. </p> <p>What bothers me about it, is that my code is not very consitent in this regard, so i wanted to ask about your "best practices".</p> <p>So lets imagine a method that takes Foo and returns a list of Bar:</p> <pre><code>public IList&lt;Bar&gt; Method(Foo something); </code></pre> <p>Or to keep it more general:</p> <pre><code>public IBar Method(IFoo something); </code></pre> <p>The question is what do you return on what kind of failure. the options would be:</p> <ol> <li>empty return type like: new List; or: new EmptyBar();</li> <li>null</li> <li>throw an exception</li> <li>a special list value indicating failure like: new List{new FailureBar()}</li> </ol> <p>I really hate option 4 so I´m mostly interessted to hear when you use the other 3 options and why</p>
<p>I'd choose between an empty list and an exception depending on the nature of the failure.</p> <p>E.g.</p> <p>If your database failed to connect - exception.</p> <p>If your query didn't return results - empty list.</p>
jQuery hyperlinks - href value? <p>On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in:</p> <pre><code>&lt;a href="#"&gt;My Link&lt;/a&gt; </code></pre> <p>However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering.</p> <p>What should I put in there?</p>
<pre><code>$('a').click(function (event) { event.preventDefault(); //here you can also do all sort of things }); </code></pre> <p>Then you can put in every <code>href</code> whatever you want and jQuery will trigger the <code>preventDefault()</code> method and you will not be redirected to that place.</p>
Standardized email regex <blockquote> <p>Why is there not a standardized email regex? I was recently involved in a project where we had a hickup where the email passed our email regex but failed when creating the MailMessage object. A small error but it had rather big consequences</p> <ul> <li>Is the MailMessage constructor using a email regex when checking if an email address is correct?</li> <li>Why are there so many different versions of an email regex?</li> </ul> <p>this is an ASP.Net application and we used the System.Net.MailMessage object</p> </blockquote> <p><strong>This is a duplicate of <a href="http://stackoverflow.com/questions/156430/regexp-recognition-of-email-address-hard">Regexp recognition of email address hard?</a></strong></p>
<p>Because even <a href="http://ex-parrot.com/~pdw/Mail-RFC822-Address.html" rel="nofollow">this regex doesn't match every valid email address</a>:</p> <pre><code>(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t] )+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?: \r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:( ?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\0 31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\ ](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+ (?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?: (?:\r\n)?[ \t])*))*|(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z |(?=[\["()&lt;&gt;@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n) ?[ \t])*)*\&lt;(?:(?:\r\n)?[ \t])*(?:@(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\ r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n) ?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t] )*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])* )(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t] )+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*) *:(?:(?:\r\n)?[ \t])*)?(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+ |\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r \n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?: \r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t ]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031 ]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\]( ?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(? :(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(? :\r\n)?[ \t])*))*\&gt;(?:(?:\r\n)?[ \t])*)|(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(? :(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)? [ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|"(?:[^\"\r\\]| \\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt; @,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|" (?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t] )*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\ ".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(? :[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[ \]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()&lt;&gt;@,;:\\".\[\] \000- \031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|( ?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\&lt;(?:(?:\r\n)?[ \t])*(?:@(?:[^()&lt;&gt;@,; :\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([ ^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\" .\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\ ]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\ [\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\ r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\] |\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()&lt;&gt;@,;:\\".\[\] \0 00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\ .|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@, ;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|"(? :[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])* (?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\". \[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[ ^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\] ]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\&gt;(?:(?:\r\n)?[ \t])*)(?:,\s*( ?:(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\ ".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:( ?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[ \["()&lt;&gt;@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t ])*))*@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t ])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(? :\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+| \Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?: [^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\ ]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\&lt;(?:(?:\r\n) ?[ \t])*(?:@(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[" ()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n) ?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt; @,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@, ;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t] )*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\ ".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)? (?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()&lt;&gt;@,;:\\". \[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?: \r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[ "()&lt;&gt;@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t]) *))*@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]) +|\Z|(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\ .(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z |(?=[\["()&lt;&gt;@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\&gt;(?:( ?:\r\n)?[ \t])*))*)?;\s*) </code></pre> <p>There are some things that are just better left to other languages.</p>
What is the difference between a 'function' and a 'procedure'? <p>Generally speaking, we all hear about the "functions" or the "procedures" in programming languages. However, I just found out that I use these terms almost interchangeably (which is probably very wrong).</p> <p>So, my question is: What is the difference in terms of their functionality, their purpose and use? An example would be appreciated.</p>
<p>A function returns a value and a procedure just executes commands.</p> <p>The name function comes from math. It is used to calculate a value based on input.</p> <p>A procedure is a set of command which can be executed in order.</p> <p>In most programming languages, even functions can have a set of commands. Hence the difference is only in the returning a value part. </p> <p>But if you like to keep a function clean, (just look at functional languages), you need to make sure a function does not have a side effect.</p>
Excel VBA macro to track changes in separate sheet <p>I am trying to write a VBA macro to track changes to a workbook in a separate sheet.</p> <p>If you do this manually, the sequence of commands is Tools > Track Changes > Highlight Changes, taking the option Separate Worksheet. You have to do two iterations of the command, one to activate tracking inline, a second to move the tracking to a separate sheet.</p> <p>Using the macro recorder, I got to this piece of code:</p> <pre><code>With ActiveWorkbook .Save .KeepChangeHistory = True .HighlightChangesOptions When:=xlAllChanges .ListChangesOnNewSheet = True .HighlightChangesOnScreen = False .Worksheets("History").Select End With </code></pre> <p>When I run this, I get the error <em>HighlightChangesOptions method fails</em>. Any suggestions?</p>
<p>The HighlightChangesOptions method will only work if the workbook is already shared. In the UI, turning on HighlightChange will share the workbook automatically, but not so in VBA.</p> <pre><code>Application.DisplayAlerts = False With ActiveWorkbook .SaveAs , , , , , , xlShared .KeepChangeHistory = True .HighlightChangesOptions When:=xlAllChanges .ListChangesOnNewSheet = True .HighlightChangesOnScreen = False .Worksheets("History").Select End With</code></pre> <p>The DisplayAlerts call will prevent Excel from warning you that you are overwriting an existing workbook - itself. You may want to comment that line out just to see what's going on.</p> <p>Note that this code cannot live in the shared workbook. Once you share the workbook, the code stops executing and errors. It has to live in a different workbook or add-in.</p>
Infragistics ultrawebgrid custom paging <p>Hi iam using infragistics ultarawebgrid in my appliccation when i use custompaging iam not able to retrive the specified no of records per page</p> <p>the code i written is string[] cusLabel;</p> <p>in the grid initialise</p> <pre><code>grid.DisplayLayout.Pager.AllowCustomPaging = true; grid.DisplayLayout.Pager.AllowPaging = true; grid.DisplayLayout.Pager.StyleMode = PagerStyleMode.CustomLabels; grdSysManager.DisplayLayout.Pager.PageSize = 3; getCustomLabel(); grdSysManager.DisplayLayout.Pager.CustomLabels = cusLabel; private void getCustomLabel() { DataTable dt = (DataTable)grdSysManager.DataSource; DataSet ds = new DataSet(); ds = dt.DataSet; //ds = (DataSet)grdSysManager.DataSource; int NoOfRows = ds.Tables[0].Rows.Count; int PageSize = grdSysManager.DisplayLayout.Pager.PageSize; if (NoOfRows % PageSize == 0) { totalNoOfPagings = NoOfRows / PageSize; } else { totalNoOfPagings = (NoOfRows / PageSize) + 1; } cusLabel = new string[totalNoOfPagings + 2]; cusLabel[0] = "First"; for (int i = 1; i &lt;= totalNoOfPagings; i++) { cusLabel[i] = i.ToString(); } cusLabel[totalNoOfPagings + 1] = "Last"; } </code></pre> <p>above is the code i written but it is displaying all the records from the table instead of 3 reords per page is i missing any thing </p> <p>thanks</p>
<pre><code>&lt;table cellspacing='0' cellpadding='0' width='100%'&gt; &lt;tr&gt; &lt;td width='12%' align='left'&gt; [currentpageindex]/[pagecount] &lt;/td&gt; &lt;td width='76%'&gt; &lt;b&gt;[page:1:First]&amp;nbsp;[prev]&lt;/b&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; [default] &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;b&gt;[next]&amp;nbsp;[page:[pagecount]:Last]&lt;/b&gt; &lt;/td&gt; &lt;td width='12%' align='right' title='Enter page number and press Enter'&gt; Go to: &lt;input id='xtxtGotoPage' size='5' style='font-family:verdana;font-size:8pt;padding:0 0 0 0' type='text' onKeyPress='return gotoPage()' autocomplete='off' /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>This pattern can be assigned in grid designer, directly in grid markup or even at runtime to Pager.Pattern property. The only thing left is to implement <code>gotoPage()</code> JavaScript function (markup, Line 17) that would go to the page number that user enters. And here it is:</p> <pre><code>function gotoPage() { if (event.keyCode == 13) { var otxtGotoPage = event.srcElement; var iPageNo = otxtGotoPage.value if (!isNaN(iPageNo)) { var oGrid = igtbl_getGridById('xuwgMyGrid'); if (iPageNo &lt; 1 || iPageNo &gt; oGrid.PageCount) { alert('Please enter page number between 1 and ' + oGrid.PageCount) } else { oGrid.goToPage(iPageNo) } } else { alert('Please enter correct numeric page number'); } otxtGotoPage.focus(); otxtGotoPage.value = ''; return false; } } </code></pre>
Are there any databases or indexes of Web Services? <p>I'm looking for something that categorizes the various services and then either (1) documents how to use them or (2) links to the documentation so I can learn more.</p>
<p>You may like <a href="http://www.programmableweb.com/matrix" rel="nofollow">ProgrammableWeb Mashup Matrix</a>, under APIs section.</p>
kill all programs from user x with vb.net <p>I try to kill all processes of a specified user.</p> <p>i use</p> <pre><code> Try Shell("C:\WINDOWS\system32\taskkill.exe /S localhost /U userx /P passwort /f /FI " &amp; Chr(34) &amp; "USERNAME eq userx" &amp; Chr(34)) Catch ex As Exception MessageBox.Show("LogoutException occurred. " + ex.Message) End Try </code></pre> <p>But Nothing happened. If i try to use this taskkill..... command by console it works fine. one of the apps that should be closed is the explorer.exe. All apps`s From the user must be closed.</p> <p>I inserted /u /p because the application it self runs under a different user.</p> <p>has anyone an idea how i could kill truely all proccesses from that 1 user?</p> <p>EDIT: i forget a little information, The application is started by a user with user-rights. thats the reason i use taskkill - there i can enter a different user with administrativ privilegs. So the second Problem is that i can`t use process.kill directly.</p> <p>thx a lot for help.</p>
<pre><code>foreach (Process p in Process.GetProcesses()) { if (String.Equals(p.ProcessName, name)) { p.Kill(); } } </code></pre> <p>or</p> <pre><code>Process.GetProcesses() .Where(p =&gt; String.Equals(p.ProcessName, name)) .First() .Kill(); // kills only first </code></pre> <p>or</p> <pre><code>Process.GetProcesses() .Where(p =&gt; String.Equals(p.ProcessName, name)) .ToList() .ForEach(p =&gt; p.Kill()); // kills all </code></pre>
Display a Photo Gallery using Asp.Net and SQL <p>I have recently added photos to my SQL database and have displayed them on an *.aspx page using Asp:Image. The ImageUrl for this control stored in a separate *.aspx page. It works great for profile pictures.</p> <p>I have a new issue at hand. I need each user to be able to have their own photo gallery page. I want the photos to be stored in the sql database. Storing the photos is not difficult. The issue is displaying the photos. I want the photos to be stored in a thumbnail grid fashion, when the user clicks on the photo, it should bring up the photo on a separate page. </p> <p>What is the best way to do this. Obviously it is not to use Asp:Image. I am curious if I should use a Gridview. If so, how do I do that and should their be a thumbnail size stored in the database for this?</p> <p>Once the picture is click on how does the other page look so that it displays the correct image. I would think it is not correct to send the photoId through the url. </p> <p>Below is code from the page I use to display profile pictures.</p> <p>protected void Page_Load(object sender, EventArgs e) {</p> <pre><code> string sql = "SELECT [ProfileImage] FROM [UserProfile] WHERE [UserId] = '" + User.Identity.Name.ToString() + "'"; string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(strCon); SqlCommand comm = new SqlCommand(sql, conn); conn.Open(); Response.ContentType = "image/jpeg"; Response.BinaryWrite((byte[])comm.ExecuteScalar()); conn.Close(); } </code></pre>
<p>"The ImageUrl for this control stored in a separate *.aspx page. It works great for profile pictures." - rather than an .aspx page, why not a generic ASP.NET handler (.ashx) instead? They are a little more lightweight than an .aspx. Just search "ASP.NET Generic Handler" and you'll find a number of samples. It's basically the code you have now behind your .aspx page, but without all the page initialization/rendering overhead.</p> <p>"I want the photos to be stored in a thumbnail grid fashion, when the user clicks on the photo, it should bring up the photo on a separate page." - I would think any ASP.NET repeatable control that supports templating of the item element (such as DataGrid, GridView, Repeater, ListView in ASP.NET 3.5, etc) should do the trick for you here. Just set the image or asp:Image height and width as appropriate for your thumbnails. Wrap which ever tag you use in an HTML anchor with an href to your page that displays the image at "full size".</p>
Strong Signed Assemblies <p>I have a project I made in Visual Basic 2008 Express. I converted it from someone else's C# project, but it works. It has several DLL dependencies. I went to publish my project so I can install it on another machine and for each DLL, I get an error: "Assembly must be strong signed in order to be marked as a prerequisite." I've done some research, but am not finding a lot and what I have found I don't really understand. What does this error mean? What is the best way to resolve it? One other thing: it took me a LONG time to be able to get all my dll's to reference correctly, so I prefer that the solution has NOTHING to do with moving DLL's around because that will likely break the functionality in my main project.</p>
<p>If you're publishing via ClickOnce, go to the publish page and click on "Application Files". From there you should see a list of your DLL's. Ensure that the ones that are giving you trouble have their Publish Status marked as "Include" rather than "Prerequisite".</p> <p>What this error message means is that the current publishing settings are going to expect all of the assemblies in question to be present in the Global Assembly Cache on the target machine before installation can take place. Since all assemblies in the GAC must be strong signed, any assembly marked as a prerequisite that isn't strong signed will give you this error.</p>
Is there a good reference card that compares T-SQL and PL/SQL side-by-side? <p>I'm looking for a good reference card / cheat sheet that compares T-SQL and PL/SQL data manipulation language commands side-by-side.</p> <p>I've previously searched SO but there isn't any older thread covering this particular subject so I thought it'd be a good idea to start one, given that such reference is almost mandatory if you happen to work in an environment where both technologies coexist.</p> <p>Thanks much in advance!</p>
<p><a href="http://troels.arvin.dk/db/rdbms/" rel="nofollow">This</a> is pretty good. In ye olde paper and inke, <a href="http://oreilly.com/catalog/9781565927445/" rel="nofollow">SQL in a nutshell</a> is also useful.</p>
extJS - Can not get data to render in GridPanel <p>The below code uses <code>Ext.data.Store</code> to retrieve a JSON with table metadata (for the column headings) and the table's data. The backend PHP script is working correctly and the <code>Ext.data.Store</code> contains valid records for the data - I just can't get them to go "into" the Grid itself.</p> <p>The API Documentation makes it seem as if I just define a <code>store</code> property for <code>Ext.grid.GridPanel</code> and it will handle the rest.</p> <p><em>Note: The code below is a separate from the rest of the application. We have pulled this portion out to see if we can just get a grid working, without the influence of the rest of the application.</em></p> <pre><code>Ext.BLANK_IMAGE_URL = 'js/ext/resources/images/default/s.gif'; Ext.onReady(function() { var columns = []; var fields = []; var tabPanel = new Ext.TabPanel({ renderTo: Ext.getBody(), activeTab: 0, height: 700 }); var queryHeaders = Ext.data.Record.create([ {name: 'id'}, {name: 'table'}, {name: 'field'}, {name: 'title'} ]); var applicationStore = new Ext.data.Store({ autoLoad: true, reader: new Ext.data.JsonReader({root: 'fields'}, queryHeaders), url: 'http://localhost/aargh/index.php/applications/hardware', listeners: { 'load': function() { console.info(applicationStore); applicationStore.each(function(r) { this_column = []; this_column['header'] = r.data['title']; this_column['dataIndex'] = r.data['id']; columns.push(this_column); this_column = [] this_column['name'] = r.data['id']; fields.push(this_column); }); console.info(fields); var queryFields = Ext.data.Record.create([fields]); var queryStore = new Ext.data.Store({ autoLoad: true, reader: new Ext.data.JsonReader({root: 'fields'}, queryFields), url: 'http://localhost/aargh/index.php/query/execute/applications/hardware', listeners: { 'load': function() { console.info(queryStore); tabPanel.add(new Ext.grid.GridPanel({ title: 'Hardware', store: queryStore, columns: columns, autoHeight: true, frame: true })); tabPanel.doLayout(); } } }); } } }); }); </code></pre> <p>As I review the <code>applicationStore</code> and <code>queryStore</code> objects in Firebug I can see the expected data results perfectly in <code>applicationStore.data.items.#.json</code> and <code>queryStore.data.items.#.json</code> (of course, replacing # with the record number).</p> <p>Any ideas?</p>
<p>Wow - this has been giving us trouble for three days. Turns out I was making an array within an array at <code>var queryFields = Ext.data.Record.create([fields]);</code></p> <p>Changing that to: <code>var queryFields = Ext.data.Record.create(fields);</code> fixed the issue.</p>
dat idx files database recognition <p>I have some .dat and .idx files and one .sup file in a directory , and i would like to know if there is any tool or .net programming tecnique to find out what type of database is? </p> <p>I dont know if this could help, but if i open one .dat file as text file, i get this: 0~0904021846460509040218464605>ÀÀX2Ü</p> <p>And the common part of all the .dat files, is the following string at the start 0~09040218.</p> <p>Could you give me a hand? Thanks a lot. Kind Regards. Josema.</p>
<p>Linux has a <a href="http://linux.die.net/man/1/file" rel="nofollow">file</a> command that uses a listing of <a href="http://linux.die.net/man/5/magic" rel="nofollow">magic numbers</a> to try and id a file type. There's a <a href="http://gnuwin32.sourceforge.net/packages/file.htm" rel="nofollow">Win32 port</a> - but I can't vouch for it. Personally, I'd xfer it over to a Linux system and run it there.</p>
MVVM + Datacontext + DataTemplate + Blend = problems <p>I'm currently using MVVM in a WPF project, all works very well. I have one Master view and many Detail views that I manage using a currentView property in my MasterViewModel. By using a datatemplate, I bind a view to a viewmodel. In fact, my master view has a contentcontrol whose content property is binded to my CurrentView property. When I set this currentview property to a viewmodel or another, it calls the corresponding template.</p> <p>My problem is that using this, my detail views doesn't have explicit datacontext because it is placed by my datatemplate. So in blend, when I open my view to edit its design, I have no datas to bind to my view. If I set a datacontext to my detailview, in blend I can see all datas I can bind but in runtime, the datacontext set by datatemplate is overrided by the datacontext set in my detailview, so I have no datas during runtime.</p> <p>Does anyone knows how I can create a good MVVM project, with views managed by datatemplates and with datacontext that we can see with Blend ?</p> <p>Thanks,</p>
<p>I've got a blog post on this issue: <a href="http://www.robfe.com/2009/08/design-time-data-in-expression-blend-3/" rel="nofollow">http://www.robfe.com/2009/08/design-time-data-in-expression-blend-3/</a></p> <p>My post is all about showing data in blend <em>without</em> having to have that data displayed or even created at runtime.</p>
php accelerator review <p>1) Can you recommend me a PHP accelerator for PHP V5.2.6?<br/> 2) Do you know about any recent test comparation/review of those modules(Alternative PHP Cache, eAccelerator, XCache, Zend Optimizer, Zend Platform, ionCube PHP Accelerator, Turck MMCache, Nusphere PhpExpress)?</p>
<p><a href="http://www.php.net/manual/en/book.apc.php"><strong>APC</strong></a> &mdash; standard choice, included in PECL, comes prepackaged in most Linux distros, to be bundled in by default in PHP6. As a bonus it can serve as <a href="http://www.php.net/manual/en/function.apc-store.php">data cache</a> (something like local memcache).</p> <p>eAccelerator was popular, for some time it was <a href="http://2bits.com/articles/benchmarking-drupal-with-php-op-code-caches-apc-eaccelerator-and-xcache-compared.html">the fastest</a> bytecode cache. But the difference in speed is not enough to justify choosing it over APC.</p> <p>Turck MMcache &mdash; dead. eAccelerator was forked from it.</p> <p>ionCube &mdash; dead.</p>
Adding a post-build event to a web site in Visual Studio 2008 <p>I am using a "web site" in visual studio 2008, and i would like to add a post-build event which would append the build time to the web.config file. Is it possible? </p>
<p>I'm afraid this isn't supported for web sites, you'll need to use a web application project.</p>
What's the best way to search GitHub? <p>The search feature on the site seems pretty awful. </p> <p>Are there any external sites that do a better job of categorizing projects with tags, etc? </p> <p>Or maybe I'm just not using GitHub correctly?</p>
<p>I haven't tried this, but I understand that very often Google does a better job of searching a website than the site's own search tools. Have you tried that?</p> <p>Go to their <a href="http://www.google.com/advanced%5Fsearch" rel="nofollow">advanced search</a> page and fill out github.com in the "Only return results from this site or domain" slot.</p>
ASP.Net MVC Controller Namespace array <p>I noticed that the MapRoute extension includes an overload that accepts a string[] parameter which is called 'namespaces'. I read what Google had for me on it, and supposedly this is to help the framework find controllers in places it wouldn't otherwise look.</p> <p>I did some spiking, and tried putting controllers in weird locations. I put one in the Scripts folder; I even built one in a separate assembly with a separate root namespace. </p> <p>Without putting anyting in the namespaces param, everything worked fine. If I put just one of the namespaces in the namespaces param, it still found all my controllers. I thought maybe it would use that array to disambiguate between similarly named controllers, but that didn't happen either. A HomeController in MyProj.Controllers and one in SomeOtherName.Stuff would collide still.</p> <p>So my question is, is that parameter deprecated? Or is it still used somehow in a way that I have yet to discern?</p>
<p>Ok, so after further testing, I figured out that it is not a filter, exactly, but it kinda is also. I gave you 'answer' credit even though you're partially wrong.</p> <p>So, it does, after all, act like I thought it should which is to say it disambiguates. Basically, the logical flow is something like this:</p> <ul> <li>Look for a namespace in the _cache that matches one in the namespaces array <ul> <li>if that's found, look for a controller of the right name</li> <li>-- if that's found, return it</li> <li>-- if it's not found, return search everywhere else that it'd normally look</li> </ul></li> <li>if it's not found, search everywhere lese</li> </ul> <p>So, in short, my thought that the namespaces array would serve to disambiguate was correct. The reason my first test in that regard failed is that it only does a perfect match, and I made the mistake of using just the root n/s from the assembly (in other wordss, MyRoot instead of MyRoot.Controllers). </p> <p>What this namespaces thing allows, then, is to have a HomeController in two different namespaces and match them differently depending on the url or params. </p>
ActiveSync support across Windows CE/Mobile machines <p>Is ActiveSync supported on all Windows CE x86 machines or are there any exceptions?</p>
<p>Windows CE is a modular, componentized OS. It is completely up to the OEM whether or not they include the ActiveSync components into the OS image. They can also include ActiveSync core support without any entity (Contact, Calendar, etc) sync capability.</p> <p>The supported transport(s) (serial, USB, ethernet, RNDIS, etc) are completely OEM configurable as well.</p>
Implementing clickable page numbers in search result <p>Classic scenario: Take user input, get a search-result and display it in pages to the user. I then need to display buttons for First, Next, Previous etc, and I maintain the users current page in viewstate. All is good, works fine.</p> <p>Then I need to implement clickable page numbers, ie. 1-2-3-4-5-6 etc.</p> <p>Rendering them is simple. I generate a linkbutton control at runtime, add commandargument with the page number and add a handler to it, so click are to be handled. Then I add it to a placeholder, and it is displayed as expected.</p> <p>But then... If I did not already have a shaved head, I would be pulling out my hair getting the events to fire as expected every time.</p> <p>How should I do this, so my events are always wired up and able to fire when the paging-linkbuttons are called?</p> <p>Below is the important parts of the code, some pseudo to make it (hopefully) easier to understand, what I am doing.</p> <pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Search() End If End Sub Sub Search 'Misc databinding stuff, searches and displays results for the page specified in Me.CurrentPage RenderPagingControls() End Sub Sub RenderPagingControls 'loop throug pagenumbers, Build a linkbutton control, add it to a placeholder AddHandler lbn.Click, AddressOf lbnNumber_Click lblPageNumbers.Controls.Add(lbn) ... End Sub Protected Sub lbnNumber_Click(ByVal sender As Object, ByVal e As EventArgs) Dim b As LinkButton = CType(sender, LinkButton) Me.CurrentPage = CInt(b.CommandArgument) Search() End Sub Public Property CurrentPage() As Integer Get Dim o As Object = Me.ViewState("CurrentPage") If o Is Nothing Then Return 1 Else Return CType(o, Integer) End If End Get Set(ByVal value As Integer) Me.ViewState("CurrentPage") = value End Set End Property Protected Sub lbnNumber_Click(ByVal sender As Object, ByVal e As EventArgs) Dim b As LinkButton = CType(sender, LinkButton) Me.CurrentPage = CInt(b.CommandArgument) Search() End Sub </code></pre>
<p>I'm going to recommend against a LinkButton and recommend Hyperlinks / QueryString parameters instead. For several reasons:</p> <ol> <li>Your page will be much more efficient without the viewstate overhead of a link button.</li> <li>If these are public facing pages, you'll get better indexing of all the pages if they can be accessed via hyperlinks (and indexed via search engines).</li> <li>You'll find them much easier to implement. No event management, etc.</li> </ol> <p>You would redefine your CurrentPage method as (hopefully this is correct, I'm better at C# than vb.net):</p> <pre><code>Public Property CurrentPage() As Integer Get Dim o As Object = Me.Request.QueryString("page") If o Is Nothing Then Return 1 Else Return CType(o, Integer) End If End Get End Property </code></pre> <p>Then just add hyperlinks for each page.</p> <pre><code>&lt;a href='mypage.aspx?page=1'&gt;1&lt;/a&gt; - &lt;a href='mypage.aspx?page=2'&gt;2&lt;/a&gt; etc... </code></pre> <p><strong>Alternative:</strong> If you want to use the LinkButton, you might want to consider putting a single LinkButton in a repeater. Then the only event you have to worry about is the OnItemCommand event. Then no dynamic controls or events. Something like this:</p> <pre><code>&lt;asp:Repeater ID="rptPages" runat="server" OnItemCommand='doPaging'&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton ID="LinkButton1" runat="server" Text='&lt;%# (Container.DataItem).ToString() %&gt;' CommandArgument='&lt;%# (Container.DataItem).ToString() %&gt;' /&gt; &lt;/ItemTemplate&gt; &lt;SeparatorTemplate&gt;-&lt;/SeparatorTemplate&gt; &lt;/asp:Repeater&gt; </code></pre> <p>Bind this control to an array (or list) of consecutive Integers (as many are there are pages). Then in your doPaging function (as I call it), check RepeaterCommandEventArgs.CommandArgument to get the page number.</p>
Using reflection to check if a method is "Extension Method" <p>As part of my application I have a function that receives a MethodInfo and need to do specific operations on it depending if that method is "Extension Method".</p> <p>I've checked the MethodInfo class and I could not find any <em>IsExtension</em> property or flag that shows that the method is extension.</p> <p>Does anyone knows how can I find that from the method's MethodInfo?</p>
<p>You can call the <strong>IsDefined</strong> method on the MethodInfo instance to find this out by checking to see if the <strong>ExtensionAttribute</strong> is applied to the method:</p> <pre><code>bool isExtension=someMethod.IsDefined(typeof(ExtensionAttribute),true); </code></pre>
What's an OCCI context and environment? <p>I'm exploring a piece of software making use of Oracle API and as far as I can see often object methods expect as an argument a "OCCI context" or a "OCCI environment" values.</p> <p>An example is a constructor of an Account object:</p> <pre><code>Account( oracle::occi::Environment* env ); </code></pre> <p>later overloaded with </p> <pre><code>Account( void* oraCtx ); </code></pre> <p>I can understand that somehow they have to do with sort of a "connection handler", but I'd like to know more.</p> <p>I googled around but I couldn't find anything clear enough for me, it seems every doc starts from the assumption you already know Oracle API.</p> <p>Thanks.</p>
<p><code>OCCI Environment</code> lets you define your own memory management functions which <code>OCCI</code> will later use.</p> <p>When you create an <code>environment</code>, you pass the pointers to your own <code>malloc</code>, <code>realloc</code> and <code>free</code>:</p> <pre><code>static Environment * createEnvironment(Mode mode = DEFAULT, void *ctxp = 0, void *(*malocfp)(void *ctxp, size_t size) = 0, void *(*ralocfp)(void *ctxp, void *memptr, size_t newsize) = 0, void (*mfreefp)(void *ctxp, void *memptr) = 0); </code></pre> <p><code>Context</code> is just a pointer to an <code>Environment</code> that is passed to these functions when <code>OCCI</code> calls them.</p>
How can I get generic Type from a string representation? <p>I have <code>MyClass&lt;T&gt;</code>.</p> <p>And then I have this <code>string s = "MyClass&lt;AnotherClass&gt;";</code>. How can I get Type from the string <code>s</code>?</p> <p>One way (ugly) is to parse out the "&lt;" and ">" and do: </p> <pre><code>Type acType = Type.GetType("AnotherClass"); Type whatIwant = typeof (MyClass&lt;&gt;).MakeGenericType(acType); </code></pre> <p>But is there a cleaner way to get the final type without any parsing, etc.?</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx">format for generics</a> is the name, a ` character, the number of type parameters, followed by a comma-delimited list of the types in brackets:</p> <pre><code>Type.GetType("System.Collections.Generic.IEnumerable`1[System.String]"); </code></pre> <p>I'm not sure there's an easy way to convert from the C# syntax for generics to the kind of string the CLR wants. I started writing a quick regex to parse it out like you mentioned in the question, but realized that unless you give up the ability to have nested generics as type parameters the parsing will get very complicated.</p>
Sql Server Ce 3.5 Check Constraints <p>Does Sql Server ce Suports Check Constraints? I wanted to do something like "ALTER TABLE WITH NOCHECK ADD CONSTRAINT id_range_check CHECK ( BETWEEN and )</p> <p>and this will give an error on 'WITH'</p>
<p>SQL Server Compact does not support CHECK constraint <a href="http://technet.microsoft.com/en-us/library/ms174123(v=sql.110).aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/ms174123(v=sql.110).aspx</a></p>
Double.Parse - Internationalization problem <p>This is driving me crazy. I have the following string in a ASP.NET 2.0 WebForm Page</p> <pre><code>string s = "0.009"; </code></pre> <p>Simple enough. Now, if my culture is Spanish - which is "es-ES" - and I try to convert the string to Double, I do the following:</p> <pre><code>double d = Double.Parse(s, new CultureInfo("es-ES")); </code></pre> <p>what I'd expect is 0,009. Instead, I get 9. I understand that .NET thinks it is a thousand separator, which in en-US is a comma, but shouldn't it take the culture info I'm passing to the parse method and apply the correct format to the conversion?</p> <p>If I do</p> <pre><code>double d = 0.009D; string formatted = d.ToString(new CultureInfo("es-ES")); </code></pre> <p>formatted is now 0,009. Anybody?</p>
<p>It <strong>is</strong> taking the culture you gave and applying the correct formatting. You provided a string of "0.009" and told it that it was Spanish...then you complain that it properly interpreted it as Spanish! Don't tell it that the string is Spanish when you know it isn't.</p> <p>You should pass the Parse method the culture of the string being parsed, which in this case would be en-US or en-Gb or InvariantCulture.</p>