input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Cascading Deletes/Updates using JPA or Inside of Database? <p>Performance is key: Is it better to cascade deletes/updates inside of the Database or let Hibernate/JPA take care of it?</p>
<p>Will this effect the ability to query for the data if cascades are inside of the DBMS?</p>
<p>I am using HSQLDB if that matters.</p>
| <p>In the case of cascading updates, you simply cannot do it in application space if you have foreign key constraints in the database.</p>
<p>Example: say you have a lookup table for US states, with a primary key of the two-letter abbreviation. Then you have a table for mailing addresses that references it. Someone tells you that you mistakenly gave Montana the abbreviation "MO" instead of "MT" so you need to change it in the lookup table.</p>
<pre><code>CREATE TABLE States (st CHAR(2) PRIMARY KEY, state VARCHAR(20) NOT NULL);
INSERT INTO States VALUES ('MO', 'Montana');
CREATE TABLE Addresses (addr VARCHAR(20), city VARCHAR(20), st CHAR(2), zip CHAR(6),
FOREIGN KEY (st) REFERENCES States(st));
INSERT INTO Addresses VALUES ('1301 East Sixth Ave.', 'Helena', 'MO', '59620');
</code></pre>
<p>Now you go to fix the mistake, without the aid of database-side cascading updates. Below is a test using MySQL 5.0 (assume no records exist for Missouri, which actually does use the abbreviation "MO").</p>
<pre><code>UPDATE States SET st = 'MT' WHERE st = 'MO';
ERROR 1451 (23000): Cannot delete or update a parent row:
a foreign key constraint fails (`test/addresses`,
CONSTRAINT `addresses_ibfk_1` FOREIGN KEY (`st`) REFERENCES `states` (`st`))
UPDATE Addresses SET st = 'MT' WHERE st = 'MO';
ERROR 1452 (23000): Cannot add or update a child row:
a foreign key constraint fails (`test/addresses`,
CONSTRAINT `addresses_ibfk_1` FOREIGN KEY (`st`) REFERENCES `states` (`st`))
UPDATE Addresses JOIN States USING (st)
SET Addresses.st = 'MT', States.st = 'MT'
WHERE States.st = 'MO';
ERROR 1451 (23000): Cannot delete or update a parent row:
a foreign key constraint fails (`test/addresses`,
CONSTRAINT `addresses_ibfk_1` FOREIGN KEY (`st`) REFERENCES `states` (`st`))
</code></pre>
<p>No application-side query can solve this situation. You need cascading updates in the database in order to perform the update in both tables atomically, before the referential integrity constraint is enforced.</p>
|
PHP standard input? <p>I know PHP is usually used for web development, where there <em>is</em> no standard input, but PHP claims to be usable as a general-purpose scripting language, if you do follow it's funky web-based conventions. I know that PHP prints to <code>stdout</code> (or whatever you want to call it) with <code>print</code> and <code>echo</code>, which is simple enough, but I'm wondering how a PHP script might get input from <code>stdin</code> (specifically with <code>fgetc()</code>, but any input function is good), or is this even possible?</p>
| <p>It is possible to read the <code>stdin</code> by creating a file handle to <code>php://stdin</code> and then read from it with <code>fgets()</code> for a line for example (or, as you already stated, <code>fgetc()</code> for a single character):</p>
<pre><code><?php
$f = fopen( 'php://stdin', 'r' );
while( $line = fgets( $f ) ) {
echo $line;
}
fclose( $f );
?>
</code></pre>
|
ASP.NET MVC: Binding a Complex Type to a Select <p>I am trying to work out if there is built-in support for binding complex types to form elements.</p>
<p>To use a common hypothetical situation:
I have a Product entity that belongs to a Category - the models look something like this:</p>
<pre><code>public class Product
{
public int ID { get; set; }
public string Description { get; set; }
public Category Category { get; set; }
}
public class Category
{
public int ID { get; set; }
public string Title { get; set; }
}
</code></pre>
<p>Creating a form to hydrate a new entity that only contains simple value types is nice and simple using the ASP.Net MVC framework, e.g.:</p>
<pre><code>public ActionResult Create(Product product);
</code></pre>
<p>But what about the above scenario where your entities contain other complex types? Are there built-in mechanisms for binding an IEnumerable<<i>T</i>> to a drop down list and then automatically hydrating the correct <i>T</i> when the form is submitted?</p>
<p>It would be fairly trivial to do it manually - I'm just trying to ascertain what I can have for free out of the box.</p>
| <p>See <a href="http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx#three">here</a> and <a href="http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx">here</a> and <a href="http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx">here</a> for details about model binding.</p>
|
What application do you use to synchronize work directory with ftp directory? <p>I'd like to poll this question: What application do you use to synchronize the working directory at local PC and remote directory (via FTP)?</p>
<p>I'm kind of bored of using FTP client to transfer each file I edit all the time.</p>
| <p>In a simple case you can use <code>scp</code> or <code>ftp</code> command line programs to write a small command line script that can upload all your files. I use a bash script that zips up all my files, puts it on my webspace, and unzips the file over ssh. Although this would be easily done with bash on linux I think that you can do similar with <code>bat</code> files on windows.</p>
<p>For a larger web development project, commit the code to a server side source repository and use a tool like <a href="http://www.capify.org/" rel="nofollow">Capistrano</a> to deploy it to remote servers which is a powerful and full featured deployment tool for web application of all kinds.</p>
|
How can I stop Filezilla changing my linebreaks? <p>I'm downloading a perl CGI file from a Linux web server.</p>
<p>It has Unix linebreaks. I edit it on a Windows PC with a decent text-editor (Geany) which preserves those linebreaks.</p>
<p>I then upload it again with Filezilla and it has DOS linebreaks, which stop it working.</p>
<p>I know it's Filezilla, not Geany because even if I just download it, and re-upload it, the problem recurs.</p>
<p>Filezilla asks me, every time, if I'm OK to upload the local file (3611) bytes and overwrite the remote file (3753 bytes), and the difference between those numbers is the number of lines in my file. But when I do that, the one on the server is 3753 bytes all over again and doesn't work.</p>
<p>I'm going through a proxy server, might that be a factor? The really weird thing is I did the same thing on a different XP PC just the other day and it was fine. And command-line FTP works fine too.</p>
| <p>In FileZilla 2.2.32, go Edit > Settings > File transfer settings > ASCII/Binary. Set it to always binary: that should do the trick.</p>
<p>In FileZilla 3.5.0 the setting is in Edit > Settings > Transfers > File Types > Default transfer type > Binary.</p>
|
Diagnosing and improving performance of a java jnlp compared to jar file <p>Customer X has asked for ways to improve the startup time of a Java process he uses. The problem is, it is not run through a jar file, but rather 'jnlp' (which I am assuming indicates it is a java webstart application)</p>
<pre><code>StartUserWorx.jnlp
</code></pre>
<p>Is there a way to convert this to a JAR file and then have the user invoke the application locally, and include a startup flag to the JRE to allocate more ram to the process?</p>
<p>The user is getting a bit frustrated, because other workers in the same office use the same application on almost identical machines, and yet his process seems to always take a much longer time to load (a few minutes rather than a few seconds).</p>
| <p>Check the proxy settings on the slow machine. That user might not have correct proxy settings, and a lot of extra network traffic/timeouts could be occurring? </p>
<p>We've had that issue with webstart before, downloading a jar from a local server was round tripping through the proxy to the other coast and back.</p>
|
Linq return IEnumerable<MyObject>, how to return MyListObject instead? <p>Is there a way without looping all the IEnumerable to get back the data inside the object (that inherited BindingList)?</p>
<pre><code>MyListObject--> Transformed with Linq --> Back the data inside MyListObject
</code></pre>
<p>I know that I can do .ToList but it doesn't do what I would like.</p>
<p>Any idea? Thank :)</p>
| <p>One option is to wrap the returned IEnumerable into your collection type by using/adding constructor that takes IEnumerable as CStick suggest. Perhaps a bit more ellegant way is to add an extension method for the IEnumerable type that would return your collection:</p>
<pre><code>static MyListObject ToMyList(this IEnumerable<T> en) {
// construct your MyListObject from 'en' somehow
}
// And then just write:
var mylist = (from c in ... ).ToMyList()
</code></pre>
<p>The last option that's probably too complicated for this simple scenario is to implement all the LINQ query operators for your type (extension methods Where, Select, and many many others). The plus thing is that you could (maybe) do some things more efficiently, but it's really a bit difficult thing to do.</p>
|
Templates: Use forward declarations to reduce compile time? <p>I have to deal with a library that consists of many templated classes, which are of course all implemented in header files. Now I'm trying to find a way to reduce the unbearably long compile times that come from the fact that I pretty much have to include the whole library in each and one of my compilation units.</p>
<p>Is using forward declarations a possibility, despite the templates? I'm trying something along the lines of the example below, where I attempted to get around the <code>#include <vector></code>, as an example, but it's giving me a linker error because <code>push_back</code> is undefined. </p>
<pre><code>#include <iostream>
namespace std {
template<class T>
class vector {
public:
void push_back(const T& t);
};
}
int main(int argc, char** argv) {
std::vector<int>* vec = new std::vector<int>();
vec->push_back(3);
delete vec;
return EXIT_SUCCESS;
}
$ g++ fwddecl.cpp
ccuqbCmp.o(.text+0x140): In function `main':
: undefined reference to `std::vector<int>::push_back(int const&)'
collect2: ld returned 1 exit status
</code></pre>
<p>I tried precompiled headers once but that didn't change the compile times at all (I did make sure they were indeed loaded instead of the real headers). But if you all say that precompiled headers should be the way to go then I'll give that a try again.</p>
<p><strong>UPDATE:</strong> Some people say it's not worth to forward-declare the STL classes. I should stress that the STL <code>vector</code> above was just an example. I'm not really trying to forward-declare STL classes, but it's about other, heavily templated classes of some library that I have to use.</p>
<p><strong>UPDATE 2:</strong> Is there a way to make above example actually compile and link properly? Logan suggests to use <code>-fno-implicit-templates</code> and put <code>template class std::vector<int></code> somewhere, presumably into a separate <code>.cpp</code> file that gets compiled with <code>-fno-implicit-templates</code>, but I still get linker errors. Again, I'm trying to understand how it works for <code>std::vector</code> so that I can then apply it to the templated classes that I'm actually using. </p>
| <p>You can't forward declare "parts" of classes like that. Even if you could, you'd still need to instantiate the code somewhere so you could link against it. There are ways to handle it, you could make yourself a little library with instantiations of common containers (e.g. vector) and link them in. Then you'd only ever need to compile e.g. vector<int> once. To implement this you'll need to use something like <code>-fno-implicit-templates</code>, at least assuming you are sticking with g++ and explicitly instantiate the template in your lib with <code>template class std::vector<int></code></p>
<p><hr /></p>
<p>So, a real working example. Here I have 2 files, a.cpp and b.cpp</p>
<p>a.cpp:</p>
<pre><code>#include <vector> // still need to know the interface
#include <cstdlib>
int main(int argc, char **argv) {
std::vector<int>* vec = new std::vector<int>();
vec->push_back(3);
delete vec;
return EXIT_SUCCESS;
}
</code></pre>
<p>So now I can compile a.cpp with <code>-fno-implicit-templates</code>:</p>
<pre><code>g++ -fno-implicit-templates -c a.cpp
</code></pre>
<p>This will give me a.o. If I then I try to link a.o I get:</p>
<pre><code>g++ a.o
/usr/bin/ld: Undefined symbols:
std::vector<int, std::allocator<int> >::_M_insert_aux(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, int const&)
void std::_Destroy<int*, std::allocator<int> >(int*, int*, std::allocator<int>)
collect2: ld returned 1 exit status
</code></pre>
<p>No good. So we turn to b.cpp:</p>
<pre><code>#include <vector>
template class std::vector<int>;
template void std::_Destroy(int*,int*, std::allocator<int>);
template void std::__uninitialized_fill_n_a(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, unsigned long, int const&, std::allocator<int>);
template void std::__uninitialized_fill_n_a(int*, unsigned long, int const&, std::allocator<int>);
template void std::fill(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, int const&);
template __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > > std::fill_n(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, unsigned long, int const&);
template int* std::fill_n(int*, unsigned long, int const&);
template void std::_Destroy(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, std::allocator<int>);
</code></pre>
<p>Now you're saying to yourself, where did all these extra template things come from? I see the <code>template class std::vector<int></code> and that's fine, but what about the rest of it? Well the short answer is that, these things implementations are by necessity a little messy, and when you manually instantiate them, by extension some of this messiness leaks out. You're probably wondering how I even figured out what I needed to instantiate. Well I used the linker errors ;).</p>
<p>So now we compile b.cpp</p>
<pre><code>g++ -fno-implicit-templates -c b.cpp
</code></pre>
<p>And we get b.o. Linking a.o and b.o we can get</p>
<pre><code>g++ a.o b.o
</code></pre>
<p>Hooray, no linker errors.</p>
<p>So, to get into some details about your updated question, if this is a home brewed class it doesn't necessarily have to be this messy. For instance, you can separate the interface from the implementation, e.g. say we have c.h, c.cpp, in addition to a.cpp and b.cpp</p>
<p>c.h</p>
<pre><code>template<typename T>
class MyExample {
T m_t;
MyExample(const T& t);
T get();
void set(const T& t);
};
</code></pre>
<p>c.cpp</p>
<pre><code>template<typename T>
MyExample<T>::MyExample(const T& t) : m_t(t) {}
template<typename T>
T MyExample<T>::get() { return m_t; }
template<typename T>
void MyExample<T>::set(const T& t) { m_t = t; }
</code></pre>
<p>a.cpp</p>
<pre><code> #include "c.h" // only need interface
#include <iostream>
int main() {
MyExample<int> x(10);
std::cout << x.get() << std::endl;
x.set( 9 );
std::cout << x.get() << std::endl;
return EXIT_SUCCESS;
}
</code></pre>
<p>b.cpp, the "library":</p>
<pre><code> #include "c.h" // need interface
#include "c.cpp" // need implementation to actually instantiate it
template class MyExample<int>;
</code></pre>
<p>Now you compile b.cpp to b.o once. When a.cpp changes you just need to recompile that and link in b.o.</p>
|
Semi-modal editing / auto prefixing keys <p>Most emacs modes include some sort of prefix to activate their features. For example, when using <em>GUD</em> "next" is "C-c C-n". Of these modes, many provide special buffers where one can use a single key to activate some functionality (just 'n' or 'p' to read next/previous mail in <em>GNUS</em> for example).</p>
<p>Not all modes provide such a buffer, however, and repeatedly typing the prefix can be tiresome. Is there a well-known bit of elisp that will allow for ad-hoc specification of prefix keys to be perpended to all input for some time? (Until hitting ESC or some other sanctioned key, for example)</p>
| <p>I agree with Joe Casadonte's answer that the way to go is to define your own minor (or major) mode.</p>
<p>That being said, your question is interesting.</p>
<p>Here's a solution that prompts you for a key sequence and it takes the prefix keystrokes and promotes that keymap to the top level.</p>
<p>e.g. Assume the following keymap:</p>
<pre><code>M-g ESC Prefix Command
M-g g goto-line
M-g n next-error
M-g p previous-error
</code></pre>
<p>When you run <code>M-x semi-modal-minor-mode</code>, it will prompt you for some keystrokes. If you enter <code>M-g n</code>, then the following keybindings are set:</p>
<pre><code>ESC Prefix Command (same as M-g ESC)
g goto-line
n next-error
p previous-error
</code></pre>
<p>So now <code>n</code> doesn't self-insert, but jumps to the next error. See the code below.</p>
<p>Note: when this minor mode is enabled, <code><f12></code> is bound to a command which disables the minor mode. This is because the keybindings might very well disable your Emacs (for instance, what if there was a new keybinding for <code>M-x</code>).</p>
<p><em>Edited to add these thoughts:</em> the minor mode variable was originally made buffer local, but that doesn't work unless you <em>also</em> make the minor-mode-alist variable buffer local (duh). But, you also (probably) don't want these bindings in the minibuffer... So, I'm not going to test it b/c it really depends on what you want, but I've added a comment to the code reflecting this thought.</p>
<p>Without further ado:</p>
<pre><code>(defvar semi-modal-minor-mode-keymap (make-sparse-keymap)
"keymap holding the prefix key's keymapping, not really used")
(defvar semi-modal-minor-mode-disable-key (kbd "<f12>")
"key to disable the minor mode")
(defun semi-modal-minor-mode-disable ()
"disable the minor mode"
(interactive)
(semi-modal-minor-mode 0))
(define-minor-mode semi-modal-minor-mode
"local minor mode that prompts for a prefix key and promotes that keymap to the toplevel
e.g. If there are bindings like the following:
M-g ESC Prefix Command
M-g g goto-line
M-g n next-error
M-g p previous-error
And you enter 'M-g n' when prompted,
then the minor mode keymap has the bindings
g -> goto-line
n -> next-error
p -> previous-error
ESC -> Prefix Command (same as M-g ESC)
The variable semi-modal-minor-mode-disable-key is bound to disable the minor mode map.
This is provided because often the mappings make the keyboard unusable.
Use at your own risk."
nil " Semi" semi-modal-minor-mode-keymap
(make-local-variable 'semi-modal-minor-mode)
(make-local-variable 'minor-mode-map-alist)
(let ((pair-holding-keymap-to-modify (assq 'semi-modal-minor-mode minor-mode-map-alist)))
(setcdr pair-holding-keymap-to-modify (make-sparse-keymap))
(if semi-modal-minor-mode
(let (key
keymap)
;; all but last (b/c we want a prefix
(setq key (substring (read-key-sequence "Enter a full key combination, the prefix will be used: ") 0 -1))
(if (and (not (equal "" key))
(not (equal (kbd "C-g") key))
(let ((semi-modal-minor-mode nil))
(keymapp (setq keymap (key-binding key)))))
(progn
(setcdr pair-holding-keymap-to-modify (copy-keymap keymap))
(when semi-modal-minor-mode-disable-key
(define-key (cdr pair-holding-keymap-to-modify)
semi-modal-minor-mode-disable-key 'semi-modal-minor-mode-disable)))
(semi-modal-minor-mode 0))))))
</code></pre>
|
SWIFT MT message validation <p>I am looking for java library or a vb addin that can be used for
- SWIFT message syntax validation
- Building SWIFT message from available data.
- Retrieving the required tag/field data.</p>
<p>Can anybody help me in this regard??</p>
<h2>I have seen few of the available libraries like WIFE but all fails in catching errors if the message is not in standard format.</h2>
<p>Pavan</p>
| <p>with "SWIFT message syntax validation" I guess you are speaking about getting the FIN syntax right?</p>
<p>If so, I have just posted an answer to another SWIFT related question on StackOverflow.</p>
<p>I have copy and pasted my response below again for your convenience (from here: <a href="http://stackoverflow.com/questions/25192/java-swift-library">java-swift-library</a>):
<hr>
SWIFT is releasing a "Standards Developer Kit" which includes an "MT/XML Schema Library".</p>
<p>From the doc: "The MT/XML Schema Library is a complete set of XML schema definitions for MT messages, and software which shows how to convert messages from an MT format to an MT XML representation and back. This approach allows XML integration between applications while the MT (FIN) format will continue to be transported over the SWIFT network."</p>
<p>Java source code will also be made available, again from the doc: "Working sample Java source code that converts a message in MT format to an XML instance and from an XML instance to a message in MT format."</p>
<p>See: https://www.swiftcommunity.net/communities/download.cfm?id=4798</p>
<p>This can be a great aid in dealing with FIN messages in XML syntax.
<hr></p>
<p>So, using the "Standards Developer Kit" you do not have to worry anymore about getting the FIN syntax right.</p>
<p>Hope it is useful for you,</p>
<p>Stijn.</p>
|
Finding Memory Usage in Java <p>Following is the scenario i need to solve. I have struck with two solutions.</p>
<p>I need to maintain a cache of data fetched from database to be shown on a Swing GUI.
Whenever my JVM memory exceeds 70% of its allocated memory, i need to warn user regarding excessive usage. And once JVM memory usage exceeds 80%, then i have to halt all the database querying and clean up the existing cache fetched as part of the user operations and notifying the user. During cleanup process, i will manually handle deleting some data based up on some rules and instructs JVM for a GC. Whenever GC occurs, if memory cleans up and reaches 60% of the allocated memory, I need to restart all the Database handling and giving back control to the user. </p>
<p>For checking JVM memory statistics i found following two solutions. Could not able to decide which is best way and why.</p>
<ol>
<li><p>Runtime.freeMemory() - Thread created to run every 10 seconds and check for the free memory and if memory exceeds the limits mentioned, necessary popups will intimate user and will call the methods to halt the operations and freeing up the memory.</p></li>
<li><p>MemoryPoolMXBean.getUsage() - Java 5 has introduced JMX to get the snapshot of the memory at runtime. In, JMX i cannot use Threshold notification since it will only notify when memory reaches/exceeds the given threshhold. Only way to use is Polling in MemoryMXBean and check the memory statistics over a period.</p></li>
</ol>
<p>In case of using polling, it seems for me both the implementations are going to be same.</p>
<p>Please suggest the advantages of the methods and if there are any other alternatives/any corrections to the methods using.</p>
| <p>Just a side note: <code>Runtime.freeMemory()</code> doesn't state the amount of memory that's left of allocating, it's just the amount of memory that's free within the currently allocated memory (which is initially smaller than the maximum memory the VM is configured to use), but grows over time.</p>
<p>When starting a VM, the max memory (<code>Runtime.maxMemory()</code>) just defines the upper limit of memory that the VM may allocate (configurable using the -Xmx VM option).
The total memory (<code>Runtime.totalMemory()</code>) is the initial size of the memory allocated for the VM process (configurable using the -Xms VM option), and will dynamically grow every time you allocate more than the currently free portion of it (<code>Runtime.freeMemory()</code>), until it reaches the max memory.</p>
<p>The metric you're interested in is the memory available for further allocation:</p>
<pre><code>long usableFreeMemory= Runtime.getRuntime().maxMemory()
-Runtime.getRuntime().totalMemory()
+Runtime.getRuntime().freeMemory()
</code></pre>
<p>or:</p>
<pre><code>double usedPercent=(double)(Runtime.getRuntime().totalMemory()
-Runtime.getRuntime().freeMemory())/Runtime.getRuntime().maxMemory()
</code></pre>
|
How to update specific files via msi installation <p>I want to make a installation which can be both new installation and update installation.
When it was used as an update installation, I want some files to be updated regardless the version and modified datetime. And some files would never be updated.</p>
<p>What I tried:
Set the "REINSTALLMODE" to "amus". And set the "Never overwrite" property of never updated files' components to be "Yes".</p>
<p>What I get:
It doesn't work. Those components with "Never overwrite = yes" are still updated somehow.</p>
<p>My question:
Is this right? REINSTALLMODE has the higher priority than component's "Never overwrite" property?
How to deal with this partial updates issue?</p>
<p>Thanks in advance.</p>
| <p>MSI has specific <a href="http://blogs.msdn.com/astebner/archive/2005/08/30/458295.aspx" rel="nofollow">File replacement logic</a>.</p>
<p>I would look into doing a <a href="http://msdn.microsoft.com/en-us/library/aa369786(VS.85).aspx" rel="nofollow">Major upgrade</a>.</p>
<p>Assuming these are unversioned files (for example text/xml config files, not assemblies) I would manually set the File Version on any file I wanted to always be updated (the manually set version will override what is already installed), and leave alone the others which the file replacement logic should ignore.</p>
<p>Here is a doc about <a href="http://msiworld.blogspot.com/2008/10/how-reinstallmodeamus-works.html" rel="nofollow">REINSTALLMODE=amus</a> which mentions the 'a' means ignore file versioning rules and update everything. not what you want. Also, I believe REINSTALLMODE is generally for 'repair' operations, not install/upgrade anyways.</p>
|
Linq to SQL null values in GridView <p>Normally if I'm linking an ObjectDataSource to a GridView and I have a TemplateColumn that has an Eval in it and it's Null, I can just put a ".ToString()" it works fine. For some reason, this doesn't work the same when you're using Linq to SQL.</p>
<p>I originally was using XSD files for my DAL with a custom BLL. I tied it to the GridView with an ObjectDataSource. I'm in the middle of swapping out the XSD files with Linq to SQL and everything is working just like the old way except for the columns that can have Null values.</p>
<p>Has anyone run into this before and if so, how do I work around this problem?</p>
| <p>Most everything that LINQ returns is of <a href="http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx" rel="nofollow">Nullable types</a>. So in your binding expressions you need to use GetValueOrDefault().ToString() or the new "??" null coalescing operator rather than just plain old ToString(). I hope this helps. Check this <a href="http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx" rel="nofollow">link</a> out to.</p>
<p>Example:</p>
<pre><code>// this will output the int if not null otherwise an empty string.
<%# (int?)Eval("MyIntegerField") ?? "" %>
</code></pre>
|
How do I get all the values of a Dictionary<TKey, TValue> as an IList<TValue>? <p>I have a the following dictionary:</p>
<pre><code>IDictionary<int, IList<MyClass>> myDictionary
</code></pre>
<p>and I am wanting to get all the values in the dictionary as an IList....</p>
<p><hr /></p>
<p>Just to add a bit of a background as to how I've gotten into this situation....</p>
<p>I have a method that gets me a list of MyClass. I then have another method that converts that list into a dictionary where they key is the id for MyClass. Later on...and without access to that original list...I'm needing to obtain the original ungrouped list of MyClass.</p>
<p><hr /></p>
<p>When I pass myDictionary.Values.ToList() to a method that takes an IList I get a compile error that says that it can't convert from </p>
<pre><code>System.Collections.Generic.List<System.Collections.Generic.IList<MyClass>>
</code></pre>
<p>to:</p>
<pre><code>System.Collections.Generic.IList<MyClass>
</code></pre>
<p>Now, I can understand that its gone and added each of the groups of IList to the new list as separate elements of the list....but in this instance its not really what I'm after. I just want a list of all the values in the entire dictionary.</p>
<p>How then can I get what I'm after without looping through each of the key values in the dictionary and creating the list I want?</p>
| <p>Because of how a dictionary (or hash table) is maintained this is what you would do. Internally the implementation contains keys, buckets (for collision handling) and values. You might be able to retrieve the internal value list but you're better of with something like this: </p>
<pre><code>IDictionary<int, IList<MyClass>> dict;
var flattenList = dict.SelectMany( x => x.Value );
</code></pre>
<p>It should do the trick ;) SelectMany flattens the result which means that every list gets concatenated into one long sequence (IEnumerable`1).</p>
|
what is the purpose of a css link placed like this style.css?23409823098 <p>Duplicate of <a href="http://stackoverflow.com/questions/438821/what-does-do-in-a-css-link">what does do in a css link</a></p>
<p>I've seen a few sites who list a stylesheet with parameters in it.
does anyone know what its called and what purpose they serve?</p>
<p>ex:</p>
<p>href="fonts.css?1169659562000" </p>
| <p>The parameter is changed every time the content of the file changes. This allows the site hoster to set an infinite cache timeout, which keeps the browser from re-requesting the CSS. Without the parameter, updates would never reach the client.</p>
<p>See also the <a href="http://blog.stackoverflow.com/2009/01/podcast-38/" rel="nofollow">Stackoverflow Podcast #38</a> and the <a href="http://developer.yahoo.com/yslow/" rel="nofollow">YSlow tool</a>.</p>
|
Error reporting tool/service <p>I was wondering if there is any tool out there which could be easily integrated into my existing application infrastructure and handle the error reporting. Kind of a service.</p>
<p>It should allow me (as an application developer) to send unhandled errors into it .. e.g. using a webservice, etc.</p>
| <p>Have a look at <a href="http://www.gurock.com/products/smartinspect/" rel="nofollow">SmartInspect</a>.</p>
|
NHibernate one-to-many problem <p>I have a Vessel object that has a one-to-many relationship with a
VesselDetail object. When I add a VesselDetail object to the Vessel object and try to save the Vessel object, it seems NHibernate does not add the foreign key when inserting the VesselDetail object.</p>
<p>Where am I going wrong here ? I just cannot figure it out.</p>
<p>Error message:
BDN.FindVessel.Tests.Integration.NhibernateRepositoryTests.SaveVessel_ShouldAddDetailsToDb_WhenAddedToEntity:
NHibernate.Exceptions.GenericADOException : could not insert: [BDN.FindVessel.Domain.VesselDetail][SQL: INSERT INTO BoatsDetails (SaftyGear, OtherMachineryAndGear, Material, Size, Various, TranslatorId, SpeenAndConsumption, MainMachinery, Created, Class, Capasities, Culture, Interior, Electronics, DeckGear) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); select SCOPE_IDENTITY()]
----> System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'BoatId', table 'FindVesselTest.dbo.BoatsDetails'; column does not allow nulls. INSERT fails.
The statement has been terminated.</p>
<pre><code>public class Vessel
{
public virtual int BoatId { get; set; }
public virtual IList<VesselDetail> Details { get; set; }
//...
}
public class VesselDetail
{
public virtual int VesselDetailId { get; set; }
//some other properties
//..
}
public class VesselMap: ClassMap<Vessel>
{
public VesselMap()
{
WithTable("Boats");
Id(x => x.BoatId, "Id");
//..
HasMany(x => x.Details)
.WithKeyColumn("BoatId") //foreign key in the BoatsDetails table
.Cascade.All();
}
}
public class VesselDetailMap:ClassMap<VesselDetail>
{
public VesselDetailMap()
{
WithTable("BoatsDetails");
Id(x => x.VesselDetailId, "Id");
//...
}
}
</code></pre>
| <p>It seems I was missing some fundamental NHibernate skills. Reading a little bit up on this it seems you need to let the child object be responsible for the one-to-many relation.</p>
<p>This fixed the problem for me:</p>
<pre><code>public class VesselMap: ClassMap<Vessel>
{
public VesselMap()
{
//...
HasMany(x => x.Details)
.Inverse()
.WithKeyColumn("BoatId");
}
}
public class VesselDetailMap:ClassMap<VesselDetail>
{
public VesselDetailMap()
{
//..
References(x => x.Vessel, "BoatId")
.Cascade
.SaveUpdate();
}
}
</code></pre>
|
Is it a good idea to store serialized objects in a Database instead of multiple xml text files? <p>I am currently working on a web application that requires certain requests by users to be persisted. I have three choices:</p>
<ol>
<li>Serialize each request object and store it as an xml text file.</li>
<li>Serialize the request object and store this xml text in a DB using CLOB.</li>
<li>Store the requests in separate tables in the DB.</li>
</ol>
<p>In my opinion I would go for option 2 (storing the serialized objects' xml text in the DB). I would do this because it would be so much easier to read from 1 column and then deserialize the objects to do some processing on them. I am using c# and asp .net MVC to write this application. I am fairly new to software development and would appreciate any help I can get. </p>
| <p>Short answer: If option 2 fits your needs well, use it. There's nothing wrong with storing your data in the database.</p>
|
DataGridView Value appearing as 1,000 when I would like it to appear as 1000 <p>I have a <code>DataGridView</code> and I am writing integers in to one of the columns, I would like these values not to have a comma in them when the value >= 1000. But at the moment, when i enter a value which is >= 1000 they appear in the form '1,000', the comma could be translated incorrectly in certain areas so I would prefer it to just appear as '1000'. Is there any formatting of the <code>DataGridViewColumn</code> that will stop this.</p>
| <blockquote>
<p>the comma could be translated
incorrectly in certain areas</p>
</blockquote>
<p>If you mean "certain countries/locales" by that then this is incorrect. Your numbers are being formatted according to the rules of the current user's locale, so a comma in one locale would become a dot in other etc.
Other than that specify "D" or "d" as DataFormatString to format it without any punctuation.</p>
|
Is there anything like IPython / IRB for Perl? <p>I've grown accustomed to using IPython to try things out whilst learning Python, and now I have to learn Perl for a new job. </p>
<p>Is there anything out there like IPython for Perl? In particular, I'm interested in completion and access to help.</p>
| <p>I usually just use <code>perl -de0</code>, but I've heard of:</p>
<ul>
<li><a href="http://search.cpan.org/perldoc?Devel%3A%3AREPL">Devel::REPL</a></li>
<li><a href="http://www.sukria.net/perlconsole.html">perlconsole</a></li>
</ul>
|
Generate Images for formulas in Java <p>I'd like to generate an image file showing some mathematical expression, taking a String like "(x+a)^n=â_(k=0)^n" as input and getting a more (human) readable image file as output. AFAIK stuff like that is used in Wikipedia for example. Are there maybe any java libraries that do that?</p>
<p>Or maybe I use the wrong approach. What would you do if the requirement was to enable pasting of formulas from MS Word into an HTML-document? I'd ask the user to just make a screenshot himself, but that would be the lazy way^^</p>
<p>Edit: Thanks for the answers so far, but I really do not control the input. What I get is some messy Word-style formula, not clean latex-formatted one.</p>
<p>Edit2: <a href="http://www.panschk.de/text.tex" rel="nofollow">http://www.panschk.de/text.tex</a>
Looks a bit like LaTeX doesn't it? That's what I get when I do
<code>clipboard.getContents(RTFTransfer.getInstance())</code> after having pasted a formula from Word07.</p>
| <p>First and foremost you should familiarize yourself with <a href="http://en.wikipedia.org/wiki/TeX" rel="nofollow">TeX</a> (and <a href="http://en.wikipedia.org/wiki/LaTeX" rel="nofollow">LaTeX</a>) - a famous typesetting system created by Donald Knuth. Typesetting mathematical formulae is an advanced topic with many opinions and much attention to detail - therefore use <a href="http://schmidt.devlib.org/java/libraries-dvi.html" rel="nofollow">something that builds upon TeX</a>. That way you are sure to get it right ;-)</p>
<p><strong>Edit:</strong> Take a look at <a href="http://en.wikipedia.org/wiki/Texvc" rel="nofollow">texvc</a></p>
<p>It can output to PNG, HTML, MathML. Check out the <a href="http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/math/README?view=markup" rel="nofollow">README</a></p>
<p><strong>Edit #2</strong> Convert that messy <a href="http://www.tug.org/utilities/texconv/pctotex.html" rel="nofollow">Word-stuff to TeX</a> or MathML?</p>
|
How do I upper case an email address? <p>I expect this should be a pretty easy question. It is in two parts:</p>
<ol>
<li>Are email addresses case sensitive? (i.e. is foo@bar.com different from Foo@bar.com?)</li>
<li>If so, what is the correct locale to use for capitalising an email address? (i.e. capitalising the email tim@foo.com would be different in the US and Turkish locales)</li>
</ol>
| <p>Judging from the specs the first part <em>can</em> be case sensitive, but normally it's not.<br>
Since it's all ASCII you should be safe using a "naive" uppercase function. </p>
<p>Check out the <a href="http://en.wikipedia.org/wiki/E-mail_address#RFC_specification" rel="nofollow">RFC spec part of the wikipedia article on E-mail adresses</a></p>
<p>If you're in for some heavier reading <a href="http://tools.ietf.org/html/rfc5322" rel="nofollow">RFC5322</a> and <a href="http://tools.ietf.org/html/rfc5321" rel="nofollow">RFC5321</a> should be useful too.</p>
|
Cannot locate 'org.springframework.security.annotation.Jsr250MethodDefinitionSource' <p>When I configure method security under Spring Security I get the error shown above (see stack trace below). I am running Spring 2.5.6, Spring Security 2.0.4 under Eclipse 3.4 with a Tomcat 6 runtime. I need any suggestion as to what to look at to get this working.</p>
<p>My security configuration file is as follows:</p>
<pre><code><beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">
<http auto-config='true'>
<intercept-url pattern="/**" access="ROLE_USER" />
</http>
<authentication-provider>
<user-service>
<user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="user" password="user" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
<global-method-security jsr250-annotations="enabled"/>
</code></pre>
<p></p>
<p>And the exception stack trace:</p>
<pre><code> ERROR [2009-02-17 20:07:34,828] main org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Cannot locate 'org.springframework.security.annotation.Jsr250MethodDefinitionSource'
Offending resource: ServletContext resource [/WEB-INF/securityApplicationContext.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:72)
at org.springframework.security.config.GlobalMethodSecurityBeanDefinitionParser.validatePresent(GlobalMethodSecurityBeanDefinitionParser.java:47)
at org.springframework.security.config.GlobalMethodSecurityBeanDefinitionParser.registerAnnotationBasedMethodDefinitionSources(GlobalMethodSecurityBeanDefinitionParser.java:109)
at org.springframework.security.config.GlobalMethodSecurityBeanDefinitionParser.parse(GlobalMethodSecurityBeanDefinitionParser.java:56)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:69)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1297)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1287)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:135)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:92)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:507)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:92)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:422)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4342)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
</code></pre>
| <p>And I found the answer. For annotations you need the following jar in your classpath:</p>
<p>spring-security-core-tiger-2.0.4.jar</p>
|
URL Rewriting <p>i am using URL rewriting in my asp.net application using regx</p>
<p>virtual URL is</p>
<pre><code>/ProductDatabaseCMS/(?<category>\w*)/Product/(?<product>\w*)\.aspx
</code></pre>
<p>original URL is</p>
<pre><code>/ProductDatabaseCMS/Product.aspx?PROD_ID=${product}
</code></pre>
<p>application path is <code>~/ProductDatabaseCMS</code></p>
<p>my application has master page that uses style sheet and the path is</p>
<pre><code>~/App_Themes/Styles/Style_Sheet.css
</code></pre>
<p>i am requesting the URL</p>
<pre><code>/ProductDatabaseCMS/(?<category>\w*)/Product/(?<product>\w*)\.aspx
</code></pre>
<p>from one of the webpage of application using Hyperlink control but in that case stylesheet is not working for this page Because it is taking path</p>
<pre><code>~/ProductDatabaseCMS/(?<category>\w*)/Product/App_Themes/Styles/Style_Sheet.css
</code></pre>
<p>what i have to do in this case.</p>
| <p>If you use a relative URI to reference the external stylesheet, you have to consider this: Relative URIs are always resolved from a base URI which is the URI of the current resource if not declared otherwise.</p>
<p>So if you request <code>/foo/bar</code> and there is a relative URI reference <code>css/baz.css</code> in the HTML document, it would be resolved to <code>/foo/css/baz.css</code> as <code>/foo/bar</code> is the base URI.</p>
<p>To solve this problem you have two options:</p>
<ol>
<li>use absolute URIs or at least absolute paths to reference the resources (e.g. <code>/App_Themes/Styles/Style_Sheet.css</code>), or</li>
<li>set a suitable base URI using the <code>BASE</code> HTML element (e.g. <code><base href="/"></code>) so that every relative URI is resolved from that new base URI.</li>
</ol>
|
SQL "group by" question - I can't select every column <p>I have a database where each row has an id, a URL, and an XML.
The IDs are unique, but URLs column can have duplicates.
I need all the URLs, without duplicates, and for each URL I need the id and XML.</p>
<p>If I ask only for the URL and the Id, I use the following query:</p>
<pre><code>select URL, max(ID) as ID from T1 group by URL
</code></pre>
<p>And all is working great.</p>
<p>But when I want also the XML, and I use the following query:</p>
<pre><code>select URL, max(ID) as ID, XML from T1 group by URL
</code></pre>
<p>I get the following error:</p>
<pre><code>ISC ERROR CODE:335544569
ISC ERROR MESSAGE:
Dynamic SQL Error
SQL error code = -104
user name required
</code></pre>
<p>What am I doing wrong?</p>
<p>Thanks,</p>
<p>Dikla</p>
<p>Thanks for the answers. I want to add an explanation:<br />
In case of duplicate URLs, I don't care which of them will be returned.
But I need to get them without duplicates, even if the XML is different between the rows.
Is it possible?<br />
Thanks!</p>
| <pre><code>select id, url, xml
from table1
where id in (
select min(id)
from table1
group by url)
</code></pre>
<p>would give you rows with duplicate urls removed (and only the first instance of duplicate urls included)</p>
|
HttpContext.Current accessed in static classes <p>Can I call <code>HttpContext.Current</code> from within a static class and Method?</p>
<p>I want to store a value on a per-user basis but want to be able to access it in a static manner.</p>
<p>e.g. Will this work?</p>
<pre><code>public static class StaticClass
{
public static string SomeThing
{
get { return HttpContext.Current.Items["SomeItem"].ToString(); }
}
}
</code></pre>
| <p>Yes thats one way in which it is helpful, of course the thread on which it is called must currently be processing a request to make it useful.</p>
|
Does the Google Ad javascript really need to be in the HEAD tag? <p>The google ad manager help site is pretty prescriptive about how the calls to their Javascript API need to be made and how combining blocks of javascript calls could cause code to break.</p>
<p>(<a href="http://www.google.com/admanager/help/en_US/tips/tagging.html" rel="nofollow">http://www.google.com/admanager/help/en_US/tips/tagging.html</a>)</p>
<p>I don't really like the idea of inserting so much JS in the head of my pages. I would prefer it to be inserted at the bottom of the page and wrapped in a <code>document.ready()</code> call.</p>
<p>Have others had any success moving away from the very specific way that Google prescribes?</p>
| <p>Have done the move with the Google Ad section outside of HEAD and just in the BODY part itself. Really doesn't make a difference since when it was moved, it was just right after the parameters used for the ads to display.</p>
<p>Probably has more to do with trying to have the script loaded before the necessary hooks on the page want to try and call or use any of the functions included in the script file. </p>
<p>From the tagging guide you mention: </p>
<blockquote>
<p><strong>JavaScript tags occur out of sequence</strong></p>
<p>This error indicates that calls to Ad Manager JavaScript functions do not occur in the proper sequence. This error may prevent ads from appearing. It may also cause Ad Manager to fetch the wrong ads; for example, if you fetch ads for the page before specifying page-level attributes for the page, you may fetch ads that do not factor in the targeting criteria.</p>
</blockquote>
<p>This may be why they're trying to be prescriptive about where to place the code.</p>
|
jquery session - dynamic variable naming <p>just having a problem here.
i'm doing the UI of a web-based app using jquery, css.
there's a shopping a cart, and i want to store the selected items in the session, i used jquery.session plugin.
e.g. <code>var $.session("var1","item1");</code></p>
<p>What i want is to dynamically store items into dynamically named variables.
how could i do that?</p>
<p>thanks.</p>
| <p>If there's a shopping cart, that data should be handled by a server side scripting language like PHP. I'm assuming at the end they will be charged via credit card? This kind of data needs to be secure.</p>
<p>In addition, that's a pretty big part of functionality to be handled by a non-secure client-side language like JS that can be turned off.</p>
<p>Just something to think about in the future..</p>
|
How to get raw query that the ODBC driver tries to execute? <p>I'm using C++ to query a SQL Server 2005 database using ODBC. The queries contain parameters that I set using SQLSetParam(). I run the queries by calling SQLExecute().</p>
<p>Occasionally a query will fail, and I need to log the context of the failure. I am calling SQLError() to get the error information, but I would also like to log the raw query that the ODBC driver tried to run - that is, the query with the parameter values expanded-out. Can anyone advise if there is a way to get access to this?</p>
<p>The context is error logging in a production environment. I'm not "there" when the error happens, so I can't use the profiler or similar tools. Thats why I want to log as much information as possible for analysis later.</p>
| <p>You can enable ODBC tracing on the client via the control panel, but be prepared for a major performance hit and some very large log files to read. </p>
|
Is F# a usable language for .net windows development <p>I have been hearing about F# and Microsoft now have a guy who is blogging and coding away in redmond somewhere about it. Can you really write GUI code from F# (I'd love to see an example of say adding a button to a form and subscribing to the onclick event for instance)</p>
<p>Does F# have full access to all of .Net?</p>
<p>I'm honestly curious and I know I could google but I'd love to hear from someone who is really using the language.</p>
| <p>Yes, you can certainly write WinForms apps - although you wouldn't override the OnClick method, you'd subscribe to the Click event.</p>
<p>Yes, F# has full access to .NET, although you won't get very idiomatic functional code if you use a lot of mutable types.</p>
<p><a href="http://tomasp.net/">Tomáš PetÅÃÄek's F# web site</a> has sample source code from his book (disclaimer: I'm involved with the book too, so I'm clearly biased) which has WinForms examples.</p>
|
ServiceContainer, IoC, and disposable objects <p>I have a question, and I'm going to tag this <em>subjective</em> since that's what I think it evolves into, more of a discussion. I'm hoping for some good ideas or some thought-provokers. I apologize for the long-winded question but you need to know the context.</p>
<p>The question is basically:</p>
<ul>
<li>How do you deal with concrete types in relation to IoC containers? Specifically, who is responsible for disposing them, if they require disposal, and how does that knowledge get propagated out to the calling code?</li>
</ul>
<p>Do you require them to be IDisposable? If not, is that code future-proof, or is the rule that you cannot use disposable objects? If you enforce IDisposable-requirements on interfaces and concrete types to be future-proof, whose responsibility is objects injected as part of constructor calls?</p>
<p><hr /></p>
<p><strong>Edit</strong>: I accepted the answer by <a href="http://stackoverflow.com/users/18782/chris-ballard">@Chris Ballard</a> since it's the closest one to the approach we ended up with.</p>
<p>Basically, we always return a type that looks like this:</p>
<pre><code>public interface IService<T> : IDisposable
where T: class
{
T Instance { get; }
Boolean Success { get; }
String FailureMessage { get; } // in case Success=false
}
</code></pre>
<p>We then return an object implementing this interface back from both .Resolve and .TryResolve, so that what we get in the calling code is always the same type.</p>
<p>Now, the object implementing this interface, <code>IService<T></code> is IDisposable, and should <em>always</em> be disposed of. It's not up to the programmer that resolves a service to decide whether the <code>IService<T></code> object should be disposed or not.</p>
<p>However, and this is the crucial part, whether the service instance should be disposed or not, that knowledge is baked into the object implementing <code>IService<T></code>, so if it's a factory-scoped service (ie. each call to Resolve ends up with a new service instance), then the service instance will be disposed when the <code>IService<T></code> object is disposed.</p>
<p>This also made it possible to support other special scopes, like pooling. We can now say that we want minimum 2 service instances, maximum 15, and typically 5, which means that each call to .Resolve will either retrieve a service instance from a pool of available objects, or construct a new one. And then, when the <code>IService<T></code> object that holds the pooled service is disposed of, the service instance is released back into its pool.</p>
<p>Sure, this made all code look like this:</p>
<pre><code>using (var service = ServiceContainer.Global.Resolve<ISomeService>())
{
service.Instance.DoSomething();
}
</code></pre>
<p>but it's a clean approach, and it has the same syntax regardless of the type of service or concrete object in use, so we chose that as an acceptable solution.</p>
<p><hr /></p>
<p><strong>Original question follows, for posterity</strong></p>
<p><hr /></p>
<p><strong>Long-winded question comes here:</strong></p>
<p>We have a IoC container that we use, and recently we discovered what amounts to a problem.</p>
<p>In non-IoC code, when we wanted to use, say, a file, we used a class like this:</p>
<pre><code>using (Stream stream = new FileStream(...))
{
...
}
</code></pre>
<p>There was no question as to whether this class was something that held a limited resource or not, since we knew that files had to be closed, and the class itself implemented IDisposable. The rule is simply that every class we construct an object of, that implements IDisposable, has to be disposed of. No questions asked. It's not up to the user of this class to decide if calling Dispose is optional or not.</p>
<p>Ok, so on to the first step towards the IoC container. Let's assume we don't want the code to talk directly to the file, but instead go through one lay | <p>One option might be to go with a factory pattern, so that the objects created directly by the IoC container never need to be disposed themselves, eg</p>
<pre><code>IBinaryDataProviderFactory factory =
ServiceContainer.Global.Resolve<IBinaryDataProviderFactory>();
using(IBinaryDataProvider provider = factory.CreateProvider())
{
...
}
</code></pre>
<p>Downside is added complexity, but it does mean that the container never creates anything which the developer is supposed to dispose of - it is always explicit code which does this.</p>
<p>If you really want to make it obvious, the factory method could be named something like CreateDisposableProvider().</p>
|
Can I pretty-print the DBIC_TRACE output in DBIx::Class? <p>Setting the DBIC_TRACE environment variable to true:</p>
<pre><code>BEGIN { $ENV{DBIC_TRACE} = 1 }
</code></pre>
<p>generates very helpful output, especially showing the SQL query that is being executed, but the SQL query is all on one line.</p>
<p>Is there a way to push it through some kinda "sql tidy" routine to format it better, perhaps breaking it up over multiple lines? Failing that, could anyone give me a nudge into where in the code I'd need to hack to add such a hook? And what the best tool is to accept a badly formatted SQL query and push out a nicely formatted one?</p>
<p>"nice formatting" in this context simply means better than "all on one line". I'm not particularly fussed about specific styles of formatting queries</p>
<p>Thanks!</p>
| <p><a href="http://blog.afoolishmanifesto.com/archives/1444">As of DBIx::Class 0.08124 it's built in.</a></p>
<p>Just set <code>$ENV{DBIC_TRACE_PROFILE}</code> to <code>console</code> or <code>console_monochrome</code>.</p>
|
YUI 3 Chaining <p>YUI 3 allows you to write<br />
<code>Y.all(".foo").removeClass("bar");</code></p>
<p>However it does not allow writing<br />
<code>Y.all(".foo").removeClass("bar").set("innerHTML", "baz");</code></p>
<p>It seems all the "operational" methods always terminate the call chain.<br />
This means YUI 3 only provides half the power of chaining that jQuery provides.</p>
<p>Does anyone know why this is, and if there is a way around it?</p>
| <p>It seems that because Y.all returns a list of things, after doing removeClass, an array of objects gets returned, not the Node object.</p>
<p>If, however, you use</p>
<pre><code>Y.get("#foo").removeClass("bar").set("innerHTML", "baz");
</code></pre>
<p>everything works as you expect, because it's working on a single object.</p>
<p>Perhaps you should tell this to the YUI folks and see about <a href="http://developer.yahoo.com/yui/articles/reportingbugs/" rel="nofollow">reporting a bug</a>. Maybe this is expected behavior, but I think what you want to do is way more powerful.</p>
|
Recommendations for Java + OpenPGP? <p>I want to develop a small OpenPGP client and I'm searching for a Java library for OpenPGP.</p>
<p>Are there any (open source) recommendations for this approach?</p>
<p><a href="http://www.cryptix.org/" rel="nofollow">Cryptix.org</a> does not seem alive anymore...</p>
| <p>I found the <a href="http://www.bouncycastle.org">BouncyCastle</a> library, for Java and C#. I haven't any experiences with it. I will try it and report here.</p>
<p>It provides:</p>
<ol>
<li>A lightweight cryptography API for Java and C#.</li>
<li>A provider for the Java Cryptography Extension and the Java Cryptography Architecture.</li>
<li>A clean room implementation of the JCE 1.2.1.</li>
<li>A library for reading and writing encoded ASN.1 objects.</li>
<li>A light weight client-side TLS API.</li>
<li>Generators for Version 1 and Version 3 X.509 certificates, Version 2 CRLs, and PKCS12 files.</li>
<li>Generators for Version 2 X.509 attribute certificates.</li>
<li>Generators/Processors for S/MIME and CMS (PKCS7/RFC 3852).</li>
<li>Generators/Processors for OCSP (RFC 2560).</li>
<li>Generators/Processors for TSP (RFC 3161).</li>
<li>Generators/Processors for OpenPGP (RFC 2440).</li>
<li>A signed jar version suitable for JDK 1.4-1.6 and the Sun JCE.</li>
</ol>
<p>(from BouncyCastle.org)</p>
|
Python list serialization - fastest method <p>I need to load (de-serialize) a pre-computed list of integers from a file in a Python script (into a Python list). The list is large (upto millions of items), and I can choose the format I store it in, as long as loading is fastest.</p>
<p>Which is the fastest method, and why?</p>
<ol>
<li>Using <code>import</code> on a .py file that just contains the list assigned to a variable</li>
<li>Using <code>cPickle</code>'s <code>load</code></li>
<li>Some other method (perhaps <code>numpy</code>?)</li>
</ol>
<p>Also, how can one benchmark such things reliably?</p>
<p><strong>Addendum:</strong> measuring this reliably is difficult, because <code>import</code> is cached so it can't be executed multiple times in a test. The loading with pickle also gets faster after the first time probably because page-precaching by the OS. Loading 1 million numbers with <code>cPickle</code> takes 1.1 sec the first time run, and 0.2 sec on subsequent executions of the script.</p>
<p>Intuitively I feel <code>cPickle</code> should be faster, but I'd appreciate numbers (this is quite a challenge to measure, I think). </p>
<p>And yes, it's important for me that this performs quickly.</p>
<p>Thanks</p>
| <p>I would guess <a href="http://docs.python.org/library/pickle.html#module-cPickle" rel="nofollow">cPickle</a> will be fastest if you really need the thing in a list.</p>
<p>If you can use an <a href="http://docs.python.org/library/array.html" rel="nofollow">array</a>, which is a built-in sequence type, I timed this at a quarter of a second for 1 million integers:</p>
<pre><code>from array import array
from datetime import datetime
def WriteInts(theArray,filename):
f = file(filename,"wb")
theArray.tofile(f)
f.close()
def ReadInts(filename):
d = datetime.utcnow()
theArray = array('i')
f = file(filename,"rb")
try:
theArray.fromfile(f,1000000000)
except EOFError:
pass
print "Read %d ints in %s" % (len(theArray),datetime.utcnow() - d)
return theArray
if __name__ == "__main__":
a = array('i')
a.extend(range(0,1000000))
filename = "a_million_ints.dat"
WriteInts(a,filename)
r = ReadInts(filename)
print "The 5th element is %d" % (r[4])
</code></pre>
|
Bash script does not continue to read the next line of file <p>I have a shell script that saves the output of a command that is executed to a CSV file. It reads the command it has to execute from a shell script which is in this format:</p>
<pre><code>ffmpeg -i /home/test/videos/avi/418kb.avi /home/test/videos/done/418kb.flv
ffmpeg -i /home/test/videos/avi/1253kb.avi /home/test/videos/done/1253kb.flv
ffmpeg -i /home/test/videos/avi/2093kb.avi /home/test/videos/done/2093kb.flv
</code></pre>
<p>You can see each line is an ffmpeg command. However, the script just executes the first line. Just a minute ago it was doing nearly all of the commands. It was missing half for some reason. I edited the text file that contained the commands and now it will only do the first line. Here is my bash script:</p>
<pre><code>#!/bin/bash
# Shell script utility to read a file line line.
# Once line is read it will run processLine() function
#Function processLine
processLine(){
line="$@"
START=$(date +%s.%N)
eval $line > /dev/null 2>&1
END=$(date +%s.%N)
DIFF=$(echo "$END - $START" | bc)
echo "$line, $START, $END, $DIFF" >> file.csv 2>&1
echo "It took $DIFF seconds"
echo $line
}
# Store file name
FILE=""
# get file name as command line argument
# Else read it from standard input device
if [ "$1" == "" ]; then
FILE="/dev/stdin"
else
FILE="$1"
# make sure file exist and readable
if [ ! -f $FILE ]; then
echo "$FILE : does not exists"
exit 1
elif [ ! -r $FILE ]; then
echo "$FILE: can not read"
exit 2
fi
fi
# read $FILE using the file descriptors
# Set loop separator to end of line
BAKIFS=$IFS
IFS=$(echo -en "\n\b")
exec 3<&0
exec 0<$FILE
while read line
do
# use $line variable to process line in processLine() function
processLine $line
done
exec 0<&3
# restore $IFS which was used to determine what the field separators are
BAKIFS=$ORIGIFS
exit 0
</code></pre>
<p>Thank you for any help.</p>
<h2>UPDATE 2</h2>
<p>Its the ffmpeg commands rather than the shell script that isn't working. But I should of been using just "\b" as Paul pointed out. I am also making use of Johannes's shorter script.</p>
| <p>I think that should do the same and seems to be correct:</p>
<pre><code>#!/bin/bash
CSVFILE=/tmp/file.csv
cat "$@" | while read line; do
echo "Executing '$line'"
START=$(date +%s)
eval $line &> /dev/null
END=$(date +%s)
let DIFF=$END-$START
echo "$line, $START, $END, $DIFF" >> "$CSVFILE"
echo "It took ${DIFF}s"
done
</code></pre>
<p>no?</p>
|
How to debug a "debug assertion failure" in VC++ 6 <p>I wonder how to debug the following error:</p>
<pre><code>Debug Assertion failure
Program: tomtoprog.exe
File: dbgheap.c
Line: 1044
Expression:_CrtIsValidHeapPointer(pUserData)
...
</code></pre>
<p>I'm quiet new to windows development with VC++ 6 ... is there a valgrind or something like that? The tomtoprog code is not written by me and its rather messy ... so something like valgrind would make my life way easier ...</p>
<p>Thanks in advance!</p>
<p>Best regards,</p>
<p>Zhengtonic</p>
| <p>It looks like you either have heap corruption or you are doing a double free of the same pointer. If you break into the debugger what is the last line of your code that is being called when the assert occurs?</p>
<p>The best way to check for issues like this is to use a page heap verifier like <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;286470" rel="nofollow">PageHeap.exe</a></p>
<p>Also see this related question on stack overflow</p>
<p><a href="http://stackoverflow.com/questions/1069/heap-corruption-under-win32-how-to-locate">http://stackoverflow.com/questions/1069/heap-corruption-under-win32-how-to-locate</a></p>
|
XSLT: sum of tree fragment will always return 0 ! <p>I am stuck with a problem which seems stupid but I cannot find out the solution... With XLST, I need to sum a list of values calculated by a template. So I stored these values in a tree structure (a list of "Number" elements contained in a root element "Numbers"). But whatever I try to do with this self-made list, it will return either nothing, 0 or an error...</p>
<p>Does someone know what I am doing wrong ?</p>
<pre><code><!-- create the tree fragment -->
<xsl:variable name="_subTotals">
<Numbers>
<xsl:for-each select="List">
<xsl:variable name="_Size">
<xsl:call-template name="GetSize">
<xsl:with-param name="_value" select="@value"/>
</xsl:call-template>
</xsl:variable>
<Number>
<xsl:value-of select="$_Size"/>
</Number>
</xsl:for-each>
</Numbers>
</xsl:variable>
<!-- this returns an error: expression must result into a node-set -->
<xsl:message terminate="no">
<xsl:value-of select="sum($_subTotals/Numbers/Number)"/>
</xsl:message>
<!-- transform the tree fragment into a node-set
<xsl:variable name="_Total" select="msxsl:node-set($_subTotals)"/>
<!-- returns nothing -->
<xsl:for-each select="$_Total/Numbers/Number">
<xsl:message terminate="no">
<xsl:value-of select="@value"/>
</xsl:message>
</xsl:for-each>
<!-- returns 0 -->
<xsl:value-of select="sum($_Total/Numbers/Number)"/>
</code></pre>
| <p>Thank you very much Dimitre ! That's exactly what solved my problem : the X-Path expression I used in the sum function.</p>
<p>But why does this work :</p>
<pre><code><xsl:value-of select="sum($vNums/*/*)"/>
</code></pre>
<p>and not that :</p>
<pre><code><xsl:value-of select="sum($vNums/nums/num)"/>
</code></pre>
<p>?</p>
|
Where can I find an ICQ library for C#? <p>Is there any (preferably native) C# library which allows me to send some messages via the ICQ protocol? Is there something better than just wrapping libgaim or something?</p>
| <p>Perhaps this can help you out:</p>
<p><a href="http://sourceforge.net/projects/oscarlib/" rel="nofollow">http://sourceforge.net/projects/oscarlib/</a></p>
<p>Download the source and check the OscarLib. </p>
|
Bit Operation For Finding String Difference <p>The following string of mine tried to find difference between two strings.
But it's horribly slow as it iterate the length of string:</p>
<pre><code>#include <string>
#include <vector>
#include <iostream>
using namespace std;
int hd(string s1, string s2) {
// hd stands for "Hamming Distance"
int dif = 0;
for (unsigned i = 0; i < s1.size(); i++ ) {
string b1 = s1.substr(i,1);
string b2 = s2.substr(i,1);
if (b1 != b2) {
dif++;
}
}
return dif;
}
int main() {
string string1 = "AAAAA";
string string2 = "ATATT";
string string3 = "AAAAA";
int theHD12 = hd(string1,string2);
cout << theHD12 << endl;
int theHD13 = hd(string1,string3);
cout << theHD13 << endl;
}
</code></pre>
<p>Is there a fast alternative to do that?
In Perl we can have the following approach:</p>
<pre><code>sub hd {
return ($_[0] ^ $_[1]) =~ tr/\001-\255//;
}
</code></pre>
<p>which is much2 faster than iterating the position.</p>
<p>I wonder what's the equivalent of it in C++?</p>
| <p>Try to replace the for loop by:</p>
<pre><code>for (unsigned i = 0; i < s1.size(); i++ ) {
if (b1[i] != b2[i]) {
dif++;
}
}
</code></pre>
<p>This should be a lot faster because no new strings are created.</p>
|
Change the characters in mysql with Convert failing - Still getting Não <p>I am populating this mysql table with data from a php (via post and using filter_input).
The database is utf8 but when I have a user that inputs words with ^,',',~ like Não I get this -> Não</p>
<p>What do I have to do to make it show the correct values. Or should I try to make some correction when I retrieve the data??</p>
<p>UPDATE:</p>
<p>I have added a utf8_decode and now it is inserting ok.
Anyone know how to convert the string that were already in the table?? I tried using the convert function but I can't make it work :(</p>
<p>UPDATE:</p>
<p>I am trying this code:</p>
<blockquote>
<p>select convert(field using latin1)
from table where id = 35;</p>
</blockquote>
<p>And I am still getting this: Não
I tried other encoding s but I never get the word Não</p>
<p>Anyone have any thoughts on this one?? </p>
| <p>First, make sure your page is utf-8</p>
<pre><code><meta http-equiv="Content-type" content="text/html; charset=UTF-8"/>
</code></pre>
<p>next, if your on Apache, make sur your in UTF-8 in config file : </p>
<pre><code>AddDefaultCharset UTF-8
</code></pre>
<p>or your can do it in a .php file like this : </p>
<pre><code>header('Content-type: text/html; charset=UTF-8');
</code></pre>
<p>if you still have problem, you can use the encode function : </p>
<pre><code>$value = utf8_encode($value);
</code></pre>
<p>Hope all this will help...</p>
|
How to join strings in PHP? <p>I have three strings:</p>
<p>$str1 = "abc";
$str2 = "def";
$str3 = "ghi";</p>
<p>I can get the value of all of them like this:</p>
<p>echo "$str1$str2$str3";</p>
<p>But I heard there is a way to join them together, so I can echo all of them without quotes.</p>
| <p>As well as concatenating like this</p>
<pre><code>echo $str1 . $str2 . $str3;
</code></pre>
<p>You can also just output them in sequence, which avoids evaluating an intermediate string</p>
<pre><code>echo $str1 , $str2 , $str3;
</code></pre>
<p>Finally, you can use braces in string to disambiguate string replacement:</p>
<pre><code>echo "{$str1}{$str2}{$str3}";
</code></pre>
|
Should I Always Fully Qualify Column Names In SQL? <p>Out of interest when working with SQL statements should I always use the fully qualifed column name (tablename.columnname) even if only working with one table e.g.</p>
<pre><code>SELECT table.column1, table.column2 FROM table
</code></pre>
| <p>It's better if you do - it doesn't add any complexity, and it can prevent errors in the future.</p>
<p>But in a well-defined system, you shouldn't <em>have</em> to - it's like namespaces in programming languages. The ideal is not to have conflicts, but it can clutter the code with the superfluous use of explicit names.</p>
|
D programming language IRC library <p>Hey, I'm searching for a D IRC library. Yes I know there is <a href="http://www.dprogramming.com/dirclib.php" rel="nofollow">dirclib</a>, but this one unfortunately doesn't seem to be compatible with version 1 or 2 of the language (anymore). When I try to use it with the 2.014 alpha for Ubuntu it throws several errors.</p>
<p>Do you've got any ideas/advises?</p>
| <p>As a general statement, D2 is bleeding edge and therefore library support for it is very poor. Most libraries out there work with D1 and maybe have versions in testing for D2. If you want to use D for something that requires complex infrastructure like libraries and tools, I'd stick with D1 for now because the language spec has been reasonably stable for a while. dirclib apparently is a D1 lib, since it works with Tango, which is not ported to D2 yet. If you can try the latest D1 compiler (1.040) and be more specific about what doesn't work, I might be able to provide more advice.</p>
<p>Also, if you're going to use D2, the downloads page is way out of date. The latest version is 2.025, not 2.014, and can be found at ftp://ftp.digitalmars.com/.</p>
|
How to get the type of T from a generic List<T>? <p>Let say I have a <code>List<T> abc = new List<T>;</code> inside a class <code>public class MyClass<T>//...</code>. </p>
<p>Later, when I initialize the class, the <code>T</code> becomes <code>MyTypeObject1</code>. So I have a generic list, <code>List< MyTypeObject1 ></code>. </p>
<p>I would like to know, what type of object the list of my class contain, e.g. the list called <code>abc</code> contain what type of object? </p>
<p>I cannot do <code>abc[0].GetType();</code> because the list might contain zero elements. How can I do it?</p>
| <p>If I understand correctly, your list has the same type parameter as the container class itself. If this is the case, then:</p>
<pre><code>Type typeParameterType = typeof(T);
</code></pre>
<p>If you are in the lucky situation of having <code>object</code> as a type parameter, see Marc's answer.</p>
|
Django - having middleware communicate with views/templates <p>Alright, this is probably a really silly question but I am new to Python/Django so I can't really wrap my head around its scoping concepts just yet. Right now I am writing a <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/#topics-http-middleware">middleware</a> class to handle some stuff, and I want to set 'global' variables that my views and templates can access. What is the "right" way of doing this? I considered doing something like this:</p>
<h2>middleware.py</h2>
<pre><code>from django.conf import settings
class BeforeFilter(object):
def process_request(self, request):
settings.my_var = 'Hello World'
return None
</code></pre>
<h2>views.py</h2>
<pre><code>from django.conf import settings
from django.http import HttpResponse
def myview(request):
return HttpResponse(settings.my_var)
</code></pre>
<p>Although this works, I am not sure if it is the "Django way" or the "Python way" of doing this.</p>
<p>So, my questions are:<br />
1. Is this the right way?<br />
2. If it is the right way, what is the right way of adding variables that can be used in the actual template from the middleware? Say I want to evaluate something and I want to set a variable <code>headername</code> as 'My Site Name' in the middleware, and I want to be able to do <code>{{ headername }}</code> in all templates. Doing it the way I have it now I'd have to add <code>headername</code> to the context inside every view. Is there anyway to bypass this? I am thinking something along the lines of CakePHP's <code>$this->set('headername','My Site Name');</code><br />
3. I am using the middleware class as an equivalent of CakePHP's <code>beforeFilter</code> that runs before every view (or controller in CakePHP) is called. Is this the right way of doing this?<br />
4. Completely unrelated but it is a small question, what is a nice way of printing out the contents of a variable to the browser ala <code>print_r</code>? Say I want to see all the stuff inside the <code>request</code> that is passed into the view? Is <code>pprint</code> the answer?</p>
| <ol>
<li><p>It's not the best way. You could set my_var on the request rather than on the settings. Settings are global and apply to the whole site. You don't want to modify it for every request. There could be concurrency issues with multiple request updating/reading the variable at the same time.</p></li>
<li><p>To access request.my_var in your templates you could do <strong>{{ request.my_var }}</strong>. To get access to the request variable in your template you will have to add <strong>django.core.context_processors.request</strong> to your <strong>TEMPLATE_CONTEXT_PROCESSORS</strong> setting.</p></li>
<li><p>Yes. Other terminology to describe request middleware would be request pre-processor/filter/interceptor. </p></li>
</ol>
<p>Also, if you want to use a common Site name for the header in your templates, you might want to check out the Django Sites application which provides a site name variable for your use.</p>
|
Populate a form and print out document <p>I have a word document which is a blank form. I need to be able to fill it in programatically using .NET, and print out the result.</p>
<p>The form I have is a Word document, but I could obviously convert this to PDF if it is needed. </p>
| <p>Do you have Word document in Open XML format or is it in old binary format?</p>
<p>In Open XML this task can as easy as manipulation of XML inside a package (ZIP file).</p>
<p>If you have binary Word file this can be tricky. You will need to use .NET Programmability Support for Office and <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(VS.80).aspx" rel="nofollow">Microsoft.Office.Interop.Word namespace</a>.</p>
|
How can I trace IIS 500 errors thrown by my webservice <p>I have deployed a new version of an ASP.NET webservice. The IIS logfile reports an errorcode 500 when this service is being called by a client. My own (test) can use the service without any error. I have enabled errorlogging in my ASP.NET webservice, but no error is being logged, which leads me to believe the error is not thrown by my code, but somewhere 'earlier' in the stack. I have also examined the httperr1.log file but there's nothing relevant there.</p>
<p>Question, how can I add more errorlogging to IIS to investigate the error? I have no access to the client.</p>
<p>[Updates] I'm using IIS6. I've checked the eventlog and found nothing there.</p>
| <p>Which version of IIS are you using?</p>
<p>In IIS7 you have extensive tracing capabilities. </p>
<p>Take a look at: <a href="http://www.iis.net/learn/troubleshoot/using-failed-request-tracing/troubleshooting-failed-requests-using-tracing-in-iis" rel="nofollow">Troubleshooting Failed Requests Using Tracing in IIS 7.0</a></p>
|
Native looking GUI framework for Mac and Windows <p>I am currently searching for a GUI framework that looks and works native under Mac and Windows. Further I dont want to use C++ but e.g. C#, Java, Ruby or Python.</p>
<p>Thx a lot.</p>
| <p>Look at <a href="http://www.wxwidgets.org/">wxWidgets</a> or <a href="http://www.qtsoftware.com/products/">QT</a>.</p>
<p>However, consider that those toolkits will only get you an approximate platform look and feel. Usually, it feels "OK" on Windows, but on the Mac it typically looks and feels more like a "ported" Windows app than a native app. Demanding as Mac users are, they don't like that very much... Also, you are often limited to the common subset of the systems.</p>
<p>If you want to make a great app, consider separating your code into a platform-neutral business layer and a platform-specific GUI layer, and implement the GUI on each platform with the native tools for that platform. Yes, this will be more work, but depending on your goals may be worth it.</p>
|
What versioning design pattern would you recommend <p>I have a requirement to build 'versioning' into an application and was wondering how best to approach it. </p>
<p>I have this general pattern:</p>
<p>Model A has many B's</p>
<p>Where on update the attributes of A need to be versioned and its associated objects (B's) also need to be versioned. So the application will display the current version of A, but it must also be possible to view previous versions of A and its associated objects.</p>
<p>I would like to use a document store however this is only a portion of the application and having a doc store and a relation database would introduce more complexity. </p>
<p>I have considered using a star schema, but before I progress I was wondering if there is a design pattern floating around tackling this problem?</p>
<p>This question is slanted towards resolving the issue of storing the versions of an associated object in a relational database. Where there is an inherent need to be able to effectively query the data (ie serializing object won't suffice). </p>
<p>Update: What I was thinking/have implemented but want to see if the is "a better way"</p>
<pre><code>,---------. 1 * ,--------.
| Model A |----------| Model B|
`---------' `--------'
|PK | | a_id |
|b_version| |version |
|version | `--------'
`---------'
</code></pre>
<p>Where I would be duplicating model A and all the associated B's and incrementing the version attribute. Then doing a select to join the B's via b_version and b.version. Just wondering if this can be done better.</p>
| <p>I don't think there is no specific GoF design pattern per se for versioning because there exists many implementations of it. </p>
<p>The most simple implementation of versioning is a linked list of objects. Where each node in the list is a new revision of whatever the versionable object is. To save space you also implement some kind of a <a href="http://en.wikipedia.org/wiki/Diff">diff</a> that shows what the difference is between the revisions. That way you can store diffs in the database, but also the final version of the versionable object since the version control system should be able to derive the versions in between.</p>
<p>The database schema could principally look something like this (you can see this pattern in most wiki systems):</p>
<pre><code>+--------------------+ 1 * +-----------------------------+
| VersionableObject |---------| Diff |
+--------------------+ +-----------------------------+
| lastStateContent | | difference |
| originalAuthor | | revision |
| #dates and whatnot | | # userId, dates and whatnot |
+--------------------+ +-----------------------------+
</code></pre>
<p>If you want to go hardcore with branching and stuff you might want to consider have a look at <a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph">DAG</a> which is what modern distributed version control systems use.</p>
<p>Now if we talk about your example a whole slew of objects that needs to be saved in configurations. I.e. we have to pick out the revisions of objects that we want for the model. It means we have a many to many relationship (which is solved with an intermediary table), sort of like this:</p>
<pre><code>+---+ 1 * +---------------+ 1 * +-----------------+ * 1 +-------+
| B |-------| Diff |-------| ModelSelection |-------| Model |
+---+ +---------------+ +-----------------+ +-------+
| revisionNo | | {PK} configId |
| {FK} configId | | {FK} modelId |
+---------------+ +-----------------+
</code></pre>
<p>I hope this helps.</p>
|
develop own WORKFLOW <p>I m in an internship in an enterprise that wants to develop its own WORKFLOW, but they are only interested to "Time management" ..I am now understanding jBoss jbpm
so what do you think about that?
From where can I start in this project?
thanks</p>
| <p>Is this question inviting opinion? </p>
<p>Surely the best platforms and tools for developing and hosting workflows are relatively dependent upon the enterprise in question, their ability to maintain and support such systems etc etc, aren't they? </p>
<p>For example, lots of larger enterprises invest heavily in Microsoft platforms, which also means they have more experience supporting those kinds of platforms and services. So, with this in mind, and in the interest of maintainability, supportability, I would choose Windows Workflow Foundation, which is incredibly comprehensive and extremely easy to integrate into Microsoft platforms.</p>
<p>If you were going to start looking into WWF then I can definitely recommend Pro WF, written by Bruce Bukovics and published by Apress (http://www.amazon.co.uk/Pro-WF-Windows-Workflow-NET/dp/1430227214/ref=sr_1_1?ie=UTF8&qid=1289905106&sr=8-1)</p>
<p>If you are going the JBoss jBPM route, there's a whole site dedicated to it - including documentation, user and developer forums, and a wiki full of useful information. (http://jboss.org/jbpm)</p>
<p>First start by understanding the environment, the business processes and the way in which users interact with those processes. Only then can you really start designing workflows that will be of any use.</p>
|
I am getting a blank page while deploying MVC application on IIS <p>I am currently deploying my application built using RC of MVC ASP.NET on the production server which is showing nothing now.
The routes in my global.ascx are typical i.e. </p>
<pre><code>routes.MapRoute(
"Default", // Route name
"{controller}.aspx/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute(
"Root",
"",
new { controller = "Home", action = "Index", id = "" }
);
</code></pre>
<p>Can any one figure out why it is showing me only blank pages</p>
<p>Sorry i forget to mention the it is IIS 6 </p>
<p><strong>Interestingnly it is also working on my local IIS (i.e. both local built in with VS & standard with XP) as well</strong></p>
| <p>You will also get a blank page when you have error handling setup in your global.asax and something generic is wrong (like an assembly that could not be found).</p>
<p>When you disable it in the global.asax, you can see the server error.
Don't forget to enable it again after fixing those initial bugs.</p>
<pre><code>protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "ErrorController");
routeData.Values.Add("action", "HandleTheError");
routeData.Values.Add("error", exception);
Response.Clear();
Server.ClearError();
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(
new HttpContextWrapper(Context), routeData));
}
</code></pre>
|
Raising Events From Interface (win forms) <p>My scenario:</p>
<p>Windows Forms Application with a base master (mdi) form.</p>
<p>An Interface that has an event:</p>
<pre><code>Public Interface IDoSomething
Event AddFilter()
</code></pre>
<p>Modal popup window implements the interface and decalres event: </p>
<pre><code>Public Class frmPopup Implements IDoSomething
Public Event AddFilter() Implements IDoSomething.AddFilter
</code></pre>
<p>Popup also contains code to fire the event: </p>
<pre><code>RaiseEvent AddFilter()
</code></pre>
<p>Base master form contains code that discovers and launches popup forms that implement a specified interface.</p>
<p>A form in the application launches the popup (that implements the interface) and handle any events that it fires. So I have the following code in the form:</p>
<pre><code>Public Class frmMyForm
Public WithEvents m_Popup As IDoSomething
Public Sub m_Popup_AddFilter() Handles m_Popup.AddFilter
MsgBox("I'm in")
End Sub
</code></pre>
<p>The code is all working, up until the stage where the event is fired. The popup loads without any issues but when the event fires it seems to drop off the face of the earth and is not being picked up by the main form - frmMyForm. I suspect it may have something to do with the way the popup form is being launched from the base master form via the discovery of the interface. </p>
<p>ADDITIONAL CODE - to expand on "Base master form contains code that discovers and launches popup forms that implement a specified interface":</p>
<p>The idea of the popup forms that are being used is to return a business object to the form that opened it using events. The popup form Interface (IDoSomething) inherits another interface - IBusinessObjectSelector which specifies that the form will return a business object.</p>
<p>So the function in the base master form is:</p>
<pre><code>Public Function GetBusinessObjectUsingPopup(Of O, F As IBusinessObjectSelector)
(ByRef dicPropertyValues As Dictionary(Of String, Object),
Optional ByVal titleText As String = "")
As O Implements IBaseMasterForm.GetBusinessObjectUsingPopup
Dim objBusinessObjectSelector As IBusinessObjectSelector = GetPopup(Of F)(False)
objBusinessObjectSelector.InitialiseForm()
' Activate and show the dialog
If objBusinessObjectSelector.ShowPopup() <> Windows.Forms.DialogResult.OK Then
' The user cancelled the load, so just exit
Return Nothing
End If
GetBusinessObjectUsingPopup = CType(objBusinessObjectSelector.SelectedBusinessObject, O)
End Function
</code></pre>
<p>And Popup Code:</p>
<pre><code>Public Function GetPopup(Of F As IBasePopupChildForm)
(Optional ByVal initialisePopupPriorToReturn As Boolean = True) As F
Implements IBaseMasterForm.GetPopup
Dim lstIBasePopupChildForm As List(Of F) = GetInterfaces(Of F)()
lstIBasePopupChildForm(0).MyIBaseMasterForm = Me
If initialisePopupPriorToReturn Then
lstIBasePopupChildForm(0).InitialiseForm()
End If
Return lstIBasePopupChildForm(0)
End Function
</code></pre>
<p>Note - GetInterfaces(Of F)() simply scans the assembly and returns a list of forms that implement the required interface. Some validation has been chopped out that returns messages if multiple forms that implement the interface are found.</p>
| <p>The critical part is initializing m_Popup correctly. You haven't said anything about that. Some sample code:</p>
<p>Form2:</p>
<pre><code>Public Class Form2
Implements IDoSomething
Public Event AddFilter() Implements IDoSomething.AddFilter
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
RaiseEvent AddFilter()
End Sub
End Class
Public Interface IDoSomething
Event AddFilter()
End Interface
</code></pre>
<p>Form1:</p>
<pre><code>Public Class Form1
Private WithEvents mPopup As IDoSomething
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim f2 As New Form2
f2.Show(Me)
mPopup = f2
End Sub
Private Sub mPopup_AddFilter() Handles mPopup.AddFilter
MsgBox("yada")
End Sub
End Class
</code></pre>
<p>The mPopup = f2 statement in this code is key.</p>
|
Clickonce Upgrade and application setting <p>We have a winform application deplyed using Clickonce which has a configuration file. </p>
<p>What we need is when there is an upgrade available, to merge the configuration in local machine with what is coming from the deplyoment.</p>
<p>Any ideas or experiences?</p>
| <p>There's an Upgrade method on Properties.Settings.Default that is supposed to do that if you call it before you access any of the settings.</p>
|
Find the unix platform name <p>I want to be able to determine the output folder based on the platform name: AS3, AS4, AS5, SUN. </p>
<p>I couldn't figure out how to extract the platform name from the system. I experimented with:</p>
<pre><code>uname -a
file /bin/bash
</code></pre>
<p>Thanks</p>
<p><strong>Solution</strong></p>
<p>./lsb_release -a</p>
<p>Kudos to Paul Dixon</p>
| <p>I think you'll have to look in a specific file for each OS. For example, on SunOS, you can type:</p>
<pre><code>uname -s -r -v
</code></pre>
<p>For RHEL, check <code>/etc/issue</code>.</p>
|
Does linq to sql automatically lazy load associated entities? <p>Does linq to sql automatically lazy load associated entities?</p>
<p>I would think it would but I can't find an article stating it as such.</p>
| <p>It depends how you define "lazy-load".</p>
<p>If you say</p>
<pre><code>var person = (from p in db.People
where p.PersonId = pid
select p).First();
var spouse = person.Spouse; // based on the SpouseId FK
// back into the People table.
</code></pre>
<p>Then that would be precisely "lazying loading" as the second object is not pulled from the database until it is referenced. This however, will require two database queries.</p>
<p>However, if you were to say,</p>
<pre><code>var family = (from p in db.People
where p.PersonId = pid
select new
{
Name = p.Name,
SpouseName = p.Spouse.Name
}).First();
</code></pre>
<p>Then Linq will automatically do the join and load the information from both records in a single database query.</p>
|
Why can't I do ??= in C#? <p>I often find myself doing:</p>
<pre><code>foo = foo ?? x;
</code></pre>
<p>Why can't I do:</p>
<pre><code>foo ??= x;
</code></pre>
<p><strong>Edit</strong>: I know it's not part of the language... My question is "why not"? I find the necessity to repeat "foo" to be unpleasing and potentially error-prone. It looks just as ugly as:</p>
<pre><code>foo = foo + x;
</code></pre>
| <p>When I think about it, </p>
<pre><code>foo = foo ?? x
</code></pre>
<p>is really just </p>
<pre><code>foo = foo != null ? foo : x
</code></pre>
<p>and at that point, the analogy to += starts to fall apart.</p>
|
How to update Dynamic Resource within a Dynamic Resource? <p>I have a visual brush which is a group of shapes, the main colour of which is a dynamic resource itself - so the shape is for example MyShape and the Colour, MyColour which is referenced by the Shape object.<br />
My problem is when I update the colour for this - it only happens the first time the shape is loaded (the colour needs to be set first) however as much as I change the colour it won't update the dynamic resource that uses the colour - how do I make this work?<br />
Just need to make a dynamic resource work within another dynamic resource and have them both update when I change the colour.<br />
I have no idea how to get this to work - I spent time creating a colour-picker for WPF only to find I cannot change the colour of this item - 1-Tier resources work where I set the brush/colour directly but not a colour within another object or 2-Tier Resource.</p>
<p>Edit: My problem seems to be specific to using these in a seperate Resource / Dictionary as my program needs to access this item from a class not the Window, the main example mentioned does not work when the MyColor is in a seperate Resource.</p>
| <p>Unless I misunderstand the situation, exactly what you're talking about works pretty well. I just tried it out with this Xaml:</p>
<pre><code><Window x:Class="ConditionalTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<SolidColorBrush x:Key="MyColor" Color="Aqua" />
<VisualBrush x:Key="MyBrush">
<VisualBrush.Visual>
<Ellipse Height="50" Width="100" Fill="{DynamicResource MyColor}" />
</VisualBrush.Visual>
</VisualBrush>
</Window.Resources>
<Grid Background="{DynamicResource MyBrush}">
<Button Height="30" Width="Auto" VerticalAlignment="Center" HorizontalAlignment="Center" Content="ChangeColor" Click="Button_Click" />
</Grid>
</Window>
</code></pre>
<p>And then changed the color in the click handler for that button:</p>
<pre><code>private void Button_Click(object sender, RoutedEventArgs e)
{
((SolidColorBrush)Resources["MyColor"]).Color = Colors.Purple;
}
</code></pre>
<p>And it worked like a champ.</p>
|
Does `Using Namespace;` consume more memory? <p>Does <code>Using Namespace;</code> consume more memory?</p>
<p>I'm currently working on a mobile application and I was just curious if those unneeded using statements that visual studio places when creating a class make my application require some extra memory to run.</p>
| <p>To put it simply: no.</p>
<p>Those statements aren't translated into any form of IL. They're just shortcuts to avoid using (ugly!) fully qualified type names.
But, if you're using VS2008 and/or R# you can remove unused ones automagically.</p>
|
Best practices for DataBinding in asp.net for maintainability <p>I would like to know what are the best practices for using asp.net DataBinding, in terms of maintainability. </p>
<p>I don't want the application to fall appart when I have to make changes to the database.</p>
<p>Should I databind completely in codebehind ? I am planning on using ObjectDataSources for the databinding. Is there something that is easier to maintain than using databinding, if so, what is it ?</p>
<p>Are there considerations, I should take into account when designing my data access layer and my business layer ?</p>
<p>Thanks.</p>
| <p>My philosophy on this is that data access stuff has no business in the markup. Object Data Sources are better then SQL Data Sources, but I like to keep my markup as only stuff that will get rendered on to the page. I also prefer the control you have on what stuff is databound that you get from always doing it from the code behind.</p>
|
How do I change the color of a Cocos2d MenuItem? <pre><code>[MenuItemFont setFontSize:20];
[MenuItemFont setFontName:@"Helvetica"];
//I'm trying to change the color of start (below item)
MenuItem *start = [MenuItemFont itemFromString:@"Start Game"
target:self
selector:@selector(startGame:)];
MenuItem *help = [MenuItemFont itemFromString:@"Help"
target:self
selector:@selector(help:)];
Menu *startMenu = [Menu menuWithItems:start, help, nil];
[startMenu alignItemsVertically];
[self add:startMenu];
</code></pre>
| <pre><code>MenuItemFont *start = [MenuItemFont itemFromString:@"Start Game"
target:self
selector:@selector(startGame:)];
[start.label setRGB:0 :0 :0]; // Black menu item
</code></pre>
<p>Label is a property of MenuItemFont, a subclass of MenuItem, so you lose it during the implicit cast to MenuItem. </p>
<p>Alternatively, you could do: </p>
<pre><code>[((MenuItemFont *)start).label setRGB:0 :0 :0]
</code></pre>
<p>(but that's ugly, and startMenu will take a MenuItemFont with no complaints).</p>
<p>Keep in mind that the colors are for the most part hardcoded in MenuItemFont, so calling 'setIsEnabled' will set the colors back to grey or white. This happens around line 239 of MenuItem.m if you need to tweak it. If I get around to making a patch to expose this functionality on MenuItemFont (assuming it's not already in the pre-.7.1 sources) I'll update my post.</p>
|
secure file exchange <p>I would like to set up a web application on my company's Linux box for enabling secure file exchange with our customers. I'm looking for an open source application, preferably with a large user base, that supports these features:</p>
<ul>
<li>works over HTTPS (so SFTP or other similar solutions are out of the question)</li>
<li>allows users to upload files using credentials that we provide them with in advance</li>
<li>the files thus uploaded should only be visible when using the same account (or an admin account)</li>
<li>allows an admin to upload files into a user account for the user to download (this doesn't necessarily have to happen via the webapp)</li>
<li>(optional) it should provide email notification when new files are uploaded by users</li>
<li>(optional) it should ensure automatic cleanup of the uploaded files, preferably after a period of time that the uploader can set</li>
</ul>
<p>I've spent some time searching for such an application both on Google and stack overflow, but I haven't found anything compelling yet. Maybe someone here knows about such a thing and can help me with a pointer? Thanks in advance.</p>
| <p>How about <a href="http://www.webdav.org/" rel="nofollow">WebDAV</a>? This is what <a href="http://subversion.tigris.org/" rel="nofollow">subversion</a> uses to sync files over HTTPS. Here's a <a href="http://www.webdav.org/projects/" rel="nofollow">list of open source WebDAV projects</a>.</p>
|
Where to store database credentials in a web app? <p>I'm wondering what techniques you use to store the database credentials for your application. I'm specifically concerned with java webapps, but I don't think there's any need to limit the questions to that. </p>
<p>things to consider:<br />
Do you use property files,xml configs, other?<br />
Is it bundled into your application(ie in a jar file) or stored seperately on the file system somewhere?<br />
Is the password encrypted? If so, what encryption scheme do you use? </p>
| <p>Since you're leaving the question open to platform, I'll add that database credentials for .NET apps are stored in the web.config file. From version 2.0 and above, there is a specific ConnectionStrings section that allows for easier programmatic access to the connection string.</p>
<p>In addition to having IIS automatically block direct requests to the web.config file by default, you can also use an IIS command to encrypt the ConnectionString section of the web.config file. This encryption is machine specific, adding to its strengths, and the .NET runtime will also decrypt the connection string on the fly when you access it, so there is no need for additional coding in your application to work with it.</p>
|
Solution structure / best practices <p>I just recently started a new personal project, with a goal of having it able to scale from the start.</p>
<p>I got a suggestion for the structure, to create something like this: </p>
<pre><code><solution>
|-- project.client.sql.queries
|-- project.admin.sql.queries
|-- project.client.business.logic
|-- project.admin.business.logic
|-- project.client.web.ui (include references of the business logic + SQL queries projects )
|-- project.admin.web.ui
</code></pre>
<p>This way, I would have everything structured and easy to follow for future expansion. My problem resides in the fact that I want to use only SQL express to start, and maybe move on to SQL server later when necessary. </p>
<p>So if I add the <code>.mdf</code> file into the <code>app_code</code> of the client side and create a <code>.dbml</code> (the linq structure file) how can I use linq into the SQL query ? I don't have access to the <code>ConfigurationManager</code> of the web.ui project. Do I have to include a reference into the SQL queries project just as I did for the web.ui ? Otherwise linq doesn't seem to work properly.</p>
<p>I'm looking mostly for the best practices, since I've been told that code behind should not include any business logic or SQL queries - they should have their own class libraries.</p>
| <p>Here is the best advice anyone can ever give you at this point in time:</p>
<blockquote>
<p>The crappy first version is infinitly better then the perfect version that doesnt exist.</p>
</blockquote>
<p>I forget where I got that from, Ive seen that advice many places. It is 100% true.</p>
|
Where can I learn about biomechanical algorithms? <p>I'm planning to start the development of human motion recognition software which will monitor accelerations and recognize motion patterns (run, walk, jump...).</p>
<p>I have started collecting books about biomechanics and it would be good to get some good book about patterncomparison and detection.</p>
<p>Where can I get started with some reading material that might be useful for the project?</p>
| <blockquote>
<p>Where can I get started with some reading material that might be useful for the project?</p>
</blockquote>
<p>I'd suggest get started by talking with a domain expert in that domain ... and/or in a university library.</p>
<p>I discovered that my local university, which receives some money from the government, therefore allows anyone including non-students to obtain a library card for a small fee ... and that library is <code>*</code>enormous<code>*</code>.</p>
<p>As well as books, a good university library would also give you access (perhaps online access) to specialized periodicals (e.g. about biomechanics).</p>
|
Is this a reasonable user registration process? <p>I'm working on a registration process for an internal application. My initial design is below.</p>
<p>My main question is whether it's really necessary to include a <code>registration_confirmation_code</code>. Does it protect the app from a realistic threat or just add unnecessary complexity? I'm not sure about that.</p>
<p><hr /></p>
<ul>
<li><p>User enters email address. Since this is an internal app, it has to be an agency address.</p></li>
<li><p>If it's a valid agency address, app creates a new row in the users table.</p>
<ul>
<li><p>The table has a column <code>registration_confirmed</code> which is <code>false</code> by default. App won't let a user log in unless <code>registration_confirmed</code> is <code>true</code>.</p></li>
<li><p>The table has a column <code>registration_confirmation_code</code> which is a randomly-generated string.</p></li>
</ul></li>
<li><p>App sends an email to the address the user entered. It contains a link to a page that will let the user confirm their registration and set their username and password.</p>
<p>The link has the user's <code>id</code> and <code>registration_confirmation_code</code> in the query string:</p>
<p><code>http://agencydomain.com/users?id=123&registration_confirmation_code=fab49dk34nw97d</code></p></li>
<li><p>By clicking on the link the user verifies that the address they entered is valid and that they have access to it.</p></li>
<li><p>The app finds the user by ID. Before allowing them to visit the page where they can set their username and password, the app checks that...</p>
<ul>
<li><p><code>registration_confirmed</code> is <code>false</code>. They should only be able to confirm their registration once.</p></li>
<li><p><code>registration_confirmation_code</code> request param matches the value in the DB for that user. That ensures this is a legitimate registration confirmation by the intended user and not someone else hitting the URL with random IDs trying to hijack a registration.</p></li>
</ul></li>
<li><p>If everything checks out, the app takes them to a page with a form for setting their username and password.</p></li>
<li><p>When they submit the form with valid data, app sets <code>registration_confirmed</code> to <code>true</code> and they are registered.</p></li>
</ul>
| <p>Don't trust people even if they are internal to your organization. It sounds bad but unless you're dealing with a very small group, your method is a wise choice.</p>
<p>One more thing, you may want to ensure their email is unique.</p>
|
Saving HABTM records when not all join table columns are foreign keys <p>I am trying to update tables with a has and belongs to many (HABTM) relationship.</p>
<p>When my join table looked like this:</p>
<pre><code>CREATE TABLE IF NOT EXISTS `items_labels` (
`item_id` int(11) NOT NULL,
`label_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code></pre>
<p>I use CakePHP, so I could update the tables with $this->Item->save($data) where $data was:</p>
<pre><code>Array
(
[Item] => Array
(
[id] => 1
)
[Label] => Array
(
[Label] => Array
(
[0] => 4
[1] => 5
[2] => 7
[3] => 8
)
)
)
</code></pre>
<p>I've added a column to my join table, so it now looks like:</p>
<pre><code>CREATE TABLE IF NOT EXISTS `items_labels` (
`item_id` int(11) NOT NULL,
`label_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code></pre>
<p>When I am saving $data, I also want to save a user id. The user id will be the same for all records in a single save operation.</p>
<p>Can someone help me understand what the $data array needs to look like in order to incorporate the user id? Thanks.</p>
| <p>This should work:</p>
<pre><code>Array
(
[Item] => Array
(
[id] => 1
)
[Label] => Array
(
[Label] => Array
(
[0] => Array
(
[label_id] => 4
[user_id] => 1
)
[1] => Array
(
[label_id] => 5
[user_id] => 1
)
[2] => Array
(
[label_id] => 7
[user_id] => 1
)
[3] => Array
(
[label_id] => 8
[user_id] => 1
)
)
)
)
</code></pre>
<p>It will generate multiple INSERTs, but will work with one save call.</p>
|
What's really good about .NET Framework 3.5 (except LINQ)? <p>I'm moving from .NET Framework 2.0 to 3.5.</p>
<p>I'm not a big fan of LINQ. So beside of that and "extensions" what should I do know and take advantage of in .NET Framework 3.5?</p>
| <p>Lambdas, Type Inferance.. most of the underlying things that were created to support LINQ.</p>
<p>Why are you not a fan of LINQ?</p>
<p>EDIT: AS a followup, when I say LINQ I am not talking about LINQ to SQL I am talking about LINQ (Language Integrated Query). I think this distinction needs to be made in general as statements like "LINQ is Dead" are erroneous and should read "LINQ to SQL is Dead".</p>
|
How to make an network-ip scan in c++? <p>I am experimenting with C++ winsockets. I want to create a method with which I can find the server on the network, without knowing it's IP. To do this I simply loop my connect method through IP adresses 192.168.1.0 to 192.168.1.255. However, the time between each connect is quite large, the program tends to wait at the: connect(nBytes, (sockaddr*)&server, sizeof(server)) statement for at least 30 seconds if not longer. My questions are the following: Why is this happening, how can I solve this and might there be an entirely different, better way to find the server?</p>
<p>my connect method:</p>
<pre><code>SOCKET connect(char *ipAdress)
{
WSAData wsaData;
if ((WSAStartup(MAKEWORD(2, 2), &wsaData)) == SOCKET_ERROR)
return errorReport("Could not create startup struct");
nBytes = socket(AF_INET, SOCK_STREAM, 0);
if (nBytes == SOCKET_ERROR)
return errorReport("Socket could not be created");
struct hostent *host_entry;
if ((host_entry = gethostbyname(ipAdress)) == NULL)
return errorReport("Cannot find server.");
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(1337);
server.sin_addr.s_addr = *(unsigned long*) host_entry->h_addr;
if (connect(nBytes, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR)
{
WSACleanup();
return errorReport("Failed to connect to server.");
}
if (nBytes == -1)
{
WSACleanup();
disconnect(nBytes);
return errorReport("Could not connect");
}
return 0;
}
</code></pre>
<p>Also, feel free to tell me anything I'm doing wrong in the current connect method.</p>
| <p>The long delay is caused by the socket's need to time out before returning to the caller. To reduce the total execution time, you should make multiple worker threads that simultaneously connect to separate IP-addresses.</p>
|
SQL query to return top N rows per ID across a range of IDs <p>Lets say I have a table containing several hundred million rows that looks something like this:</p>
<pre><code>memID | foo | bar | foobar
1 | blah | blah | blah
1 | blah | blah | blah
1 | blah | blah | blah
1 | blah | blah | blah
1 | blah | blah | blah
1 | blah | blah | blah
1 | blah | blah | blah
2 | blah | blah | blah
2 | blah | blah | blah
2 | blah | blah | blah
2 | blah | blah | blah
2 | blah | blah | blah
.
.
.
10001 | blah | blah | blah
10001 | blah | blah | blah
</code></pre>
<p>I need a query that will return the top N rows for each memID in a range of member IDs.
For example, if N = 3 and the range is 0-2 it should return</p>
<pre><code>memID | foo | bar | foobar
1 | blah | blah | blah
1 | blah | blah | blah
1 | blah | blah | blah
2 | blah | blah | blah
2 | blah | blah | blah
2 | blah | blah | blah
</code></pre>
<p>I've considered a couple approaches, first creating a massive </p>
<pre><code>SELECT TOP (3) *
FROM table
WHERE memID = 0
UNION ALL
SELECT TOP (3) *
FROM table
WHERE memID = 1
.
.
.
</code></pre>
<p>query in code. This isn't really a realistic option for probably obvious reasons.</p>
<p>The second approach is to create a temporary table and loop over the range of memIDs inserting the TOP 3 for each memID into that temporary table.</p>
<pre><code>WHILE @MemID < 10000 AND @MemID > 0
BEGIN
INSERT INTO tmp_Table
SELECT TOP (3) *
FROM table
WHERE memID = @MemID
SET @MemID = @MemID + 1
END
</code></pre>
<p>This works, but I'm wondering if there is a more elegant single query solution that I'm missing.</p>
<p>Cadaeic gave me an answer that works without tinkering, but thank you to everyone that suggested analytics, it looks like I have some serious reading to do.</p>
| <pre><code>declare @startID int, @endID int, @rowsEach int
select @startID = 0, @endID = 2, @rowsEach = 3
select *
from
(
select memID, foo, bar, foobar, row_number() over (partition by dense_rank order by dense_rank) [rank_row]
from
(
select memID, foo, bar, foobar, dense_rank() over (order by memID) [dense_rank]
from #test
where memID between @startID and @endID
) a
) b
where rank_row <= @rowsEach
</code></pre>
<p>The result:</p>
<pre><code>memID foo bar foobar rank_row
----------- ---- ---- ------ --------------------
1 blah blah blah 1
1 blah blah blah 2
1 blah blah blah 3
2 blah blah blah 1
2 blah blah blah 2
2 blah blah blah 3
</code></pre>
<p>And here's the set-up code if you'd like to test locally:</p>
<pre><code>create table #test
(
memID int not null
, foo char(4) not null
, bar char(4) not null
, foobar char(4) not null
)
insert into #test (memID, foo, bar, foobar)
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 2, 'blah', 'blah', 'blah'
union all
select 2, 'blah', 'blah', 'blah'
union all
select 2, 'blah', 'blah', 'blah'
union all
select 2, 'blah', 'blah', 'blah'
union all
select 10001, 'blah', 'blah', 'blah'
union all
select 10001, 'blah', 'blah', 'blah'
union all
select 10001, 'blah', 'blah', 'blah'
</code></pre>
|
How to predict MySQL tipping points? <p>I work on a big web application that uses a MySQL 5.0 database with InnoDB tables. Twice over the last couple of months, we have experienced the following scenario: </p>
<ol>
<li>The database server runs fine for weeks, with low load and few slow queries.</li>
<li>A frequently-executed query that previously ran quickly will suddenly start running very slowly.</li>
<li>Database load spikes and the site hangs.</li>
</ol>
<p>The solution in both cases was to find the slow query in the slow query log and create a new index on the table to speed it up. After applying the index, database performance returned to normal.</p>
<p>What's most frustrating is that, in both cases, we had no warning about the impending doom; all of our monitoring systems (e.g., graphs of system load, CPU usage, query execution rates, slow queries) told us that the database server was in good health. </p>
<p>Question #1: <strong>How can we predict these kinds of tipping points or avoid them altogether?</strong></p>
<p>One thing we are not doing with any regularity is running OPTIMIZE TABLE or ANALYZE TABLE. We've had a hard time finding a good rule of thumb about how often (if ever) to manually do these things. (Since these commands LOCK tables, we don't want to run them indiscriminately.) Do these scenarios sound like the result of unoptimized tables? </p>
<p>Question #2: <strong>Should we be manually running OPTIMIZE or ANALYZE? If so, how often?</strong></p>
<p>More details about the app: database usage pattern is approximately 95% reads, 5% writes; database executes around 300 queries/second; the table used in the slow queries was the same in both cases, and has hundreds of thousands of records. </p>
| <p>The MySQL Performance Blog is a fantastic resource. Namely, <a href="http://www.mysqlperformanceblog.com/2007/11/01/innodb-performance-optimization-basics/" rel="nofollow">this</a> post covers the basics of properly tuning InnoDB-specific parameters.</p>
<p>I've also found that the PDF version of the <a href="http://dev.mysql.com/doc/#refman" rel="nofollow">MySQL Reference Manual</a> to be essential. <a href="http://dev.mysql.com/doc/refman/5.1/en/optimization.html" rel="nofollow">Chapter 7 covers general optimization</a>, and <a href="http://dev.mysql.com/doc/refman/5.1/en/optimizing-the-server.html" rel="nofollow">section 7.5</a> covers server-specific optimizations you can toy with.</p>
<p>From the sound of your server, the <a href="http://dev.mysql.com/doc/refman/5.1/en/query-cache.html" rel="nofollow">query cache</a> may be of IMMENSE value to you.</p>
<p>The reference manual also gives you some great detail concerning slow queries, caches, query optimization, and even disk seek analysis with indexes.</p>
<p>It may be worth your time to look into multi-master replication, allowing you to lock one server entirely and run OPTIMIZE/ANALYZE, without taking a performance hit (as 95% of your queries are reads, the other server could manage the writes just fine).</p>
<p>Section 12.5.2.5 covers OPTIMIZE TABLE in detail, and 12.5.2.1 covers ANALYZE TABLE in detail.</p>
<p>Update for your edits/emphasis:</p>
<p><b>Question #2</b> is easy to answer. From the reference manual:</p>
<p>OPTIMIZE:</p>
<blockquote>
<p>OPTIMIZE TABLE should be used if you have deleted a large part of a table or if you have made many changes to a table with variable-length rows. [...] You can use OPTIMIZE TABLE to reclaim the unused space and to defragment the data table.</p>
</blockquote>
<p>And ANALYZE:</p>
<blockquote>
<p>ANALYZE TABLE analyzes and stores the key distribution for a table. [...] MySQL uses the stored key distribution to decide the order in which tables should be joined when you perform a join on something other than a constant. In addition, key distributions can be used when deciding which indexes to use for a specific table within a query.</p>
</blockquote>
<p>OPTIMIZE is good to run when you have the free time. MySQL optimizes well around deleted rows, but if you go and delete 20GB of data from a table, it <i>may</i> be a good idea to run this. It is definitely not required for good performance in most cases.</p>
<p>ANALYZE is much more critical. As noted, having the needed table data available to MySQL (provided with ANALYZE) is very important when it comes to pretty much <i>any query</i>. It is something that should be run on a common basis.</p>
<p><b>Question #1</b> is a bit more of a trick. I would watch the server very carefully when this happens, namely disk I/O. My bet would be that your server is thrashing either your swap or the (InnoDB) caches. In either case, it may be query, tuning, or load related. Unoptimized tables could cause this. As mentioned, running ANALYZE can immensely help performance, and will likely help out too.</p>
|
.NET User Management Customization <p>I was wondering if anyone could point me to some resources concerning customization of the user management system that is built in .NET. What I am talking about is: <a href="http://msdn.microsoft.com/en-us/library/ms998347.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms998347.aspx</a></p>
<p>I would like to know, how can I extend the user fields to store more than just common password, username? I want to store for example: birthday, and other result sets.</p>
| <p>In my opinion, you should not extend the membership tables at all. You should, instead, create your own tables and reference the membership data. One technique I use is to use the Membership GUID ID as a foriegn key to my own "users" table which contains my extended data.</p>
<p>This works out for the best because then if Microsoft decides to extend the Membership table in the future, your code doesn't break.</p>
|
How can I return the results of a function to a cell in Excel? <p>Suppose I have a function attached to one of my Excel sheets:</p>
<pre><code>Public Function foo(bar As Integer) as integer
foo = 42
End Function
</code></pre>
<p>How can I get the results of <code>foo</code> returned to a cell on my sheet? I've tried <code>"=foo(10)"</code>, but all it gives me is <code>"#NAME?"</code></p>
<p>I've also tried <code>=[filename]!foo(10) and [sheetname]!foo(10)</code> with no change.</p>
| <p>Try following the directions <a href="http://web.archive.org/web/20090220142331/http://exceltip.com/st/Writing_Your_First_VBA_Function_in_Excel/631.html" rel="nofollow">here</a> to make sure you're doing everything correctly, specifically about where to put it. ( <code>Insert->Module</code> )</p>
<p>I can confirm that opening up the VBA editor, using <code>Insert->Module</code>, and the following code:</p>
<pre><code>Function TimesTwo(Value As Integer)
TimesTwo = Value * 2
End Function
</code></pre>
<p>and on a sheet putting <code>"=TimesTwo(100)"</code> into a cell gives me <code>200</code>.</p>
|
XPath SelectNodes in .NET <pre><code><Document>
<A>
<B>
<C></C>
</B>
</A>
<E>
<F>
<C></C>
</F>
<G>
<C></C>
</G>
</E>
</Document>
</code></pre>
<p>If i load the above XML into an XmlDocument and do a SelectSingleNode on A using the XPath query //C</p>
<pre>
XmlNode oNode = oDocument.SelectSingleNode("E");
XmlNodeList oNodeList = oNode.SelectNodes("//C");
</pre>
<p>why does it return nodes from Under B when what I would expect to happen would that it only return nodes from under E</p>
<p>Make sense?</p>
<p>Edit : How would i make it only return from that node onwards?</p>
| <p>Simply: a leading // means "at any level" in the same <em>document</em> as the selected node.</p>
<p>From the <a href="http://www.w3.org/TR/xpath">spec</a>:</p>
<ul>
<li>//para selects all the para descendants of the document root and thus selects all para elements in the same document as the context node</li>
<li>.//para selects the para element descendants of the context node</li>
</ul>
|
windows service stops and starts immediately, but it shouldn't <p>I'm creating a windows service and after installing the service, it stops and starts immediately, but it shouldn't be at all. Previously, I was getting errors that the service was not responding to the start command in a timely fashion, so I took the init code out and put it in a thread, and now I am here:</p>
<pre><code>protected override void OnStart(string[] args)
{
this.EventLog.WriteEntry("ATNotifier Started");
ThreadPool.QueueUserWorkItem(WaitOnEmailsChanged);
ThreadPool.QueueUserWorkItem(Init, "IP");
}
</code></pre>
<p>The waitonemailschanged thread simply creates a filesystemwatcher to watch to see if the settings file (xml document) gets changed, and loads in the data from that file if that happens. For the time being, this just waits indefinitely (which is the general case, as that will only be changed a few times a year), as no changes are being made to the xml document.</p>
<p>The Init thread does all kinds of things, including creating and starting a System.Timers.Timer object whose Elapsed method is the meat of the service.</p>
<p>I can't understand why it would start and then immediately stop. I should also note that the eventviewer shows no logs from this app.</p>
<p>edit> I tried creating 'proper' threads, with the same results and I've removed everything except the creating and starting of the timer like so:</p>
<pre><code>protected override void OnStart(string[] args)
{
this.EventLog.WriteEntry("ATNotifier Started");
m_Timer = new System.Timers.Timer(90000.0); // 1.5 mins
m_Timer.Elapsed += new ElapsedEventHandler(m_Timer_Elapsed);
m_Timer.Start();
}
</code></pre>
<p>and I'm still getting the same message. It's almost as if the OnStart is never being called.</p>
| <p>It might be stopped unexpectedly if your main thread terminates on exception.</p>
|
Entity Linq - Retrieve record and only the first child record in a one to many relationship <p>I have an entity called "Requests" which has a navigation called "StatusHistories" </p>
<p>I need to retrieve all of the Requests where the last StatusHistory is "Open"</p>
<p>StatusHistory has the fields
StartDate (the highest one of these would be the last StatusHistory)
Status (for this presume status contains the string "Open" or "Closed")
RecordID (this is an Identity field in SQL Server, so it too could be used to find the last one, but I'd rather not)</p>
<p>Thanks.</p>
| <pre><code>var result = from r in Requests
where <condition>
select r.field1, r.field2, (from s in StatusHistory
where <join codition>
order by s.StartDate descending
select s.field).FirstOrDefault()
</code></pre>
|
Best practice for using window.onload <p>I develop Joomla websites/components/modules and plugins and every so often I require the ability to use JavaScript that triggers an event when the page is loaded. Most of the time this is done using the <code>window.onload</code> function.</p>
<p><strong>My question is:</strong> </p>
<ol>
<li>Is this the best way to trigger JavaScript events on the page loading or is there a better/newer way?</li>
<li>If this is the only way to trigger an event on the page loading, what is the best way to make sure that multiple events can be run by different scripts?</li>
</ol>
| <p><code>window.onload = function(){};</code> works, but as you might have noticed, <strong>it allows you to specify only 1 listener</strong>.</p>
<p>I'd say the better/newer way of doing this would be to use a framework, or to just to use a simple implementation of the native <code>addEventListener</code> and <code>attachEvent</code> (for IE) methods, which allows you to <em>remove</em> the listeners for the events as well.</p>
<p>Here's a cross-browser implementation:</p>
<pre><code>// Cross-browser implementation of element.addEventListener()
function listen(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
var r = elem.attachEvent("on"+evnt, func);
return r;
}
else window.alert('I\'m sorry Dave, I\'m afraid I can\'t do that.');
}
// Use: listen("event name", elem, func);
</code></pre>
<p>For the window.onload case use: <code>listen("load", window, function() { });</code></p>
<hr/>
<p><strong>EDIT</strong> I'd like to expand my answer by adding precious information that was pointed by others.</p>
<p>This is about the <strong><code>DOMContentLoaded</code></strong> (Mozilla, Opera and webkit nightlies currently support this) and the <strong><code>onreadystatechange</code></strong> (for IE) <em>events</em> which can be applied to the <strong>document</strong> object to understand when the document is available to be manipulated (without waiting for all the images/stylesheets etc.. to be loaded).</p>
<p>There are a lot of "hacky" implementations for cross-browsers support of this, so I strongly suggest to use a framework for this feature.</p>
|
Question about yield return statement <p>Take the example here:</p>
<pre><code> public static IEnumerable<BigInt> EvenNumbers(IEnumerable<BigInt> numbers)
{
foreach (BigInt number in numbers)
{
if (number % 2 == 0)
{
yield return number;
}
}
}
</code></pre>
<p>This will return only the values which match the criteria (n % 2 == 0). But what is the difference between yield return number; and return number;?</p>
<p>If I say yield return number, will it return each number to the calling function and so on? Where can I find some details on what goes on behind the scenes?</p>
<p>Thanks </p>
| <p>"return" simply won't work here (since it would try to return a <code>BigInt</code>, and the method declares an <code>IEnumerable<BigInt></code>. Jon Skeet has a good write-up of iterator blocks (what this is) in the <strong>free</strong> chapter 6 of <a href="http://www.manning.com/skeet/" rel="nofollow">C# in Depth</a> (then buy the whole book - it really is worth it ;-p).</p>
<p><hr /></p>
<p>edit - here's a <strong>very rough</strong> version of what you would have to do in order to write this yourself; note that it doesn't quite do the same, but achieves the goal. I think you'll agree that the <code>yield return</code> version is easier!</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
static class Program
{
static void Main()
{
IEnumerable<int> source = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (int value in EvenNumbers(source))
{
Console.WriteLine(value);
}
}
public static IEnumerable<int> EvenNumbers(IEnumerable<int> numbers)
{
return new EvenEnumerable(numbers);
}
class EvenEnumerable : IEnumerable<int>
{
private readonly IEnumerable<int> numbers;
public EvenEnumerable(IEnumerable<int> numbers) {
this.numbers = numbers;
}
public IEnumerator<int> GetEnumerator()
{
return new EvenEnumerator(numbers);
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
class EvenEnumerator : IEnumerator<int>
{
private readonly IEnumerable<int> numbers;
public EvenEnumerator(IEnumerable<int> numbers)
{
this.numbers = numbers;
}
private int current;
void IEnumerator.Reset() { throw new NotSupportedException(); }
public int Current { get { return current; } }
object IEnumerator.Current { get { return Current; } }
IEnumerator<int> iter;
public bool MoveNext()
{
if (iter == null) iter = numbers.GetEnumerator();
while (iter.MoveNext())
{
int tmp = iter.Current;
if (tmp % 2 == 0)
{
current = tmp;
return true;
}
}
return false;
}
public void Dispose()
{
if (iter != null)
{
iter.Dispose();
iter = null;
}
}
}
}
</code></pre>
|
jQuery JSON Problem <p>I want to populate form fields with values from a database immediately after the user enters a value in the #sid field. Here is my jQuery/HTML example:</p>
<pre><code><script src="jquery-1.3.1.min.js"></script>
<script type="text/JavaScript">
$(document).ready(function()
{
$('#sid').bind("change", function(){
$.getJSON("test.php?sid=" + $("#sid").val(),
function(data)
{
$.each(data.items,
function(i, item)
{
if (item.field == "saffil")
{
$("#saffil").val(item.value);
}
else if (item.field == "sfirst")
{
$("#sfirst").val(item.value);
}
});
});
});
});
</script>
</code></pre>
<p>Here is my processing script (test.php which gets called by the .getJSON method)</p>
<pre><code><?
require_once("db_pers.inc");
$ssql = "SELECT * FROM contacts_mview WHERE sempid = '".$_GET['sid']."'";
$rres = pg_query($hdb, $ssql);
pg_close($hdb);
$ares = pg_fetch_assoc($rres);
$json = array(array('field' => 'saffil',
'value' => $ares['saffil']),
array('field' => 'sfirst',
'value' => $ares['sfirst']));
echo json_encode($json);
?>
</code></pre>
<p>According to firebug the GET param is passed just fine to test.php and the JSON object comes back just fine:</p>
<pre><code>[{"field":"saffil","value":"Admin"},{"field":"sfirst","value":"Nicholas"}]
</code></pre>
<p>however nothing happens on the page and I get the following error message back:</p>
<pre><code>G is undefined
init()()jquery-1....1.min.js (line 12)
(?)()()test.html (line 15)
I()jquery-1....1.min.js (line 19)
F()()jquery-1....1.min.js (line 19)
[Break on this error] (function(){var l=this,g,y=l.jQuery,p=l.....each(function(){o.dequeue(this,E)})}});
</code></pre>
<p>This is my first stab at ajax with jQuery so any input would be much appreciated!</p>
<p>Thanks,</p>
<ul>
<li>Nicholas</li>
</ul>
| <p>Nice little injection attack waiting to happen there ;)</p>
<p>Try changing</p>
<pre><code>$.each(data.items,
</code></pre>
<p>to:</p>
<pre><code>$.each(data,
</code></pre>
<p><em>Edit</em>: to answer your comment, I like to name my fields the same as the data key:</p>
<pre><code><input type="text" name="saffil" value="" />
<input type="text" name="sfirst" value="" />
var data = {saffil:'foo', sfirst:'bar'};
$.each(data, function(key, value) {
$('[name='+key+']').val(value)
})
</code></pre>
|
How to download fast lots of web pages in ruby? Parallelizing download? <p>I need to scrape(using scrAPI) 400+ web pages ruby, my actual code is very sequential:</p>
<pre><code>data = urls.map {|url| scraper.scrape url }
</code></pre>
<p>Actually the code is a bit different (exception handling and stuff).</p>
<p>How can I make it faster?
How can I parallelize the downloads?</p>
| <pre><code>th = []
data = []
dlock = Mutex.new
urls.each do |url|
th << Thread.new(url) do |url|
d = scraper.scrape url
dlock.synchronize { data << d }
end
end
th.each { |t| t.join }
</code></pre>
<p>Tada! (Caution; written from memory, not tested, may eat your kitten, etc)</p>
<p><strong>Edit:</strong> I figured someone must have written a generalised version of this, and so they have: <a href="http://peach.rubyforge.org/" rel="nofollow">http://peach.rubyforge.org/</a> -- enjoy!</p>
|
getline() in C++ - _GNU_SOURCE not needed? <p>Firstly, I'm pretty new to C++. I believe that <code>getline()</code> isn't a standard C function, so <code>#define _GNU_SOURCE</code> is required to use it. I'm now using C++ and g++ tells me that <code>_GNU_SOURCE</code> is already defined:</p>
<pre><code>$ g++ -Wall -Werror parser.cpp
parser.cpp:1:1: error: "_GNU_SOURCE" redefined
<command-line>: error: this is the location of the previous definition
</code></pre>
<p>Can anyone confirm if this is standard, or is its definition hidden somewhere in my setup? I'm not sure of the meaning of the final line quoted.</p>
<p>The file's includes are as follows, so presumably it's defined in one or more of these?</p>
<pre><code>#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>
#include <list>
#include <sstream>
</code></pre>
<p>Thanks!</p>
| <p>I think g++, from version 3, automagically defines <code>_GNU_SOURCE</code>. This is supported by your third line in the error stating that the first definition was done on the command line (with nary a <code>-D_GNU_SOURCE</code> in sight):</p>
<pre><code><command-line>: error: this is the location of the previous definition
</code></pre>
<p>If you don't want it, <code>#undef</code> it as the first line in your compilation unit. You may need it, however, in which case use:</p>
<pre><code>#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
</code></pre>
<p>The reason you're getting the error is because you're re-defining it. It shouldn't be an error if you define it to what it already was. At least that's the case with C, it may be different with C++. Based on the GNU headers, I would say they're doing an implicit <code>-D_GNU_SOURCE=1</code> which is why it thinks you're <em>re-defining</em> it to something else.</p>
<p>The following snippet should tell you its value provided you haven't changed it.</p>
<pre><code>#define DBG(x) printf ("_GNU_SOURCE = [" #x "]\n")
DBG(_GNU_SOURCE); // first line in main.
</code></pre>
|
How to limit user access at database level in Hibernate <h3>The App</h3>
<p>I need to implement a web app that will be used by different users. Each user has different privileges on various tables, e.g. </p>
<p><li> User A can see fields 'name' and 'address' from the table <code>Student</code> </li>
<li> User B can see fields 'name' and 'phone number', but not 'address' from the table <code>Student</code> </li>
<li> User C can see and modify all fields mentioned above</li></p>
<p><br/>
I will have something at the UI level to limit certain access, e.g. hide the "edit" button for users that don't have permission to modify entries. However, I think I should have something at a lower level (at a database level maybe?) just to ensure data security. </p>
<p><hr /></p>
<h3>The Problem</h3>
<p>I am using Hibernate, JBoss, DB2 and Struts for my app. I think I should use a JBoss LoginModule of some sort, which authenticates the user against a database with user/password/roles (but I may be wrong(?)). I have done some research and came up with the following options, but none seems to fit my case. I would think this is a very common data access problem in multi-user web apps. Could somebody please point me to the right direction? <em>Thank you in advance!</em></p>
<ol>
<li><p>Use the 'grant' tag in <code>hibernate.cfg.xml</code> with JACC event listeners. This can set "insert" "update" "read" permissions on all hibernate entities. However, what if I need finer controls? I need to set permissions on certain fields instead of the entire object. <a href="http://www.hibernate.org/hib_docs/v3/reference/en-US/html/objectstate-decl-security.html" rel="nofollow">http://www.hibernate.org/hib_docs/v3/reference/en-US/html/objectstate-decl-security.html</a> </p></li>
<li><p>Limit permissions on getter/setter method of each ejb. If I understood this correctly, this requires manual configuration of every single bean for every user profile, which seems unrealistic for me.
<a href="http://www.jboss.org/file-access/default/members/jbossas/freezone/docs/Server%5FConfiguration%5FGuide/4/html/J2EE%5FDeclarative%5FSecurity%5FOverview-EJB%5Fmethod%5Fpermissions.html" rel="nofollow">EJB Method Permissions</a> </p></li>
<li><p>Code the DAO's to check for user permissions. Roll my own utility function that checks a giant permission table everytime a particular DAO method is called to determine if the logged in user can perform the action or not. </p></li>
<li><p>Use 'interceptor' and 'events' in Hibernate. Define specific "onLoad", "onSaveorUpdate" etc. events and interceptors for each class. Can I specify permission level for individual fields in this case? <a href="http://www.hibernate.org/hib_docs/v3/reference/en-US/html/objectstate-events.html" rel="nofollow">http://www.hibernate.org/hib_docs/v3/reference/en-US/html/objectstate-events.html</a></p></li>
</ol>
<p>I might be barking at the wrong tree. All of the above seem to be labour-intensive and not very intelligent. None of the above options give me programmatic ways to change user permissions at runtime, which would be useful when an admin-level user want to give another user more control in this app. </p>
<p><br/>
What is a good way of doing data-access control here?</p>
| <ol>
<li><p>Add a security key to your entities, create a table for permissions and link user with permission with entitytype and also with security key with role. This way you can say things like: Admin_role can access Student (Entitiy type) and do read (Operation in Permission) and Write (Operation) while Student_role can access Student_key for him-/herself and Read_permission. You can fix the address by refactoring that into an entity and adding a security key to it.</p></li>
<li><p>Your number four could have a closed-world assumption and say that unless you can for the current role of the user, link the property-name with a flag in a dictionary (entity+property)-hash to flag, the closed world-assumption being that reads are not allowed by default. Then of course you don't get any writes-permissions etc.</p></li>
<li><p>You can define views in your database and assign rights to them using the database authentication system. This is probably the most clean way if you are able to code yourself, the way of selecting which view to call depending on which role we are. (My former RDBMS-teacher would love me for saying this ;)) This also goes away a bit from Hibernate and couples your stuff more to the database. It depends on how movable/portable your code needs to be, I guess. </p></li>
<li><p>Use an aspect around your generic dao (IRepository) which rewrites the queries based on your permissions; this implies you have the permission-based security in code of course.</p></li>
</ol>
<p>The edit-button hiding in the gui can really only be done if you first port the permissions to code, like in my point 1. I suggest you have a look at <a href="http://ayende.com/Blog/category/548.aspx" rel="nofollow">Ayendes blog</a> for an open-source implementation of this, he's a very skilled coder.</p>
|
Looking for Java spell checker library <p>I am looking for an open source Java spell checking library which has dictionaries for at least the following languages: French, German, Spanish, and Czech. Any suggestion?</p>
| <p>Another good library is JLanguageTool <a href="http://www.languagetool.org/usage/" rel="nofollow">http://www.languagetool.org/usage/</a>
It has a pretty simple api and does both spelling and grammar checking/suggestions.</p>
<pre class="lang-java prettyprint-override"><code>JLanguageTool langTool = new JLanguageTool(Language.AMERICAN_ENGLISH);
langTool.activateDefaultPatternRules();
List<RuleMatch> matches = langTool.check("Hitchhiker's Guide tot he Galaxy");
for (RuleMatch match : matches) {
System.out.println("Potential error at line " +
match.getEndLine() + ", column " +
match.getColumn() + ": " + match.getMessage());
System.out.println("Suggested correction: " +
match.getSuggestedReplacements());
}
</code></pre>
<p>You can also use it to host your own spelling and grammar web service. </p>
|
Selecting empty mysql datetime fields <p>Is there a better way to select empty datetime fields than this?</p>
<pre><code>SELECT * FROM `table` WHERE `datetime_field` = '0000-00-00 00:00:00'
</code></pre>
| <p>Better in what way? That query does everything you ask of it and, provided there's an index on <code>datetime_field</code>, it's as fast as it's going to get.</p>
<p>If you're worried about the query looking "ugly", don't be. Its intent is quite clear.</p>
<p>The only possible improvement you could consider is to use NULLs for these zero-date/time rows, in which case your query becomes:</p>
<pre><code>SELECT * FROM `table` WHERE `datetime_field` IS NULL
</code></pre>
<p>That's what I'd do with a standards-compliant DBMS. My understanding is that MySQL <strong>may</strong> represent true NULL datetime fields in this horrific manner, in which case I guess the <code>IS NULL</code> may not work.</p>
|
Is getting JSON data with jQuery safe? <p>JSON allows you to <a href="http://docs.jquery.com/Ajax/jQuery.get">retrieve data in multiple formats</a> from an AJAX call. For example:</p>
<pre><code>$.get(sourceUrl, data, callBack, 'json');
</code></pre>
<p>could be used to get and parse JSON code from <code>sourceUrl</code>. </p>
<p>JSON is the simply JavaScript code used to describe data. This could be evaled by a JavaScript interpreter to get a data structure back. </p>
<p>It's generally a bad idea to evaluate code from remote sources. I know the JSON spec doesn't specifically allow for function declarations, but there's no reason you couldn't include one in code and have an unsafe and naive consumer compile/execute the code.</p>
<p>How does jQuery handle the parsing? Does it evaluate this code? What safeguards are in place to stop someone from hacking <code>sourceUrl</code> and distributing malicious code?</p>
| <p>The last time I looked (late 2008) the JQuery functions get() getJSON() etc internally eval the JSon string and so are exposed to the same security issue as eval.</p>
<p>Therefore it is a very good idea to use a parsing function that validates the JSON string to ensure it contains no dodgy non-JSON javascript code, before using eval() in any form. </p>
<p>You can find such a function at <a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js">https://github.com/douglascrockford/JSON-js/blob/master/json2.js</a>.</p>
<p>See <a href="http://yuiblog.com/blog/2007/04/10/json-and-browser-security/">JSON and Broswer Security</a> for a good discussion of this area.</p>
<p>In summary, using JQuery's JSON functions without parsing the input JSON (using the above linked function or similar) is not 100% safe.</p>
<p>NB: If this sort of parsing is still missing from getJSON (might have recently been added) it is even more important to understand this risk due to the cross domain capability, from the JQuery reference docs:</p>
<blockquote>
<p>As of jQuery 1.2, you can load JSON
data located on another domain if you
specify a JSONP callback, which can be
done like so: "myurl?callback=?".
jQuery automatically replaces the ?
with the correct method name to call,
calling your specified callback.</p>
</blockquote>
|
iPhone: Popping a modalViewController off of a UINavigationController stack <p>Ever since I've taken one of my UIViewController subclasses and present it to the user in the form of a modal view, with presentModalViewController:animated.. I haven't been able to dismiss it using:</p>
<pre><code>[self dismissModalViewControllerAnimated:YES];
</code></pre>
<p>I do believe this is some odd mixup with how I'm instantiating a UINavigationController on the modalViewController, with code that looks like the following (similar code is also in the App Delegate):</p>
<pre><code>UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
navigationController =
[[UINavigationController alloc] initWithRootViewController:self];
navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
</code></pre>
<p>The navigation stack works as expected, but unless I remove it, I can't dismiss the modal view controller any longer. I'm under the impression that I shouldn't be adding a subView to UIWindow more than once and that's just one of the problems. </p>
| <p>Make sure you call dismissModalViewControllerAnimated on the parent of the modal view controller, not on the modal view controller itself.</p>
|
About ProgramData folder's right with UAC turned on under Vista <p>I login in with Administrator on Vista with UAC turned on, is it OK for me to create, modifty or delete file in ProgramData folder. My test result is YES, but I found my AP can access the folder which name is "MicroSoft", is there any starndard document to know the ProgramData folder's right under Vista?</p>
| <p>It should be fine, yes. The Program Data folder is there for programs for that purpose.</p>
<p>In terms of permission, you should be able to check or modify file permissions using .NET. See the <code>System.IO.DirectoryInfo</code> class as a reference, and see <code>System.Management</code> and <code>System.Management.Instrumentation</code> namespaces for getting user information.</p>
|
ROWID and RECID <p>what is ROWID and RECID actually in progress.Can we use the RECID instead of ROWID.what is the diffrrence between them??</p>
| <p>Both <a href="http://documentation.progress.com/output/OpenEdge102a/oe102ahtml/wwhelp/wwhimpl/common/html/wwhelp.htm?context=dvref&file=dvref-15-48.html">RECID</a> and <a href="http://documentation.progress.com/output/OpenEdge102a/oe102ahtml/wwhelp/wwhimpl/common/html/wwhelp.htm?context=dvref&file=dvref-15-66.html">ROWID</a> are unique pointers to a specific record in the database.</p>
<p>Both are more-or-less physical pointers into the database itself, except for non-OpenEdge tables where there is no equivalent on the underlying platform. In those cases, it may be comprised of the values making up the primary key.</p>
<p>RECIDs are 32 bit integers up through 10.1A, and were fine when the database was an OpenEdge database and had only one area. From 10.1B forward they were upgraded to 64 bit integers.</p>
<p>In v6 the capacity was added to connect to non-OpenEdge databases, and in v8 to create OpenEdge databases of more than one storage area. At that point, RECIDs were insufficient to address all of the records in a table uniquely in all circumstances.</p>
<p>So the ROWID structure was born. Its actual architecture depends on the type of database underneath, but it does not suffer from the limitations of being an integer.</p>
<p>The documentation is fairly clear in stating <a href="http://documentation.progress.com/output/OpenEdge102a/oe102ahtml/wwhelp/wwhimpl/common/html/wwhelp.htm?context=dvref&file=dvref-15-48.html">that RECIDs should not be used going forward</a>, except for code that manipulates the OpenEdge database metaschema.</p>
|
what language are the apps for the iphone created with? <p>what language is it similar to? cause i was looking at the dev page on apple for the iphone and it doesnt look like anything that i'm used to or know.</p>
| <p>iPhone applications are created using objective-C as the primary language. You can also use C/C++ in the applications, but the Cocoa Touch API uses objective-C.</p>
<p>Also, if you have never programmed on the Mac before it will take some getting used to. Apple uses the MVC (Model View Controller) design pattern extensively in their programming model.</p>
<p>Here is a good site with several iPhone apps with source code:
<a href="http://appsamuck.com/" rel="nofollow">http://appsamuck.com/</a></p>
<p>If you need a crash course in objective-C check out this link:
<a href="http://cocoadevcentral.com/d/learn_objectivec/" rel="nofollow">http://cocoadevcentral.com/d/learn_objectivec/</a></p>
|
how do you print a bag datatype? <pre><code>Bag<String> wordFrequencies = getWordFrequencies(text);
</code></pre>
<p>how do i see what this wordfrequencies bag contains..
i ve used
org.apache.commons.collections15.Bag
org.apache.commons.collections15.bag.HashBag packages</p>
| <pre><code>public static String bagToString(Bag<?> bag) {
StringBuilder sb = new StringBuilder();
for (Object o : bag.uniqueSet() {
sb.append(o);
sb.append(":");
int nItems = bag.getCount(o);
sb.append(nItems);
sb.append(" ");
}
return sb.toString();
}
</code></pre>
|
Why can't I use multiple ids here? <p>I'm trying to get a bit of code working. I'm using xfade, latest version. Homebrew Javascript image fader that fades between all img tags in a div, assigned by the Javascript. There's an image fade script I found that uses Javascript to fade between images in a div. However, it can only fade 1 div...I have 3 spots I want to have fading images at, and I can't get the Javascript code to accept the effects to run on another div.</p>
<p><s>Here's the code I'm using:</p>
<p><a href="http://www.enlinegraphics.com/assets/js/xfade2.js" rel="nofollow">http://www.enlinegraphics.com/assets/js/xfade2.js</a></p>
<p>And the page I'm trying to get the multiple divs with their own set of fading images working is the homepage, aka <a href="http://www.enlinegraphics.com" rel="nofollow">http://www.enlinegraphics.com</a></s></p>
<p>If I'm going about this completely wrong, and the code can't easily run the effects on different DIVs, then I can look for another, but I really need to figure out a good Javascript image fader.</p>
<p><strong>EDIT</strong>: I'm going to try my hand at JQuery per an answer's suggestion - if you have any help that will help me with that, that would be the focus now, not trying to get xfade working. Thanks.</p>
| <p>You could consider implementing and learning jQuery, which has a few plugins to fade things as well as built in functions such as fadeIn(), fadeOut(), etc.</p>
<p>You could use multiple divs fade using a selector like this</p>
<pre><code>$('#div1, #div2').fadeOut(1000);
</code></pre>
<p>Good luck!</p>
<h2>Extra Help</h2>
<p>More specifically if at this stage you'd like to get started on fading Div's, check out the jQuery docs at <a href="http://docs.jquery.com" rel="nofollow">http://docs.jquery.com</a>, more specifically the selectors (for selecting the div) and the effects (for learning how and which functions to use).</p>
|
Conditional compilation in Python <p>How to do conditional compilation in Python ?</p>
<p>Is it using DEF ?</p>
| <p>Python isn't compiled in the same sense as C or C++ or even Java, python files are compiled "on the fly", you can think of it as being similar to a interpreted language like Basic or Perl.<sub>1</sub></p>
<p>You can do something equivalent to conditional compile by just using an if statement. For example:</p>
<pre><code>if FLAG:
def f():
print "Flag is set"
else:
def f():
print "Flag is not set"
</code></pre>
<p>You can do the same for the creation classes, setting of variables and pretty much everything.</p>
<p>The closest way to mimic IFDEF would be to use the hasattr function. E.g.:</p>
<pre><code>if hasattr(aModule, 'FLAG'):
# do stuff if FLAG is defined in the current module.
</code></pre>
<p>You could also use a try/except clause to catch name errors, but the idiomatic way would be to set a variable to None at the top of your script.</p>
<ol>
<li>Python code is byte compiled into an intermediate form like Java, however there generally isn't a separate compilation step. The "raw" source files that end in .py are executable.</li>
</ol>
|
Introducing agile practices in a subproject only? <p>Imagine you work as a contractor in a large project involving multiple systems, and you are creating one of them. The whole project uses a traditional process, but there are smells that tell you that an agile process would be much better.</p>
<p>Now the question. Does it make sense to introduce an agile software development process in your own group only? There is no chance to change the whole project, but you might perhaps change the process in your own group.</p>
<p>What would be the major benefits and pitfalls of such a local process change? Are there specific agile processes that would work good in such a case?</p>
| <p>Here's a great diary of how a guy changed his whole company towards Agile over a period of a couple of years - yes, starting with his own subproject, i.e. "bottom-up". But he does go into the pros and cons of trying a "top-down" change.</p>
<p><a href="http://jamesshore.com/Change-Diary/" rel="nofollow">http://jamesshore.com/Change-Diary/</a></p>
<p>Very entertaining and intruiging stuff.</p>
|
MSMQ with WCF problem <p>This is a though on to explain, here i go.</p>
<p>We are creating a program where sender and receiver of the msmq is using WCF. We implemented a fault handle very similar as this:
<a href="http://msdn.microsoft.com/en-us/library/ms751472.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms751472.aspx</a> in combination with <a href="http://msdn.microsoft.com/en-us/library/ms789028.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms789028.aspx</a></p>
<p>Everything works great. We even made testcases which run 100's of messages through the queue and everything gets processed. When we make it 10000's we get some timeouts, but de error handling works fine so the message is retried a couple of times and then it ends up in the poison queue.</p>
<p>I checked in my code and released it to the other developers. The following problem occured more then one time while using the queue:</p>
<p>A message is not correctly read in ends up as a fault message (in the PoisonErrorHandler class). It always has this Exception message (of type FaultException):
The message with To 'net.msmq://localhost/private/adpqueue' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree.
In this error the Code.Name = Sender and Code.SubCode.Name = DestinationUnreachable</p>
<p>after the retry times it becomes a MsmqPoisonMessageException, it gets a LookupId. With this lookupid I do the ReceiveByLookupId(lookupId) (with the standard System.Messaging.MessageQueue class). This results in a InvalidOperationException.</p>
<p>After this the service will restart itself and the cycle will restart, this never ends. (after reboots, purging of the queue it never stops).</p>
<p>If you open Computer Management and look if there is a message on the queue it's empty. But when I open the p0000001.mq file (in the C:\WINDOWS\system32\msmq\storage) with a text editor you can see the message. If you delete this file, everything works again.
I can't recreate the problem by using the application (I can recreate te problem becaue I saved a corrupt .mq file), it just occures sometimes. </p>
<p>This is not a workable situation.
- Anyone any idea's how I can solve this problem through code or how to prevent it from happening?
- Why is it that the wcf service can see the message, but the MessageQueue with LookupId sees nothing?
- Is there another way to query the queue with a LookupId?
- How can this situation occure? I can see all other messages.</p>
| <p>I finally found my problem. </p>
<p>On the receiving side of the queue I was using a nested transaction scope. When this happend:
- Invalid message received
- Exception
- catch the exception
- Dispose of the nested transaction</p>
<p>But the exception was thrown a little bit early, the nested transaction wasn't openend yet. </p>
<p>I think this infected the transaction of the transactional msmq and the message got locked and unreadable by the poisonhandle. When the service got restarted it could be read again, but got unreadable again because of the dispose of the nested transaction.</p>
<p>(
to replay this behaviour in your receiving operation just type this:
new TransactionScope(TransactionScopeOption.Required).Dispose();
)</p>
|
Microsoft SQL Server 2008 External Backup <p>I would like to save my backups from my SQL 2008 server to another server location.
We have 2 servers:</p>
<ul>
<li>Deployment server</li>
<li>File Server</li>
</ul>
<p>The problem is that the deployment server doesn't have much space. And we keep 10 days backups of our databases. Therefore we need to store our backups on an external "file server". The problem is that SQL doesn't permit this.
I've tried to run the SQL 2008 service with an account that has admin rights on both pc's (domain account), but this still doesn't work.</p>
<p>Any thoughts on this one.
Otherwise we'll have to put an external harddisk on a rack server and that's kinda silly no?</p>
<p><strong>EDIT:</strong></p>
<p>I've found a way to make it work.
You have to share the folder on the server. Then grant the Development Server (the PC itself) write permissions. This will make external backups possible with SQL server.
Don't know if it's safe though, I find it kinda strange to give a computer rights on a folder.</p>
| <p>You can use 3rd party tools like <a href="http://SqlBackupAndFTP.com">SqlBackupAndFTP</a></p>
|
Performance of data <p>I have 60 columns in a table. </p>
<p>1). I want to add one more column to that table. Will there be any impact on performance?</p>
<p>2). How many columns can I add?</p>
<p>3). any idea for the avoid recursion. <em>[I have no idea here - annakata]</em></p>
| <p>Yes, but one more column is less of a problem than the fact that you already have 60.</p>
<p>I bet most of them are nullable?</p>
<p>With very wide tables (many columns) it becomes harder to write maintainable SQL. You are forced to deal with lots of exceptions due to the NULLS.</p>
<p>See also this post which asks <a href="http://stackoverflow.com/questions/220613/how-many-fields-is-too-many-in-a-table">how many fields is too many</a>?</p>
|
Handling WCF Proxy null return issue <p>I have a WCF Client Proxy connected to a third party webservice.
The proxy works fine with nearly everything except on function.</p>
<p>This function works just fine with a ASMX proxy.</p>
<p>I have added service trace logging and can see the response from the service coming back.
Only the proxy returns null.</p>
<p>So now I know for sure that the proxy is at fault.</p>
<p>Where to from here?</p>
<p><strong>RESOLUTION</strong>
I found the issue. WCF is less forgiving than an ASMX proxy.
The service WSDL specifies that the returned object was called "data", and the actual xml passed back was called "result"</p>
<p>So that was a great goose chase! I think i wasted 4 hours on this problem!</p>
| <p>You can try to use Trace Viewer to analyse WCF communications in more detail and find out more detail when errors are encountered. </p>
<p>Within the app.config (Client) and web.config (Server), you can add blocks. To enable tracing, simply add dignostics blocks and trace files will be generated in the specified location when the app is run. This should enable you to dig a little deeper with the problem.</p>
<p>Trace viewer can be found:</p>
<p>("C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\SvcTraceViewer.exe")</p>
<p>Info on trace viewer usage:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa751795.aspx">http://msdn.microsoft.com/en-us/library/aa751795.aspx</a></p>
<p>Also, what type of method is it? does it return complex types or simple types?</p>
<p>ADDED:
Ah, sorry about the mis-read, didn't realise you had no control of server side. I'd try to update the service reference/proxy (you've probably already done that) and check if anything has changed. </p>
<p>WCF doesn't make tracking down issues very easy i'm afraid. Is it possible to provide the method signatures for a call that works and one that doesn't so we can see what data types are being passed about?</p>
|
What is the win32 API function for private bytes? <p>What is the win32 API function for private bytes (the ones you can see in perfmon).</p>
<p>I'd like to avoid the .NET API</p>
| <pre><code>BOOL WINAPI GetProcessMemoryInfo(
__in HANDLE Process,
__out PPROCESS_MEMORY_COUNTERS ppsmemCounters,
__in DWORD cb
);
</code></pre>
<p>ppsmemCounters can be a PROCESS_MEMORY_COUNTERS or PROCESS_MEMORY_COUNTERS_EX structure. </p>
<p>PROCESS_MEMORY_COUNTERS_EX.PrivateUsage is what you're looking for.</p>
<p>More info <a href="http://msdn.microsoft.com/en-us/library/ms683219%28VS.85%29.aspx">here</a> and <a href="http://msdn.microsoft.com/en-us/library/ms684874%28VS.85%29.aspx">here</a></p>
|
Flash toggle button <p>I need a button in Flash/AS3 that toggles between on and off. So I was glad to see that the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/fl/controls/Button.html" rel="nofollow"><code>Button</code></a> class has the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/fl/controls/LabelButton.html#toggle" rel="nofollow"><code>toggle</code></a> property that lets me have that behavior. I was less happy to see that what I get when I make something a "button" in the Flash file is an instance of <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/SimpleButton.html" rel="nofollow"><code>SimpleButton</code></a> class, which does not have that option.</p>
<p>Is there a way to either get a Button instance from the .fla, or get the SimpleButton to behave as a toggle?</p>
| <p>Here's how I coded my way around this:</p>
<pre><code>private buttonState:Boolean;
private function buttonToggle(button:SimpleButton){
var currDown:DisplayObject = button.downState;
button.downState = button.upState;
button.upState = currDown;
buttonState = !buttonState;
}
private function clickEvent(e:MouseEvent){
buttonToggle(e.target);
}
</code></pre>
<p>I didn't put the code in the <code>clickEvent</code> function, because this allows me to toggle the button from elsewhere in the code.</p>
|
Flex memory limit - how to configure <p>Can I control the memory limit (i.e. when GC has to run) in my Flex application?</p>
| <p>Check out the flash.system.System class. The "totalMemory" property will show you (in bytes) how much memory the current application is using. Calling System.gc() will run a GC. You could use a Timer to periodically check totalMemory and then preform gc if it exceeds a threshold. More info:</p>
<p><a href="http://livedocs.adobe.com/flex/3/langref/flash/system/System.html" rel="nofollow">http://livedocs.adobe.com/flex/3/langref/flash/system/System.html</a></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.