input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
C# Why is my code throwing a io.system.directorynotfound? <p>Why would the code below throw a io.system.directorynotfound exception? I can't recreate the problem myself but another user of my code does see it, any ideas why?
Thanks</p>
<pre><code>try
{
//create path
string strAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\MyApp\\Data\\logs";
//check path exists
if (!System.IO.File.Exists(strAppData))
{
System.IO.Directory.CreateDirectory(strAppData);
}
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strAppData);
int count = dir.GetFiles().Length;
if (count > 100)
{
string[] files = System.IO.Directory.GetFiles(strAppData);
foreach (string file in files)
{
System.IO.File.Delete(file);
}
}
this.fileName = fileName;
// delete the file if it exists
if (File.Exists(fileName))
{
//delete the file
File.Delete(fileName);
}
// write the data to the file
fs = File.OpenWrite(fileName);
sWriter = new StreamWriter(fs);
sWriter.WriteLine(headerText);
sWriter.Flush();
sWriter.Close();
}
catch (Exception exp)
{
throw new Exception(exp.Message);
}
</code></pre>
| <p>Have you tried using System.IO.Directory.Exists rather than System.IO.File.Exists when checking to see if the path exists?</p>
|
SharePoint user's AD group membership <p>I've been tasked with creating a SharePoint web part for our new web site. One of the things it needs to know is which AD groups the current user belongs to (each site user will belong to one or more special security groups within the domain.) Is there a part of the SharePoint API that exposes this information, or do I need to query AD directly?</p>
| <p>I would just do an LDAP query directly. This is much simpler and the LDAP interface to Active Directory is well documented.</p>
|
In WSE services, with custom types, do constructors work on the consuming client's side? <p>I have custom types in a WSE web service.</p>
<p>the consuming client can't seem to see my constructor when instantiating a class, is this normal?</p>
| <p>Yes.</p>
<p>Web services do not pass objects, they pass messages. The class on the client side is simply a holder for properties on that message, it will not have implementation beyond that.</p>
|
TransactionScope and multi-threading <p>I was wondering how you would use the TransactionScope class in the correct way when you are dealing with multithreading?</p>
<p>We create a new scope in our main thread and then we spawn of a couple of worker threads and we want these to participate in the main scope, so that for example the rollback is called on each worker if the scope is never completed.</p>
<p>I read something about TransactionScope using the ThreadStaticAttribute internally which made the above impossible / very difficult - could someone verify either way? If we run out code in a syncrhonized fashion then the rollbacks work, i.e the inner transactions are able to participate in the main transaction, but not if we switch over to a threaded execution.</p>
<p>Thanks</p>
| <p>See <a href="http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx">MSDN</a>:</p>
<blockquote>
<p>You should also use the TransactionScope and
DependentTransaction class for
applications that require the use of
the same transaction across multiple
function calls or multiple thread
calls.</p>
</blockquote>
<p>So maybe look into <code>DependentTransaction</code> - in particular, there is a worker thread example, <a href="http://msdn.microsoft.com/en-us/library/system.transactions.dependenttransaction.aspx">here</a>.</p>
|
Wordpress and Widget using TinyMCE <p>I have written a Text/HTML widget that uses TinyMCE to allow some basic formatting. However, when I save the changes, the data in the textarea is not getting posted. If I use just a simple textarea without TinyMCE then I can save the data properly. Any ideas?</p>
| <p>I've experienced this issue recently as well. Just solved it, actually. :)</p>
<p>If you write a PHP function to include your tinyMCE code and run the Javascript init, you can include that in admin_head ( add_action('admin_print_scripts-widgets.php', 'NAME OF YOUR INIT FUNCTION HERE'); ).</p>
<p>Currently I've also go the following in my init function. although I'm not certain it's needed in this context:</p>
<p>wp_enqueue_script('editor');
wp_enqueue_script('editor_functions');
wp_enqueue_script('quicktags');</p>
<p>Hope this helps. :)</p>
|
White papers on logging <p>I am planning to create a logging framework for Java/J2EE from scratch.In this regard I want some white papers on common industry logging standards for reference.Any pointers to the same are appreciated.</p>
| <p>Google 'log4j sucks' or something similar, and try to find out everything you can about what's wrong with the current frameworks. Since they obviously don't meet your needs.</p>
|
RichFaces: Displaying a notification "popup" when AJAX operation succeeded <p>We are currently developing a B2B web shop based on Java EE 5, JSF, Facelets and RichFaces. The technology has really worked very well so far, but now I am facing a small problem I just can't figure out how to solve:</p>
<p>Products are listed as tables, where every item can be added to the shopping basket by clicking on a small icon at the end of the row. Adding the product is done via AJAX to avoid the full reload of the page. This works without any problems just by using a <code>h:dataTable</code> and an <code>a4j:commandLink</code> to call an action-method which adds the selected product to the basket. Even the re-rendering of the basket total always visible in the side-bar is working properly.</p>
<p>Due to the nature of AJAX, there is no visible indication (except the changing total at the side) that the operation was successful or has been completed at least. Now I want to add a little "popup" box, which is made visible next to the add-icon when the AJAX-operation is completed, stating that the item was added to the basket. This box should automatically go away after a few seconds.</p>
<p>This is what I think should work (the popup_message and popup_content css-classes make the box float above the position where its markup is):</p>
<pre><code><h:dataTable ....>
...
<h:column>
<a4j:commandLink action="...">
<rich:effect event="oncomplete" targetId="addedMessage"
type="Appear" />
<rich:effect event="oncomplete" targetId="addedMessage"
type="Appear" params="{delay:3.0, duration:1.0}" />
</a4j:commandLink>
<a4j:outputPanel id="addedMessage" styleClass="popup_message"
style="display: none">
<a4j:outputPanel layout="block" styleClass="popup_content">
<h:outputText value="Item added!" />
</a4j:outputPanel>
</a4j:outputPanel>
</h:column>
</h:dataTable>
</code></pre>
<p>Unfortunately, it doesn't display the box at all. If I change the <code>event</code> of the "Appear" effect to <code>onclick</code> it works almost as expected. It is immediately shown when the icon is clicked and it dissapears 3 seconds after the AJAX operation was completed. But I don't want it to appear immediately after the click, because it would be wrong to indicate that the item was added to the basket, when in fact the operation hasn't even started yet. This becomes even more important, when I want to indicate some error or want to include some item specific information into the box, which is only available after the item was added.</p>
<p>So any ideas how to do this? And why adding two effects for the same event does not work?</p>
<p>(I've already looked at <a href="http://livedemo.exadel.com/richfaces-demo/richfaces/effect.jsf" rel="nofollow">the effect-example from the RichFaces live demo</a>. The examples do almost work the same, execept that they add the second effect with explicitly stating the <code>for</code> attribute. But even this does not work for me.)</p>
<p><strong>Update:</strong> I've tried using the <code>rich:toolTip</code> for this purpose, which actually seems to be quite flexible. But no matter what I do, I can't attach anything to the "oncomplete" (I've also tried just "complete") event of the <code>a4j:commandLink</code>, except one effect... seems there is some bug/undocumented behaviour regarding that event. I've just found this bug report: <a href="https://jira.jboss.org/jira/browse/RF-3427" rel="nofollow">RF-3427</a></p>
| <p>you can try <code>rich:notify</code> for this
<a href="http://showcase.richfaces.org/richfaces/component-sample.jsf?demo=notify&skin=blueSky" rel="nofollow">http://showcase.richfaces.org/richfaces/component-sample.jsf?demo=notify&skin=blueSky</a></p>
|
Binding a static text box to a checkbox <p>I need some help in MFC. The following is my problem:</p>
<ol>
<li>I have two controls a static text and a checkbox</li>
<li>When using MFC Wizard, i place a '&' in front of one of the letters in the static text, while executing if i press Alt+, the checkbox either gets enabled or disabled.</li>
<li>Now my problem is i am adding these controls programaticaly, and even though i have the '&' placed in the static text, if i press the Alt+, it doesn't change the state of the checkbox control.</li>
</ol>
<p>My queries are:</p>
<ol>
<li>Can anyone kindly let me know if there is some binding which has to be done in case we are adding the controls programatically.</li>
<li>If someone can briefly explain how the binding is taken care by MFC it will be gr8 help</li>
</ol>
<p>edit:
One more thing the checkbox won't have any text associated with it.</p>
| <p>Since the static text is not associated with the checkbox control, how can the system know which checkbox it should link? I bet if you look at the TAB ordering and the group settings of the controls, you will arrive at your solution.</p>
|
What is the workaround for unaligned memory access exception on ARM9 using C? <p>Architecture ARM9. Programming Language C.</p>
<p>We have a third-party stack and one of the calls takes a pointer(<code>pBuffer</code>) to a memory location. Within the stack, they are free to move around the pointer passed and access it as they wish. Unfortunately, they offset the passed in pointer and passed it into a another function that tried to do this from an <strong>odd/unalighed</strong> memory location</p>
<pre><code> ((uint16 *)pBuffer)[index] = value;
</code></pre>
<p>where <code>value</code> is of type <code>uint16</code> and <code>index </code> is bounds checked and indexes <code>pBuffer</code>. This causes a unaligned memory access exception. <code>pBuffer</code> points to <code>char *</code> on the heap.</p>
<p>As mentioned, even though we can peek into the third-party stack, we can not update the code officially. So we notify the provider and they provide the update in the next release. </p>
<p>I want to understand if there is a work around for this. How do I perform the above assignment without violating the unaligned access? What is the best approach to resolving such problems.</p>
| <p>Copy the value byte by byte. Cast it to a (unsigned) char pointer, and then copy a byte at a time.</p>
<p>It's not pretty, but it doesn't sound like you have many options.</p>
|
How can I make the Django contrib Admin change list for a particular model class editable with drop downs for related items displayed in the listing? <p>Basically I want to have an editable form for related entries instead of a static listing. </p>
| <p>Try Django 1.1 beta. It's got the option to make items in the changelist editable (as well as incorporating the django-batchadmin project) </p>
|
Django syncdb locking up on table creation <p>I've added new models and pushed to our staging server, run syncdb to create their tables, and it locks up. It gets as far as 'Create table photos_photousertag' and postgres output shows the notice for creation of 'photos_photousertag_id_seq', but otherwise i get nothing on either said. I can't ctrl+c the syncdb process and I have no indication of what route to take from here. Has anyone else ran into this?</p>
| <p>We use postgres, and while we've not run into this particular issue, there are some steps you may find helpful in debugging:</p>
<p>a. What version of postgres and psycopg2 are you using? For that matter, what version of django?</p>
<p>b. Try running the syncdb command with the "--verbosity=2" option to show all output.</p>
<p>c. Find the SQL that django is generating by running the "manage.py sql " command. Run the CREATE TABLE statements for your new models in the postgres shell and see what develops.</p>
<p>d. Turn the error logging, statement logging, and server status logging on postgres way up to see if you can catch any particular messages.</p>
<p>In the past, we've usually found that either option b or option c points out the problem.</p>
|
customize cout <p>How can I derive a class from <code>cout</code> so that, for example, writing to it</p>
<p><code>new_cout << "message";</code></p>
<p>would be equivalent to</p>
<p><code>cout << __FUNCTION__ << "message" << "end of message" << endl;</code></p>
| <pre><code>class Log
{
public:
Log(const std::string &funcName)
{
std::cout << funcName << ": ";
}
template <class T>
Log &operator<<(const T &v)
{
std::cout << v;
return *this;
}
~Log()
{
std::cout << " [end of message]" << std::endl;
}
};
#define MAGIC_LOG Log(__FUNCTION__)
</code></pre>
<p>Hence:</p>
<pre><code>MAGIC_LOG << "here's a message";
MAGIC_LOG << "here's one with a number: " << 5;
</code></pre>
|
Know of any source-control "stash"-like programs? <p>I once ran across a commercial tool for Windows that allowed you to "stash" code changes outside of source control but now I can't remember the name of it. It would copy the current version of a document to a backup location and undo your checkout in source control. You could then reintroduce your backed up changes later. I believe it worked with multiple source control systems. Does anyone know what program I'm trying to describe?</p>
<p>The purpose of my asking is twofold: The first is to find a good way to do this. The second is because I just can't remember what that darn program was and it's driving me crazy.</p>
| <p>Git: <a href="http://git-scm.com/" rel="nofollow">http://git-scm.com/</a></p>
<p>You can use <code>git stash</code> to temporarily put away your current set of changes: <a href="http://git-scm.com/docs/git-stash" rel="nofollow">http://git-scm.com/docs/git-stash</a> . This stores your changes locally (without committing them), and lets you reintroduce them into your working copy later.</p>
<p>Git isn't commercial, but is quickly gaining many converts from tools like Subversion.</p>
|
Common interface for different OpenID providers and Facebook <p>Is stack overflow uisng https://rpxnow.com/ for login in using different services. If so is it good, and does it have good (preferable free, preferable with PHP api) alternatives.</p>
<p>What I'm looking for is a login page wich would allow users to login using major web open-id providers + facebook connect.</p>
| <p>No, StackOverflow does not use RPXNow. And if you choose to use it be careful to avoid <a href="http://blog.nerdbank.net/2009/01/why-using-rpxnow-is-bad-idea.html" rel="nofollow">its pitfalls</a>. </p>
<p>I suggest you just accept OpenID, which covers many, many Providers (who uses Facebook but doesn't use one of Google, Yahoo, and (soon) Microsoft?). Besides, I expect as an OpenID supporter, Facebook will eventually become an OpenID Provider too. So I suggest you save yourself the trouble and just support OpenID using one of the PHP OpenID libraries since that is your language.</p>
|
How can I copy my git revision history into svn? <p>I use Git, but some of my colleagues are unable to move away from SVN right now. We want the integration between the two systems to be seamless -- all of our development has been in git so far, so we need to copy that over into svn with complete revision history. </p>
<p>I've been able to jigger this such that it copies the repository in a single commit, but I would like it to copy <em>all</em> of the history. I would imagine that this should be pretty easy with git svn dcommit, etc., but it hasn't worked out that way -- merges seem to only go in as a single commit, rebasing kills git-svn, and pull just merges.</p>
<p>So, I've been trying things for the last couple of hours, but can't seem to get it. Tailor almost works, but dies amidst import with what appears to be a bug.</p>
<p>All help is appreciated, and thanks again.</p>
| <p>Have you tried creating the svn repository, git-svn clonning it, git-pull'ing from the old git repo (the one with all the history), git-rebase those changes into the master branch, then git-svn dcommitting the changes up to svn? That's just off the top of my head, but might work.</p>
<p>Googling for "git svn export" also showed up this : <a href="http://kerneltrap.org/mailarchive/git/2008/10/29/3848124" rel="nofollow">http://kerneltrap.org/mailarchive/git/2008/10/29/3848124</a> which seems similar to what I've just described, but with more detail and accuracy, which should get you there.</p>
<p>But knowing Git - i'm sure this will be possible for you :)</p>
<p>Let me know how you get on! I'm also interested in this problem...</p>
|
Python, __init__ and self confusion <p>Alright, so I was taking a look at some source when I came across this:</p>
<pre><code>>>> def __parse(self, filename):
... "parse ID3v1.0 tags from MP3 file"
... self.clear()
... try:
... fsock = open(filename, "rb", 0)
... try:
... fsock.seek(-128, 2)
... tagdata = fsock.read(128)
... finally:
... fsock.close()
... if tagdata[:3] == 'TAG':
... for tag, (start, end, parseFunc) in self.tagDataMap.items():
... self[tag] = parseFunc(tagdata[start:end])
... except IOError:
... pass
...
</code></pre>
<p>So, I decided to test it out.</p>
<pre><code> >>> __parse("blah.mp3")
</code></pre>
<p>And, I received this error: </p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __parse() takes exactly 2 arguments (1 given)
</code></pre>
<p>This wouldn't be the first time I've encountered this, I keep thinking I'm meant to include self in the argument parameter list, but I know that that's not right. Could someone explain to me why this happens a lot with code I try to play around with, I suppose its due to my level of understanding about the terms, I barely even understand what init or self does, or why it's relevant. def x(b): print b is the same as def x(self, b): self.b = b print self.b isn't it? Why does it matter so much!</p>
<p>I just want a basic explanation, so I can get this out of my mind,thanks.</p>
| <p>The <code>def __parse</code> was inside some class definition.</p>
<p>You can't pull the method defs out of the class definitions. The method function definition is part of the class.</p>
<p>Look at these two examples:</p>
<pre><code>def add( a, b ):
return a + b
</code></pre>
<p>And</p>
<pre><code>class Adder( object ):
def __init__( self ):
self.grand_total = 0
def add( self, a, b ):
self.grand_total += a+b
return a+b
</code></pre>
<p>Notes.</p>
<ol>
<li><p>The function does not use <code>self</code>.</p></li>
<li><p>The class method does use <code>self</code>. Generally, all instance methods will use <code>self</code>, unless they have specific decorators like <code>@classmethod</code> that say otherwise.</p></li>
<li><p>The function doesn't depend on anything else else.</p></li>
<li><p>The class method depends on being called by an instance of the class <code>Adder</code>; further, it depends on that instance of the class <code>Adder</code> having been initialized correctly. In this case, the initialization function (<code>__init__</code>) has assured that each instance of <code>Adder</code> always has an instance variable named <code>grand_total</code> and that instance variable has an initial value of <code>0</code>.</p></li>
<li><p>You can't pull the <code>add</code> method function out of the <code>Adder</code> class and use it separately. It is not a stand-alone function. It was defined <em>inside</em> the class and has certain expectations because of that location <em>inside</em> the class.</p></li>
</ol>
|
In Python 2.6, How Might You Pass a List Object to a Method Which Expects A List of Arguments? <p>I have a list full of various bits of information that I would like to pass to several strings for inclusion via the new string <code>format</code> method. As a toy example, let us define </p>
<p><code>thelist = ['a', 'b', 'c']</code></p>
<p>I would like to do a print statement like <code>print '{0} {2}'.format(thelist)</code> and <code>print '{1} {2}'.format(thelist)</code></p>
<p>When I run this, I receive the message <code>IndexError: tuple index out of range</code>; when mucking about, it clearly takes the whole list as a single object. I would, of course, rather it translate <code>thelist</code> to <code>'a', 'b', 'c'</code>.</p>
<p>I tried using a tuple and received the same error.</p>
<p>What on Earth is this particular technique called? If I knew the name, I could have searched for it. "Expand" is clearly not it. "Explode" doesn't yield anything useful.</p>
<p>My actual use is much longer and more tedious than the toy example.</p>
| <p><code>.format(*thelist)</code></p>
<p>It's part of the calling syntax in Python. I don't know the name either, and I'm not convinced it has one. See the <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists">tutorial</a>.</p>
<p>It doesn't just work on lists, though, it works for any iterable object.</p>
|
Regarding JavaScript for() loop voodoo <p>I was for quite some time under the impression that a <code>for</code> loop could exist <em>solely</em> in the following format:</p>
<pre><code>for (INITIALIZER; STOP CONDITION; INC(DEC)REMENTER)
{
CODE
}
</code></pre>
<p>This is, however, most <em>definitely</em> not the case; take a look at this JavaScript implementation of the <a href="http://en.wikipedia.org/wiki/Knuth%5Fshuffle">Fisher-Yates Shuffle</a>:</p>
<pre><code>shuffle = function(o)
{
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
</code></pre>
<p>This little snippet completely blows my mind; how in the world is so much going on inside a simple for loop declaration? I mean... it doesn't even open a brace! All of the magic is being done <em>right there</em> inside the <code>for</code> statement. It'd be absolutely wonderful if somebody could provide a relatively thorough explanation as to how in the world this voodoo is doing what it does. Much appreciated in advance.</p>
| <pre><code>shuffle = function(o){
for (
var j, // declare j
x, // declare x
i = o.length; // declare i and set to o.length
i; // loop while i evaluates true
j = parseInt(Math.random() * i), // j=random number up to i
x = o[--i], // decrement i, and look up this index of o
o[i] = o[j], // copy the jth value into the ith position
o[j] = x // complete the swap by putting the old o[i] into jth position
);
return o;
};
</code></pre>
<p>This is starting with i equal to the number of positions, and each time swapping the cards i and j, where j is some random number up to i each time, as per the algorithm.</p>
<p>It could be more simply written without the confusing comma-set, true.</p>
<p>By the way, this is <strong>not</strong> the only kind of for loop in javascript. There is also:</p>
<pre><code> for(var key in arr) {
value = arr[key]);
}
</code></pre>
<p>But be careful because this will also loop through the properties of an object, including if you pass in an Array object.</p>
|
ClickOnce deployment for restricted users <p>From firsthand experience, it appears that ClickOnce only installs for the current user, and there is no option to install for all users. This is a problem because some users within the company need to use ClickOnce applications but do not have permissions to install applications (for security reasons).</p>
<p>So far, the only solution we have to this problem is to grant the user in question permission to install programs, let them install the ClickOnce program, and then revoke their privileges. It seems as if there should be a better solution for this problem.</p>
<p>Any suggestions?</p>
<p>Thanks.</p>
| <p>ClickOnce should allow these users to install anyway. That's the point of ClickOnce: it allows restricted users to install your app. Otherwise you could just distribute an msi using group policy.</p>
|
Where to get D for .Net <p>Where can I get D for the .Net framework?</p>
| <p>(Heavily edited.)</p>
<p>Assuming you mean <a href="http://en.wikipedia.org/wiki/D%5Fprogramming%5Flanguage" rel="nofollow">D the programming language</a>, you can't currently do so. The currently released D compilers compile to native code, not managed code. A port is in progress, and this <a href="http://www.infoq.com/news/2009/03/D-NET" rel="nofollow">recent InfoQ interview</a> which may be of interest for more information.</p>
<p><a href="http://stackoverflow.com/questions/539234/using-d-programming-language-in-a-net-context">This existing question</a> has other information and links.</p>
|
Go to the end of the C++ function in Vim <p>If I am in the middle of the function, I would like go to the very end of it in vim. I run into this problem as we sometimes have function of 500+ lines long (don't ask why). </p>
<p>I use vim, gvim.</p>
| <p><code>][</code> goes to the next '}' in the first column.</p>
<p>Read <code>:help 29.3</code> to find out more about moving through a program.</p>
|
What is the question mark's significance in MySQL at "WHERE column = ?"? <p>I am dissecting some code and came across this, </p>
<pre><code>$sql = 'SELECT page.*, author.name AS author, updator.name AS updator '
. 'FROM '.TABLE_PREFIX.'page AS page '
. 'LEFT JOIN '.TABLE_PREFIX.'user AS author ON author.id = page.created_by_id '
. 'LEFT JOIN '.TABLE_PREFIX.'user AS updator ON updator.id = page.updated_by_id '
. 'WHERE slug = ? AND parent_id = ? AND (status_id='.Page::STATUS_REVIEWED.' OR status_id='.Page::STATUS_PUBLISHED.' OR status_id='.Page::STATUS_HIDDEN.')';
</code></pre>
<p>I am wondering what the "?" does in the WHERE statement. Is it some sort of parameter holder?</p>
| <p>Prepared statments use the '?' in MySQL to allow for binding params to the statement. Highly regarded as more secure against SQL injections if used properly. This also allows for quicker SQL queries as the request only has to be compiled once and can be reused.</p>
|
How can I access runat="server" ASP element using javascript? <p>It seems everyone is doing this (in code posts etc.)...but I dont' know how :(</p>
<p>whenever i try to manipulate an asp element using javascript i get a "element is null" or "document is undefined" etc. error.....</p>
<p>javascript works fine usually,...but only when i add the runat="server" attribute does the element seem invisible to my javascript.</p>
<p>any suggestions would be appreciated</p>
<p>Thanks, Andrew</p>
| <p>What's probably happening is that your element/control is within one or more ASP.NET controls which act as naming containers (Master page, ITemplate, Wizard, etc), and that's causing its ID to change.</p>
<p>You can use "view source" in your browser to confirm that's what's happening in the rendered HTML.</p>
<p>If your JavaScript is in the ASPX page, the easiest way to temporarily work around that is to <a href="http://encosia.com/2007/08/08/robust-aspnet-control-referencing-in-javascript/">use the element's ClientID property</a>. For example, if you had a control named TextBox1 that you wanted to reference via JS:</p>
<pre><code>var textbox = document.getElementById('<%= TextBox1.ClientID %>');
</code></pre>
|
Regular expression for finding a regular expression? <p>Does anyone have code for finding a file that contains a regular expression? I would assume you could have two different flavors, one for BREs and one for EREs.</p>
<p>You would think some kind of test suites would have something like an isRegex() test. Can anyone have any code? Looking for something comprehensive of course.</p>
<p>I see this was discussed <a href="http://stackoverflow.com/questions/416438/regular-expression-contains-another-regular-expression">here</a> but didn't see any practical responses. If I want to grep for any file that contains a regular expression, perhaps bounded by the typical //, how would I do it?</p>
| <p>Regular expressions are themselves not a <a href="http://en.wikipedia.org/wiki/Regular%5Flanguage">regular language</a>. The clue is that they contain parentheses and square brackets and such that must be balanced. </p>
<p>A regular expression itself can be described by a <a href="http://en.wikipedia.org/wiki/Context-free%5Fgrammar">context-free grammar</a>, and parsed with a <a href="http://en.wikipedia.org/wiki/Recursive%5Fdescent%5Fparser">recursive-descent parser</a>.</p>
|
inspect javascript calls for gmail's buttons <p>i'm working on a greasemonkey script for gmail in which it'd be very useful to know what function call is made when the "send" button is clicked. (i was unable to find this using firebug, but am relatively new to javascript debugging.) it seems that one should be able to detect this, i just don't know what tool(s) to use.</p>
<p>thanks very much for any help.</p>
<p>p.s. ultimately the goal here is to be able to extract a unique message i.d. for outgoing gmail messages, which i figured would be present in this javascript call -- so if there's an alternate way to do this, that would work just as well.</p>
| <p>Gmail's Javascript code is obfuscated to avoid this type of inspection (and also to reduce code size). It is very unlikely you'll be able to make heads or tails of it even if you manage to get Firebug to breakpoint in the code properly.</p>
|
TLS connection with timeouts (and a few other difficulties) <p>I have a HTTP client in Python which needs to use TLS. I need not only
to make encrypted connections but also to retrieve info from the
remote machine, such as the certificate issuer. I need to make
connection to many HTTP servers, often badly behaved, so I absolutely
need to have a timeout. With non-TLS connections,
<code>mysocket.settimeout(5)</code> does what I want.</p>
<p>Among the many TLS Python modules:</p>
<p><a href="http://pypi.python.org/pypi/python-gnutls" rel="nofollow">python-gnutls</a> does not allow to use settimeout() on sockets because
it uses non-blocking sockets:</p>
<pre><code>gnutls.errors.OperationWouldBlock: Function was interrupted.
</code></pre>
<p><a href="http://pyopenssl.sourceforge.net/" rel="nofollow">python-openssl</a> has a similar issue:</p>
<pre><code>OpenSSL.SSL.WantReadError
</code></pre>
<p>The <a href="http://docs.python.org/library/ssl.html" rel="nofollow">SSL module</a> of the standard library does not work with Python
2.5.</p>
<p>Other libraries like <a href="http://trevp.net/tlslite/" rel="nofollow">TLSlite</a> apparently does not give access to
the metadata of the certificate.</p>
<p>The program is threaded so I cannot use signals. I need detailed
control on the HTTP dialog so I cannot use a standard library like urllib2.</p>
<p>Background: this is
the survey project <a href="http://www.dnswitness.net/" rel="nofollow">DNSwitness</a>. Relevant SO threads: <a href="http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call">Timeout on a
Python function call</a> and <a href="http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python">How to limit execution time of a function call in Python</a>.</p>
| <p>Although I've never used it for exactly this purpose, <a href="http://twistedmatrix.com" rel="nofollow">Twisted</a> should do what you want. The only downside is that it's a rather large library, and you will also need to install <a href="http://pyopenssl.sourceforge.net/" rel="nofollow">PyOpenSSL</a> (Twisted depends on it). If you've never used it before, Twisted's callback-based architecture can take some getting used to (you <strong>really</strong> want to read the tutorials before starting).</p>
<p>But aside from that, it's designed around the idea of managing a lot of connections, it of course lets you specify timeouts, reconnects, etc., and you can retrieve certificate info (see <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.ssl.Certificate.html" rel="nofollow">here</a>).</p>
|
python class __getitem__ negative index handling <p>Is there a common function to do this? Right now I'm just doing the following (and overriding __len__)</p>
<pre><code>idx < 0:
idx = len(self) + idx
if idx < 0 or idx >= len(self):
raise IndexError, "array index (%d) out of range [0, %d)" %(idx, len(self))
</code></pre>
| <p>That seems fine to me. I don't think there is a better or built-in way to do that; overriding is about providing your own functionality, after all.</p>
<p>Edited to remove rather stupid suggestion.</p>
|
Javascript menu conflict <p>I'm having a Javascript conflict. I have a vertical javascript left nav menu and a horizontal javascript time zone menu. Working code for both but when I call them within the same page, the menu tree does not work. If i take out the <code><SCRIPT src="timezone.js" type=text/javascript></SCRIPT></code> tag the menu works fine but the time zone is negated. <code><div></code> issue?</p>
<h2>html</h2>
<pre><code> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta http-equiv="Content-Language" content="en-us" />
<title>TEST</title>
<link rel="stylesheet" type="text/css" href="test.css" />
<SCRIPT src="BarMenu.js" type=text/javascript></SCRIPT>
</head>
<body onload="startw();" style="background-color: #808080">
<SCRIPT type=text/javascript>
/* preload images, you can remove this code */
img1 = new Image();
img1.src = "images/tree-node.gif";
img2 = new Image();
img2.src = "images/tree-node-open.gif";
img3 = new Image();
img3.src = "images/tree-leaf.gif";
img4 = new Image();
img4.src = "images/tree-leaf-last.gif";
window.onload = function() {
var barMenu3a = new BarMenu('bar-menu3a');
barMenu3a.box1Hover = false;
barMenu3a.box2Hover = false;
barMenu3a.init();
var barMenu3b = new BarMenu('bar-menu3b');
barMenu3b.box1Hover = false;
barMenu3b.box2Hover = false;
barMenu3b.init();
var barMenu3c = new BarMenu('bar-menu3c');
barMenu3c.box1Hover = false;
barMenu3c.box2Hover = false;
barMenu3c.init();
}
</SCRIPT>
<table id="MainTable" cellspacing="0" cellpadding="0" style="width: 800px" class="style8">
<tr>
<td colspan="2" style="height: 91px" class="style10">
<span class="FooterText"> <br />
</span><br />
</td>
<tr>
<td colspan="2">
<SCRIPT src="timezone.js" type=text/javascript></SCRIPT>
<div id="zonediv" class="GreenBar"></div>
</td>
</tr>
<tr>
<td valign="top" style="width: 200px" class="LeftNav">
<DIV class=left>
<TABLE cellSpacing=0 cellPadding=0 width="100%">
<TBODY>
<TR>
<TD class=top>» Products</TD></TR>
<TR>
<TD class=section>
<DIV class=bar-menu id=bar-menu3a>
<TABLE cellSpacing=0 cellPadding=0 width="100%">
<TBODY>
<TR>
<TD>
<DIV><SPAN class=box1>Product One</SPAN></DIV>
<DIV class=section>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Overview</A></DIV>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Features</A></DIV>
<DIV class=box2-last><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Requirements</A></DIV></DIV></TD></TR>
<TR>
<TD height=2></TD></TR>
<TR>
<TD>
<DIV><SPAN class=box1>Product Two</SPAN></DIV>
<DIV class=section>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Overwiev</A></DIV>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Features</A></DIV>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Requirements</A></DIV>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Screenshots</A></DIV>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Flash
Demos</A></DIV>
<DIV class=box2-last><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Live
Demo</A></DIV></DIV></TD></TR>
<TR>
<TD height=2></TD></TR>
<TR>
<TD>
<DIV><SPAN class=box1>Product Three</SPAN></DIV>
<DIV class=section>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Overview</A></DIV>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Features</A></DIV>
<DIV class=box2-last><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Requirements</A></DIV></DIV></TD></TR>
<TR>
<TD height=2></TD></TR>
<TR>
<TD>
<DIV><SPAN class=box1>Product Four</SPAN></DIV>
<DIV class=section>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Overview</A></DIV>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Features</A></DIV>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Requirements</A></DIV>
<DIV class=box2><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Screenshots</A></DIV>
<DIV class=box2-last><A
href="http://www.gosu.pl/MyGosuMenu/demo/BarMenu/example3.html">Live
Demo</A></DIV></DIV></TD></TR></TBODY></TABLE></DIV></TD></TR>
</TBODY></TABLE></DIV>
</td></tr></tr>
</table>
</body>
</html>
</code></pre>
<h2>BarMenu.js</h2>
<pre><code>function BarMenu(id) {
this.box1Hover = true;
this.box2Hover = true;
this.highlightActive = false;
this.init = function() {
if (!document.getElementById(this.id)) {
alert("Element '"+this.id+"' does not exist in this document. BarMenu cannot be initialized");
return;
}
this.parse(document.getElementById(this.id).childNodes, this.tree, this.id);
this.load();
if (window.attachEvent) {
window.attachEvent("onunload", function(e) { self.save(); });
} else if (window.addEventListener) {
window.addEventListener("unload", function(e) { self.save(); }, false);
}
}
this.parse = function(nodes, tree, id) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].nodeType != 1) {
continue;
}
if (nodes[i].className) {
if ("box1" == nodes[i].className.substr(0, 4)) {
nodes[i].id = id + "-" + tree.length;
tree[tree.length] = new Array();
eval('nodes[i].onmouseover = function() { self.box1over("'+nodes[i].id+'"); }');
eval('nodes[i].onmouseout = function() { self.box1out("'+nodes[i].id+'"); }');
eval('nodes[i].onclick = function() { self.box1click("'+nodes[i].id+'"); }');
}
if ("section" == nodes[i].className) {
id = id + "-" + (tree.length - 1);
nodes[i].id = id + "-section";
tree = tree[tree.length - 1];
}
if ("box2" == nodes[i].className.substr(0, 4)) {
nodes[i].id = id + "-" + tree.length;
tree[tree.length] = new Array();
eval('nodes[i].onmouseover = function() { self.box2over("'+nodes[i].id+'", "'+nodes[i].className+'"); }');
eval('nodes[i].onmouseout = function() { self.box2out("'+nodes[i].id+'", "'+nodes[i].className+'"); }');
}
}
if (this.highlightActive && nodes[i].tagName && nodes[i].tagName == "A") {
if (document.location.href == nodes[i].href) {
nodes[i].className = (nodes[i].className ? ' active' : 'active')
}
}
if (nodes[i].childNodes) {
this.parse(nodes[i].childNodes, tree, id);
}
}
}
this.box1over = function(id) {
if (!this.box1Hover) return;
if (!document.getElementById(id)) return;
document.getElementById(id).className = (this.id_openbox == id ? "box1-open-hover" : "box1-hover");
}
this.box1out = function(id) {
if (!this.box1Hover) return;
if (!document.getElementById(id)) return;
document.getElementById(id).className = (this.id_openbox == id ? "box1-open" : "box1");
}
this.box1click = function(id) {
if (!document.getElementById(id)) {
return;
}
var id_openbox = this.id_openbox;
if (this.id_openbox) {
if (!document.getElementById(id + "-section")) {
return;
}
this.hide();
if (id_openbox == id) {
if (this.box1hover) {
document.getElementById(id_openbox).className = "box1-hover";
} else {
document.getElementById(id_openbox).className = "box1";
}
} else {
document.getElementById(id_openbox).className = "box1";
}
}
if (id_openbox != id) {
this.show(id);
var className = document.getElementById(id).className;
if ("box1-hover" == className) {
document.getElementById(id).className = "box1-open-hover";
}
if ("box1" == className) {
document.getElementById(id).className = "box1-open";
}
}
}
this.box2over = function(id, className) {
if (!this.box2Hover) return;
if (!document.getElementById(id)) return;
document.getElementById(id).className = className + "-hover";
}
this.box2out = function(id, className) {
if (!this.box2Hover) return;
if (!document.getElementById(id)) return;
document.getElementById(id).className = className;
}
this.show = function(id) {
if (document.getElementById(id + "-section")) {
document.getElementById(id + "-section").style.display = "block";
this.id_openbox = id;
}
}
this.hide = function() {
document.getElementById(this.id_openbox + "-section").style.display = "none";
this.id_openbox = "";
}
this.save = function() {
if (this.id_openbox) {
this.cookie.set(this.id, this.id_openbox);
} else {
this.cookie.del(this.id);
}
}
this.load = function() {
var id_openbox = this.cookie.get(this.id);
if (id_openbox) {
this.show(id_openbox);
document.getElementById(id_openbox).className = "box1-open";
}
}
function Cookie() {
this.get = function(name) {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var a = cookies[i].split("=");
if (a.length == 2) {
a[0] = a[0].trim();
a[1] = a[1].trim();
if (a[0] == name) {
return unescape(a[1]);
}
}
}
return "";
}
this.set = function(name, value) {
document.cookie = name + "=" + escape(value);
}
this.del = function(name) {
document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
var self = this;
this.id = id;
this.tree = new Array();
this.cookie = new Cookie();
this.id_openbox = "";
}
if (typeof String.prototype.trim == "undefined") {
String.prototype.trim = function() {
var s = this.replace(/^\s*/, "");
return s.replace(/\s*$/, "");
}
}
</code></pre>
<h2>timezone.js</h2>
<pre><code>var wd=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var D=[['Bucharest',120,60],['Madrid',60,60],['New York',-300,60],['Nairobi',180,0]]//city,standard time zone(minutes), DST(minutes)
//add in the array your cities,STZ, DST
function calc(){
var spans=document.getElementById('zonediv').getElementsByTagName('span')
for(var i=0;i<D.length;i++){
var t=new Date();
t.setTime(t.getTime()+(t.getTimezoneOffset()*60000)+((D[i][1]+D[i][2])*60000));//the zone's time
var Dy=t.getFullYear();
var Dd=t.getDate()<10?'0'+t.getDate():t.getDate();
var Dm=t.getMonth()<10?'0'+(t.getMonth()+1):t.getMonth()+1;
var Dh=t.getHours()<10?'0'+t.getHours():t.getHours();
var Di=t.getMinutes()<10?'0'+t.getMinutes():t.getMinutes();
var Ds=t.getSeconds()<10?'0'+t.getSeconds():t.getSeconds();
var Dz=wd[t.getDay()];
spans[i].firstChild.data=Dh+':'+Di+':'+Ds;
}
setTimeout('calc()',1000)
}
onload=function(){
var root = document.getElementById('zonediv');
for(var i=0;i<D.length;i++){
root.appendChild(document.createTextNode(D[i][0]+' '))
var sp= document.createElement('span');
sp.appendChild(document.createTextNode('span'));
root.appendChild(sp);root.appendChild(document.createTextNode(' | '));
}
calc();
}
</code></pre>
<h2>test.css</h2>
<pre><code>/* Left Navigation Menu */
DIV.left {
background-image: url('images/LeftNav.gif'); WIDTH: 190px; HEIGHT: 100%
}
TD.top {
FONT-WEIGHT: bold; FONT-SIZE: 13px; COLOR: #D5D7C0; TEXT-INDENT: 10px; LINE-HEIGHT: 26px; font-family: Verdana;
background-color:#3D3D3D;
/*background-image: url('images/LeftNav.gif');*/
}
TD.section {
PADDING-RIGHT: 12px; PADDING-LEFT: 12px; PADDING-BOTTOM: 6px; PADDING-TOP: 6px
}
.bar-menu {
moz-user-select: none
}
.bar-menu .box1 {
PADDING-LEFT: 19px; BACKGROUND: url(images/tree-node.gif) no-repeat; CURSOR: default
}
.bar-menu .box1-open {
PADDING-LEFT: 19px; BACKGROUND: url(images/tree-node-open.gif) no-repeat; CURSOR: default
}
.bar-menu .box1 {
font-family: Verdana;
font-size: 13px;
color:#3D3D3D;
}
.bar-menu .box1-open {
font-family: Verdana;
font-size: 11px;
color:#3D3D3D;
}
UNKNOWN {
FONT-SIZE: 12px; PADDING-BOTTOM: 1px; COLOR: #000000; LINE-HEIGHT: 16px; FONT-FAMILY: arial
}
HTML .bar-menu .box1 {
FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY: arial; HEIGHT: 16px
}
HTML .bar-menu .box1-open {
FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY: arial; HEIGHT: 16px
}
.bar-menu .section {
DISPLAY: none; FONT-SIZE: 12px; LINE-HEIGHT: 16px; FONT-FAMILY: arial
}
.bar-menu .section A {
COLOR: #000000; WHITE-SPACE: nowrap; TEXT-DECORATION: none
}
.bar-menu .section A:hover {
COLOR: #0000ff; WHITE-SPACE: nowrap; TEXT-DECORATION: none
}
.bar-menu .box2 {
PADDING-LEFT: 19px; BACKGROUND: url(images/tree-leaf.gif) no-repeat
}
.bar-menu .box2-last {
PADDING-LEFT: 19px; BACKGROUND: url(images/tree-leaf-last.gif) no-repeat
}
</code></pre>
| <p>They're both setting window.onload.</p>
<p>The quick fix is to change timezone.js from this:</p>
<pre><code>onload=function(){
var root = document.getElementById('zonediv');
...
</code></pre>
<p>to this</p>
<pre><code>var oldOnload = window.onload;
window.onload = function()
{
if (oldOnload)
oldOnload();
var root = document.getElementById('zonediv');
...
</code></pre>
|
Unable to show siteA's content at siteB by domain masking <p>I have a domain <em>www.siteA.com</em>, which uses Joomla, while the domain <em>www.siteB.com</em> is empty.</p>
<p>I would like to show the content of the domain <em>www.siteA.com</em> at <em>www.siteB.com</em>.</p>
<p>I tried to solve the problem first by making a domain redirection by <strong>.htaccess</strong>, but I could not show SiteA's content at SiteB.</p>
<p><strong>How can you show the contents of mysiteA.com at mysiteB.com by domain masking in .htaccess?</strong></p>
| <pre><code>RewriteEngine On
RewriteRule ^.*$ http://www.siteA.tld/$1 [NC]
</code></pre>
<p>This should rewrite every request to siteA.</p>
|
Tab-completion in Python interpreter in OS X Terminal <p>Several months ago, I wrote a <a href="http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html">blog post</a> detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that I sometimes have to switch to the standard interpreter due to IPython unicode issues.</p>
<p>Recently I've done some work in OS X. To my discontent, the script doesn't seem to work for OS X's Terminal application. I'm hoping some of you with experience in OS X might be able to help me trouble-shoot it so it can work in Terminal, as well.</p>
<p>I am reproducing the code below</p>
<pre><code>import atexit
import os.path
try:
import readline
except ImportError:
pass
else:
import rlcompleter
class IrlCompleter(rlcompleter.Completer):
"""
This class enables a "tab" insertion if there's no text for
completion.
The default "tab" is four spaces. You can initialize with '\t' as
the tab if you wish to use a genuine tab.
"""
def __init__(self, tab=' '):
self.tab = tab
rlcompleter.Completer.__init__(self)
def complete(self, text, state):
if text == '':
readline.insert_text(self.tab)
return None
else:
return rlcompleter.Completer.complete(self,text,state)
#you could change this line to bind another key instead tab.
readline.parse_and_bind('tab: complete')
readline.set_completer(IrlCompleter('\t').complete)
# Restore our command-line history, and save it when Python exits.
history_path = os.path.expanduser('~/.pyhistory')
if os.path.isfile(history_path):
readline.read_history_file(history_path)
atexit.register(lambda x=history_path: readline.write_history_file(x))
</code></pre>
<p>Note that I have slightly edited it from the version on my blog post so that the <code>IrlCompleter</code> is initialized with a true tab, which seems to be what is output by the Tab key in Terminal.</p>
| <p>This should work under Leopard's python:</p>
<pre><code>import rlcompleter
import readline
readline.parse_and_bind ("bind ^I rl_complete")
</code></pre>
<p>Whereas this one does not:</p>
<pre><code>import readline, rlcompleter
readline.parse_and_bind("tab: complete")
</code></pre>
<p>Save it in ~/.pythonrc.py and execute in .bash_profile</p>
<pre><code>export PYTHONSTARTUP=$HOME/.pythonrc.py
</code></pre>
|
Mimic AES_ENCRYPT and AES_DECRYPT functions in Ruby <p>I need to mimic what MySQL does when encrypting and decrypting strings using built-in functions AES_ENCRYPT() and AES_DECRYPT().</p>
<p>I have read a couple of blog posts and apparently MySQL uses AES 128-bit encryption for those functions. On top of that, since this encryption requires a 16-bit key, MySQL pads the string with x0 chars (\0s) until it's 16-bit in size.</p>
<p>The algorithm in C from MySQL source code is spotted <a href="http://gtowey.blogspot.com/2009/01/mysql-aes-encryption-compatability.html" rel="nofollow">here</a>.</p>
<p>Now I need to replicate what MySQL does in a Rails application, but every single thing I tried, doesn't work. </p>
<p>Here's a way to replicate the behavior I am getting:</p>
<p>1) Create a new Rails app</p>
<pre><code>rails encryption-test
cd encryption-test
</code></pre>
<p>2) Create a new scaffolding</p>
<pre><code>script/generate scaffold user name:string password:binary
</code></pre>
<p>3) Edit your config/database.yml and add a test MySQL database</p>
<pre><code>development:
adapter: mysql
host: localhost
database: test
user: <<user>>
password: <<password>>
</code></pre>
<p>4) Run the migration</p>
<pre><code>rake db:migrate
</code></pre>
<p>5) Enter console, create an user and update its password from MySQL query</p>
<pre><code>script/console
Loading development environment (Rails 2.2.2)
>> User.create(:name => "John Doe")
>> key = "82pjd12398JKBSDIGUSisahdoahOUASDHsdapdjqwjeASIduAsdh078asdASD087asdADSsdjhA7809asdajhADSs"
>> ActiveRecord::Base.connection.execute("UPDATE users SET password = AES_ENCRYPT('password', '#{key}') WHERE name='John Doe'")
</code></pre>
<p>That's where I got stuck. If I attempt to decrypt it, using MySQL it works:</p>
<pre><code>>> loaded_user = User.find_by_sql("SELECT AES_DECRYPT(password, '#{key}') AS password FROM users WHERE id=1").first
>> loaded_user['password']
=> "password"
</code></pre>
<p>However if I attempt to use OpenSSL library, there's no way I can make it work:</p>
<pre><code>cipher = OpenSSL::Cipher::Cipher.new("AES-128-ECB")
cipher.padding = 0
cipher.key = key
cipher.decrypt
user = User.find(1)
cipher.update(user.password) << cipher.final #=> "########gf####\027\227"
</code></pre>
<p>I have tried padding the key:</p>
<pre><code>desired_length = 16 * ((key.length / 16) + 1)
padded_key = key + "\0" * (desired_length - key.length)
cipher = OpenSSL::Cipher::Cipher.new("AES-128-ECB")
cipher.key = key
cipher.decrypt
user = User.find(1)
cipher.update(user.password) << cipher.final #=> ""|\e\261\205:\032s\273\242\030\261\272P##"
</code></pre>
<p>But it really doesn't work.</p>
<p>Does anyone have a clue on how can I mimic the MySQL AES_ENCRYPT() and AES_DECRYPT() functions behavior in Ruby?</p>
<p>Thanks! </p>
| <p>For future reference:</p>
<p>According to the blog post I sent before, here's how MySQL works with
the key you provide AES_ENCRYPT / DECRYPT:</p>
<blockquote>
<p>"The algorithm just creates a 16 byte
buffer set to all zero, then loops
through all the characters of the
string you provide and does an
assignment with bitwise OR between the
two values. If we iterate until we
hit the end of the 16 byte buffer, we
just start over from the beginning
doing ^=. For strings shorter than 16
characters, we stop at the end of the
string."</p>
</blockquote>
<p>I don't know if you can read C, but here's the mentioned snippet:</p>
<p><a href="http://pastie.org/425161">http://pastie.org/425161</a></p>
<p>Specially this part:</p>
<pre><code>bzero((char*) rkey,AES_KEY_LENGTH/8); /* Set initial key */
for (ptr= rkey, sptr= key; sptr < key_end; ptr++,sptr++)
{
if (ptr == rkey_end)
ptr= rkey; /* Just loop over tmp_key until we used all key */
*ptr^= (uint8) *sptr;
}
</code></pre>
<p>So I came up with this method (with a help from Rob Biedenharn, from ruby forum):</p>
<pre><code>def mysql_key(key)
final_key = "\0" * 16
key.length.times do |i|
final_key[i%16] ^= key[i]
end
final_key
end
</code></pre>
<p>That, given a string returns the key MySQL uses when encrypting and decrypting. So all you need now is:</p>
<pre><code>def aes(m,k,t)
(aes = OpenSSL::Cipher::AES128.new("ECB").send(m)).key = k
aes.update(t) << aes.final
end
def encrypt(key, text)
aes(:encrypt, key, text)
end
def decrypt(key, text)
aes(:decrypt, key, text)
end
</code></pre>
<p>To use openssl lib, built into ruby, and then you can make the two "final" methods:</p>
<pre><code>def mysql_encrypt(s, key)
encrypt(mysql_key(key), s)
end
def mysql_decrypt(s, key)
decrypt(mysql_key(key), s)
end
</code></pre>
<p>And you're set! Also, complete code can be found in this Gist:</p>
<p><a href="http://gist.github.com/84093">http://gist.github.com/84093</a></p>
<p>:-)</p>
|
What's the best way to embed HTML within a HTML page in a content management system? <p>I'm in the process of building a content management system for a scientific journal. The system is designed with content "blocks" that editors can manipulate using the FCKEditor. I am trying to display these "blocks" read-only in the system without the editor. My concern is "rogue" HTML that could break the rest of the page if the HTML isn't valid. I was thinking of using an <em>iframe</em> to segregate the blocks from the rest of the page. </p>
<p>Is there a better way to segregate the HTML "data"? Maybe something I haven't thought of?</p>
| <p>Just let them put anything they want on FCKEditor, and before saving it to the database use <a href="http://htmlpurifier.org/" rel="nofollow">http://htmlpurifier.org/</a> to filter out all the "bad html"</p>
|
How do I parameterize an extended Collection <p>I've been trying to extend the ArrayList class without much success. I want to extend it, and be able to parameterize it.</p>
<p>So normally you have something like</p>
<pre><code>ArrayList<SomeObject> list = new ArrayList<SomeObject>();
</code></pre>
<p>I want </p>
<pre><code>MyList<SomeObject> list = new MyList<SomeObject>();
</code></pre>
<p>Simply extending ArrayList doesn't work.</p>
<pre><code>public class MyList extends ArrayList ...
</code></pre>
<p>The when I try to use it I get the error</p>
<blockquote>
<p>The type MyList is not generic; it
cannot be parameterized with arguments
<SomeObject></p>
</blockquote>
<p>I've tried variations of </p>
<pre><code>public class MyList extends ArrayList<Object>
public class MyList<SubObject> extends ArrayList<Object>
</code></pre>
<p>with no success, If I use the subobject behind the class name it appears to work, but hides methods in the subobject class for some reason.</p>
<p>Any thoughts or suggestions on how to get this working right are appreciated.</p>
| <p>You need to specify a type for the <code>ArrayList</code>'s type parameter. For generic type parameters, <code>T</code> is fairly common. Since the compiler doesn't know what a <code>T</code> is, you need to add a type parameter to <code>MyList</code> that can have the type passed in. Thus, you get:</p>
<pre><code>public class MyList<T> extends ArrayList<T>
</code></pre>
<p>Additionally, you may want to consider implementing <code>List</code> and delegating to an <code>ArrayList</code>, rather than inheriting from <code>ArrayList</code>. "Favor object composition over class inheritance. [<em>Design Patterns</em> pg. 20]"</p>
|
How do i use a hashing computed column after i have indexed a varchar(max) field? <p>I created a computed column of type varbinary and referenced a varchar(max) field. Now, how do i use or invoke it? </p>
<p>thanks</p>
| <pre><code>SELECT
computedcolumn
FROM
table
</code></pre>
<p>For indexing, look for "computed columns" in the <a href="http://msdn.microsoft.com/en-us/library/ms188783%28SQL.90%29.aspx" rel="nofollow">CREATE INDEX</a> statment. There are rules such as deterministic, and no longer than 900 bytes etc.</p>
<p>Is this what you wanted?</p>
|
DDL not executing properly inside of an IF NOT EXISTS statement on SQL Server 2005 <p>I have a fairly complex database that needs to be deployed to a variety of servers which may or may not potentially have existing parts of the DB already implemented on it. To work around this contingency I have setup the following test:</p>
<pre><code>USE [testDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[wcSites]') AND type in (N'U'))
begin
CREATE TABLE [dbo].[wcSites](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[siteCSS] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[masterTemplate] [int] NULL,
[errorPage] [int] NULL,
[homePage] [int] NULL,
[addressProduction] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[addressTest] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[routeHandler] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[publish] [bit] NOT NULL CONSTRAINT [DF_wcSites_publish] DEFAULT ((0)),
[publicAccess] [bit] NOT NULL CONSTRAINT [DF_wcSites_publicAccess] DEFAULT ((1)),
[siteAccessPermission] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[contentOwner] [int] NULL,
[navStyle] [int] NULL,
[incScripts] [int] NULL,
[boxW] [int] NULL,
[boxH] [int] NULL,
[columns] [int] NULL,
[rows] [int] NULL,
CONSTRAINT [PK_wcSites] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_wcSites_Unique_Address] UNIQUE NONCLUSTERED
(
[addressProduction] ASC,
[addressTest] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Ensure unique addresses in the addressProduction, addressTest fields' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'wcSites', @level2type=N'CONSTRAINT',@level2name=N'IX_wcSites_Unique_Address'
end
</code></pre>
<p>And the end result is always:</p>
<pre><code>Msg 102, Level 15, State 1, Line 32
Incorrect syntax near 'PRIMARY'.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'end'.
</code></pre>
<p>If I test the IF statement, it works correctly:</p>
<pre><code>IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[wcSites]') AND type in (N'U'))
begin
PRINT 'Table does not exist'
end
</code></pre>
<p>And likewise when I test the CREATE TABLE script. But when I put the CREATE TABLE script inside of the begin..end block it fails every time. And I have the problem across the board, almost every table that uses this method fails.</p>
| <p>Try removing the 'go' statements within the begin..end block, see if that helps.</p>
|
C#: "The table 'sometable' cannot be the child table to itself in nested relations." <pre><code>public string GetArtistThumbnail(string artistName)
{
var request =
WebRequest.Create("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" + artistName +
"&api_key=" +
APIKey) as HttpWebRequest;
using (var response = request.GetResponse() as HttpWebResponse)
{
var ds = new DataSet();
ds.ReadXml(response.GetResponseStream()); // <-- Exception is thrown here
}
return "";
}
</code></pre>
<p>The above method basically retrieves an xml file from one of <a href="http://www.last.fm/api/intro" rel="nofollow">LastFM's API Services</a>.</p>
<p>Now, I am facing the following <strong>exception</strong> when filling the dataset from the xml with the <code>ReadXml</code> method: </p>
<p><code>The table (artist) cannot be the child table to itself in nested relations.</code></p>
<p><hr /></p>
<p><a href="http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=iron%20maiden&api%5Fkey=b25b959554ed76058ac220b7b2e0a026" rel="nofollow">Here is an example</a> of an XML file that is being retrieved</p>
<p>Notice that there is a nested <code>Artist</code> in the XML file, and I obviously presume that that is the reason for the exception.</p>
<p><hr /></p>
<p>My question, <strong>how can I prevent this from happening? as regards the nested tables</strong></p>
| <p>As far as I know, DataSets aren't meant to hold just about any type of XML. Do you really need a dataset in this case? </p>
<p>I suggest switching to linq 2 xml or XmlDocument to manipulate the results of the web service.</p>
|
A question about run program <p>How can I run my application (written in C#) and use a SQL Server database without having to install SQL Server first?</p>
| <p>If it needs to connect to a Microsoft SQL Server database in order to work, then you need to run it on a network where you have a Microsoft SQL Server installed somewhere.</p>
<p>You can use the SQL Server Express, found <a href="http://www.microsoft.com/Sqlserver/2005/en/us/express.aspx" rel="nofollow">here</a>, if you haven't gotten the full server available.</p>
|
Finding your application's URL with only a ServletContext <p>I'm writing a Java web app using Spring MVC. I have a background process that goes through the database and finds notifications that must be e-mailed to my users. These e-mail messages need to include hyperlinks to the application. This seems like a fairly common pattern for a web app, but I'm having trouble.</p>
<p>How do I derive my application's fully qualified URL, with server name and context path? I don't have access to any of the methods in HttpServletRequest because I'm running this as a background process, not in response to a web request. The best I can do is get access to ServletContext.</p>
<p>Currently I'm putting the base URL into a configuration file and reading it at startup, but this application is going to be licensed and deployed to customers' application servers, and if possible I'd like them not to have to configure this manually.</p>
| <p>It is not recommended to dynamically prepare the URL at run time, especially based on ServletRequest. This is primarily because you have no idea of the URL that users would be using to access the application - the application server could be behind a web server, a firewall or a load balancer. To keep it short, one cannot predict network topologies.</p>
<p>Your current technique of fetching the URL from the property file is good enough to resolve the said issue. Maybe you should look at providing an administrative console to manage the URL appearing in mails, especially if there is an admin console in place, or if there are related options that should go into one.</p>
<p>Edit: My last point echoes what Tony has spoken of.</p>
|
Typesetting New Functions in LaTeX <p>So, I just have a little question:</p>
<p>What is the "best way" to typeset new functions in LaTeX which aren't already included in the various packages? Right now I'm just using <code>\mbox</code> as my go-to method, but I just was wondering if there was a more "acceptable way of doing it (as with mbox, I have to make sure to include spaces around the text of the functions in order for it to not look too strange)</p>
<p>Here is an example:</p>
<pre><code>$y(t)=2e^{1/2}\sqrt{\pi}\mbox{Erfi }(t)$
</code></pre>
<p>which comes out looking like:</p>
<p><img src="http://adamnbowen.com/images/error%5Ffunction.jpg" alt="$y(t)=2e^{1/2}\sqrt{\pi}\mbox{Erfi }(t)$" /></p>
<p>Don't get me wrong... I think it looks fine, but I was just looking for some opinions (as far as best practices go).</p>
| <p><code>\DeclareMathOperator</code> (or, if you're using some weird distribution of LaTeX that doesn't have the AMS packages, <code>\mathop{\mathrm{Erfi}}</code>)</p>
<p>See the always-useful UK TeX FAQ, specifically <a href="http://www.tex.ac.uk/cgi-bin/texfaq2html?label=newfunction">Defining a new log-like function in LaTeX</a>.</p>
|
Software/languages for online structured data collection from (human) clients <p>I need to develop a web interface to collect and validate a range of data from many of my organization's clients.</p>
<p>This isn't a single form, but a collection of forms with interdependencies (i.e., field X on form Y is needed if field A was equal to C on form B), and variable length lists (please provide the details for all Xs in your possession).</p>
<p>I had a look at the marketing on Microsoft InfoPath and Adobe LiveCycle, but I get the impression that they're principally electronic forms solutions rather than data collection tools. (e.g., If a user has entered their address once, they should never have to see it on a form again).</p>
<p>Any suggestions of good tools, applications or domain-specific languages?</p>
| <p>Sounds like you're looking for survey software. If you want to follow the principle of "buy, don't build," take a look at <a href="http://www.surveymonkey.com" rel="nofollow">http://www.surveymonkey.com</a>. If you want this hosted in-house, then <a href="http://www.quask.com/" rel="nofollow">http://www.quask.com/</a> has a nice product called FormArtist.</p>
<p>Otherwise, you can use any web application technology (ASP.NET, PHP, etc.) to build your own survey application.</p>
|
Linux: Mapping Windows key to M-x for the purpose of emacs usage <p>I am an emacs user (on linux laptop) looking to make better use of my keyboard settings. The windows key is unused on my keyboard... is there any way to map it to m-x? This might make many emacs commands faster.</p>
<p>Thanks,</p>
<p>SetJmp</p>
| <p>Use <code>xmodmap</code> to make it the <code>Menu</code> key, as in</p>
<pre><code>keycode 115 = Menu
</code></pre>
<p>You will have to use <code>xev</code> to find out if the Windows key is key 115 on your keyboard.</p>
|
SDL/C++ OpenGL Program, how do I stop SDL from catching SIGINT <p>I am using <a href="http://www.libsdl.org/">SDL</a> for an OpenGL application, running on Linux. My problem is that SDL is catching SIGINT and ignoring it. This is a pain because I am developing through a screen session, and I can't kill the running program with CTRL-C (the program the computer is running on is connected to a projector and has no input devices).</p>
<p>Is there a flag or something I can pass to SDL so that it does not capture SIGINT? I really just want the program to stop when it receives the signal (ie when I press ctrl-c).</p>
| <p>Ctrl-C at the console generates an SDL_QUIT event. You can watch for this event using SDL_PollEvent or SDL_WaitEvent, and exit (cleanly) when it is detected.</p>
<p>Note that other actions can generate an SDL_QUIT event (e.g. attempting to close your main window via the window manager).</p>
|
How to Implement multi language in PHP application? <p>I'm posting this question on it's own as I found post one which lacks full explanation or the best way to do it.</p>
<p>Should I use a language file to name items like:</p>
<p>$first_name= 'name';
$last_name = 'last_name';</p>
<p>and then include this file depending on selection?</p>
<p>I have an app which I need to have in two languages.</p>
<p>Will like something in this lines:</p>
<p><a href="http://www.myapp.com/?lang=en" rel="nofollow">http://www.myapp.com/?lang=en</a>
<a href="http://www.myapp.com/?lang=es" rel="nofollow">http://www.myapp.com/?lang=es</a></p>
<p>Should I use a constants file for this purpose?</p>
<p>constants.php</p>
<p>define('OPERATION_NOT_ALLOWED_EN', 'This operation is not allowed!');</p>
<p>define('OPERATION_NOT_ALLOWED_ES', 'This operation is not allowed!');</p>
<p>What is the recommended way of accomplishing this?</p>
| <p>You can follow in the footsteps of phpBB - they use a <code>$lang[]</code> array with code that looks like:</p>
<pre><code>$lang['Next'] = 'Next';
$lang['Previous'] = 'Previous';
$lang['Goto_page'] = 'Goto page';
$lang['Joined'] = 'Joined';
$lang['IP_Address'] = 'IP Address';
$lang['Select_forum'] = 'Select a forum';
$lang['View_latest_post'] = 'View latest post';
$lang['View_newest_post'] = 'View newest post';
$lang['Page_of'] = 'Page <b>%d</b> of <b>%d</b>'; // Replaces with: Page 1 of 2 for example
$lang['ICQ'] = 'ICQ Number';
$lang['AIM'] = 'AIM Address';
$lang['MSNM'] = 'MSN Messenger';
$lang['YIM'] = 'Yahoo Messenger';
</code></pre>
<p>It is of course included from a file specified in the user's settings, but you'd be fine with your suggestion of <code>?lang=en</code> in the query string accessing something similar to a <code>constants.php</code> file.</p>
<p>You might want to name the file <code>lang_en.php</code> or something similar for clarity.</p>
|
Can a makefile update the calling environment? <p>Is it possible to update the environment from a makefile? I want to be able to create a target to set the client environment variables for them. Something like this:</p>
<pre><code>AXIS2_HOME ?= /usr/local/axis2-1.4.1
JAVA_HOME ?= /usr/java/latest
CLASSPATH := foo foo
setenv:
export AXIS2_HOME
export JAVA_HOME
export CLASSPATH
</code></pre>
<p>So that the client can simply do:</p>
<pre><code>make setenv all
java MainClass
</code></pre>
<p>and have it work without them needing to set the classpath for the java execution themselves.</p>
<p>Or am I looking to do this the wrong way and there is a better way?</p>
| <p>No, you can't update the environment in the calling process this way. In general, a subprocess cannot modify the environment of the parent process. One notable exception is batch files on Windows, when run from a cmd shell. Based on the example you show, I guess you are not running on Windows though.</p>
<p>Usually, what you're trying to accomplish is done with a shell script that sets up the environment and then invokes your intended process. For example, you might write a go.sh script like this:</p>
<pre><code>!#/bin/sh
AXIS2_HOME=/usr/local/axix2-1.4.1
JAVA_HOME=/usr/java/latest
CLASSPATH=foo foo
export AXIS2_HOME
export JAVA_HOME
export CLASSPATH
java MainClass
</code></pre>
<p>Make go.sh executable and now you can run your app as <code>./go.sh</code>. You can make your script more elaborate too, if you like -- for example, you may want to make "MainClass" a parameter to the script rather than hard coding it.</p>
|
Options for asp.net MVC Validation Framework <p>I'm thinking of two options right now for model-base validation for an ASP.net project I'm starting:</p>
<p><a href="http://xval.codeplex.com/" rel="nofollow">xVal</a> (Steve Sanderson's project) and the Enterprise module that Stephen Walther uses on <a href="http://www.aspworkshops.com/blog/archive/2008/09/10/asp-net-mvc-tip-43-use-data-annotation-validators.aspx" rel="nofollow">this page</a></p>
<p>I don't really know enough to talk about the preferences as I haven't used either of them yet. Any ideas?</p>
<p><b>Update</b> Using LinqToSql for ORM right now, but am open to changes.</p>
| <p>One difference I see in reviewing the two is that Stephen Walther's blog post describes a library which does only validation in the Web server, where as xVal works with jQuery validators to do in-browser validation, as well. This feature, incidentally, is almost completely automatic.</p>
|
How do we perform multi threading application in C#? <p><strong>Duplicate of</strong></p>
<ul>
<li><a href="http://stackoverflow.com/questions/177488/c-threading">c# threading</a></li>
<li><a href="http://stackoverflow.com/questions/533042/beginners-threading-in-c">Beginners threading in C#</a></li>
<li><a href="http://stackoverflow.com/questions/601558/multithreading-reference">Multithreading reference?</a></li>
</ul>
<p><hr /></p>
<p>Can any body provide some good examples, codes for multi threading in c#..
I tried on google but I need examples with good explanation about what is happening at what point?</p>
| <p>There is a good resource by Joseph Albahari..</p>
<p><a href="http://www.albahari.com/threading/" rel="nofollow">Threading in C#</a></p>
|
Do you follow any guidelines (java) in packaging? <p>Do you follow any design guidelines in java packaging?</p>
<p>is proper packaging is part of the design skill? are there any document about it?</p>
<p>Edit : How packages has to depend on each other?, is cyclic packages unavoidable?, not about jar or war files.</p>
| <p>My approach that I try to follow normally looks like this:</p>
<ol>
<li>Have packages of reasonable size. Less then 3 classes is strange. Less then 10 is good. More then 30 is not acceptable. I'm normally not very strict about this.</li>
<li>Don't have dependency cycles between packages. This one is tough since many developers have a hard time figuring out any way to keep the dependencies cycle free. BUT doing so teases out a lot of hidden structure in the code. It becomes easier to think about the structure of the code and easier to evolve it.</li>
<li>Define layer and modules and how they are represented in the code. Often I end up with something like <code><domain>.<application>.<module>.<layer>.<arbitrary substructure as needed></code> as the template for package names</li>
<li>No cycles between layers; no cycles between modules.</li>
</ol>
<p>In order to avoid cycles one has to have checks. Many tools do that (JDepend, Sonar ...). Unfortunatly they don't help much with finding ways to fix cycles. That's why I started to work on <a href="https://github.com/schauder/degraph" rel="nofollow">Degraph</a> which should help with that by visualizing dependencies between classes, packages, modules and layer. </p>
|
How to make use of full bandwidth? <p>Using WinPcap I crafted a series of custom UDP packets and injected them into the Ethernet layer.</p>
<p>I sent 1000 packets, 1440 bytes each. It takes 2.1 sec for 100 Mbps bandwidth.</p>
<p>How do I make use of full bandwidth?</p>
| <p>Your throughput seems to be exactly the max you'd get for a <em>10 mbit</em> connection. Sure there's no 10mbit involved anywhere ?</p>
|
creating something like pageflakes <p>Does anyone know about a tutorial that lets you to create something like pageflakes.com for your website? In jquery perhaps?</p>
| <p>The creator of PageFlakes, <a href="http://msmvps.com/blogs/omar/" rel="nofollow">Omar al Zabir</a>, has created an open-source web portal called <a href="http://www.codeplex.com/dropthings/" rel="nofollow">DropThings</a>. Can't get any more similiar to PageFlakes than that!</p>
|
Different ways of loading a file as an InputStream <p>What's the difference between:</p>
<pre><code>InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName)
</code></pre>
<p>and</p>
<pre><code>InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName)
</code></pre>
<p>and</p>
<pre><code>InputStream is = this.getClass().getResourceAsStream(fileName)
</code></pre>
<p>When are each one more appropriate to use than the others?</p>
<p>The file that I want to read is in the classpath as my class that reads the file. My class and the file are in the same jar and packaged up in an EAR file, and deployed in WebSphere 6.1.</p>
| <p>There are subtle differences as to how the <code>fileName</code> you are passing is interpreted. Basically, you have 2 different methods: <code>ClassLoader.getResourceAsStream()</code> and <code>Class.getResourceAsStream()</code>. These two methods will locate the resource differently.</p>
<p>In <code>Class.getResourceAsStream(path)</code>, the path is interpreted as a path local to the package of the class you are calling it from. For example calling, <code>String.getResourceAsStream("myfile.txt")</code> will look for a file in your classpath at the following location: <code>"java/lang/myfile.txt"</code>. If your path starts with a <code>/</code>, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling <code>String.getResourceAsStream("/myfile.txt")</code> will look at the following location in your class path <code>./myfile.txt</code>.</p>
<p><code>ClassLoader.getResourceAsStream(path)</code> will consider all paths to be absolute paths. So calling <code>String.getClassLoader().getResourceAsStream("myfile.txt")</code> and <code>String.getClassLoader().getResourceAsStream("/myfile.txt")</code> will both look for a file in your classpath at the following location: <code>./myfile.txt</code>.</p>
<p>Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.</p>
<p>In your case, you are loading the class from an Application Server, so your should use <code>Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName)</code> instead of <code>this.getClass().getClassLoader().getResourceAsStream(fileName)</code>. <code>this.getClass().getResourceAsStream()</code> will also work.</p>
<p>Read <a href="http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html">this article</a> for more detailed information about that particular problem.</p>
<hr>
<h2>Warning for users of Tomcat 7 and below</h2>
<p>One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.</p>
<p>So I've looked at the source code of Tomcat's <code>WebAppClassLoader</code> for several versions of Tomcat. The implementation of <code>findResource(String name)</code> (which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.</p>
<p>In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, <code>classLoader.getResourceAsStream("/resource.txt")</code> may not produce the same result as <code>classLoader.getResourceAsStream("resource.txt")</code> event though it should (since that what the Javadoc specifies). <a href="http://svn.apache.org/repos/asf/tomcat/tc7.0.x/tags/TOMCAT_7_0_40/java/org/apache/catalina/loader/WebappClassLoader.java">[source code]</a></p>
<p>In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. <a href="http://svn.apache.org/repos/asf/tomcat/tc8.0.x/tags/TOMCAT_8_0_3/java/org/apache/catalina/loader/WebappClassLoader.java">[source code]</a></p>
<p>As a result, you have to be extra careful when using <code>ClassLoader.getResourceAsStream()</code> or <code>Class.getResourceAsStream()</code> on Tomcat versions earlier than 8. And you must also keep in mind that <code>class.getResourceAsStream("/resource.txt")</code> actually calls <code>classLoader.getResourceAsStream("resource.txt")</code> (the leading <code>/</code> is stripped).</p>
|
How do i get the Sum in this Linq query? <p>i have a table that has zero to many children. just like how this site has a <code>QUESTION</code> which can have zero to many <code>VOTES</code> (either Up == 1 or Down == 0).</p>
<p>I need to get <em>all questions that have the most up votes</em>. Eg. all the questions, ordered by Sum(Vote) descending.</p>
<p>I'm not sure how to do it in linq.</p>
<p>So i would have an EntitySet called Questions and another EntitySet called Votes.</p>
<p>I was trying to do group by and let and order by and nothing compiles :(</p>
<p>Could anyone have any suggestions, please?</p>
| <pre><code>myDataContext.Questions
.OrderByDescending(q => q.Votes.Select(v => v.VoteValue).Sum())
</code></pre>
<p>In query comprehension (unchecked):</p>
<pre><code>from q in myDataContext.Questions
order q by
(
from v in q.Votes
select v.VoteValue
).Sum() descending
select q;
</code></pre>
|
Read eclipse installation path using eclipse API <p>I opened eclipse 3.3.2. Now i need to get the current eclispe installation path. Is</p>
<p>there any eclipse API to get the eclipse installation path? Please help in this regard.</p>
<p>Thanks in Advance..</p>
<p>Snehal</p>
| <p>Since eclipse3.4 and the <a href="http://dev.eclipse.org/mhonarc/lists/eclipse-pmc/msg00341.html">p2 mechanism</a>, you coud use <a href="http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/osgi/service/datalocation/Location.html"><code>org.eclipse.osgi.service.datalocation.Location</code></a>, which represents a URL.</p>
<p>That interface includes **<code>ECLIPSE_HOME_FILTER**</code>, a constant which defines the filter string for acquiring the service which specifies the eclipse home location (i.e. "<code>eclipse.home.location</code>".)</p>
<p>But in eclipse3.3, just query the property value "<code>eclipse.home.location</code>", as in:</p>
<pre><code>System.getProperty("eclipse.home.location");
</code></pre>
|
Listview Selection <p>HI,</p>
<p>I need to select a single item(cell) in a listview </p>
| <p>You cannot select 'subitems' in a ListView. If you want to be able to select 'cells', you'll have to use a gridview.</p>
|
Play 1 sound clip after another without any interruption in iPhone <p>I am developing a simple iPhone sound app. How can I play 1 sound clip after another without any interruption ?</p>
| <p>Are you using SystemSounds or AudioQueues? If SystemSounds (for short sounds), you'll need to have a thread that plays them at a specific time interval, as there is no way to know when the sound ends.</p>
<p>For AudioQueues, you get callbacks when each section of a sound is finished, and so it's a fairly easy thing to start another sound (say, background music) when the first ends.</p>
<p>You don't really state what you're trying to accomplish, so giving a specific answer is difficult. Are you looking to splice together sound files? Play background music? Make 3 lazer-beam sounds come when the user shoots 3 times? Etc.</p>
|
Eclipse + Git - what does "staged" mean? <p>After working for some time with SVN I decided to try git with my new django project and installed the plugin for it into eclipse. I made a new pydev project and added django initial project files to the src directory. Then I "shared" the project to Git, added and commited all files. Now I have strange problems - all files except "manage.py" are "up to date" and manage.py has a strange icon that means it is "staged". What does this mean? I tried to google for it, but without success. :(</p>
<p>Thanks beforehand.</p>
| <p>It means your file has been added to the <a href="http://gitready.com/beginner/2009/01/18/the-staging-area.html">index</a>.</p>
<p><img src="http://i.stack.imgur.com/W7tgI.png" alt="index"></p>
<p>As described in <a href="http://tomayko.com/writings/the-thing-about-git">The Thing About Git</a></p>
<p>The Index is also sometimes referred to as The Staging Area.</p>
<blockquote>
<p>I tend to think of it as the next patch:<br>
You build it up interactively with changes from your working copy and can later review and revise it.<br>
When youâre happy with what you have lined up in the staging area, which basically amounts to a diff, you commit it.
<strong>And because your commits are no longer bound directly to whatâs in your working copy, youâre free to stage individual pieces on a file-by-file, hunk-by-hunk basis</strong>.</p>
</blockquote>
<hr>
<p>If you look to the latest <a href="http://repo.or.cz/w/egit.git?a=log">change logs of egit</a> (the eclipse Git plugin), you will see they are still fiddling with how "staged" files are managed, se the more recent your egit plugin is, the better ;)</p>
|
Web crawlers and Google App Engine Hosted applications <p>Is it impossible to run a web crawler on GAE along side with my app considering the I am running the free startup version?</p>
| <p>While Google hadn't exposed scheduling, queue and background tasks API, you can do any processing only as an answer to external HTTP request. You'd need some heartbeat service that will process one item from crawler's queue at a time (not to hit GAE limits).</p>
<p>To do crawling from GAE, you have to split your application into queue (that stores queue data in Datastore), queue processor that will react to external HTTP heartbeat and your actual crawling logic.</p>
<p>You'd manually have to watch your quota usage and start heartbeat when you have spare quota, and stop if it is used up.</p>
<p>When Google introduces the APIs I've told in the beginning you'd have to rewrite parts that are implemented more effectively via Google API.</p>
<p>UPDATE: Google introduced Task Queue API some time ago. See <a href="http://code.google.com/appengine/docs/python/taskqueue/" rel="nofollow">task queue docs for python</a> and <a href="http://code.google.com/appengine/docs/java/taskqueue/" rel="nofollow">java</a>.</p>
|
How change List<T> data to IQueryable<T> data <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/73542/ilistt-to-iqueryablet">IList<T> to IQueryable<T></a> </p>
</blockquote>
<p>I have a List data, but I want a IQueryable data , is it possible from List data to IQueryable data?
Show me code</p>
| <pre><code>var list = new List<string>();
var queryable = list.AsQueryable();
</code></pre>
<p>Add a reference to: <code>System.Linq</code></p>
|
Is it possible to have windows integrated and forms auth on the same web app (same url)? <p>Basically I want to build a web app that will try windows authentication and if authentication fails then will provide the user with a login form ? </p>
<p>I do not want to have different web apps for different authentication modes.</p>
<p>Is this possible ? Did I missed some points about this ?</p>
| <p>You could go into your IIS Error Pages settings and change the various target pages for the 401 error to point to a Windows Forms login page. That way, then the user bails out/fails for the three requested authentication attempts it redirects to another page.</p>
|
Vim search and replace selected text <p>Let's say we have a text, and I enter visual mode and select some text. How do I quickly do a search for the highlighted text and replace it with something else?</p>
| <p>Try execute the following or put in into your .vimrc</p>
<pre><code>vnoremap <C-r> "hy:%s/<C-r>h//gc<left><left><left>
</code></pre>
<p>By pressing ctrl + r in the visual mode you will be prompted to enter text to replace with. Press enter and then confirm each change you agree with 'y' or decline with 'n'.</p>
<p>This command will override your register 'h' so you can choose other one ( by changing 'h' in the command above to other lower case letter ) that you don't use. </p>
|
What do I need to know before I sell a software license? <p>I've developed a web-based application that a company is interested in licensing. I suspect they intend to appropriate the features they want, and add to their existing codebase, so a license is likely to be a one-time affair. Since it's interpreted at run-time, I'd have to turn over the source, and it's not immediately apparent that I can protect it in any way.</p>
<p>To add a layer of complexity, I've had a number of users express interest in using it as a service, so I've been working towards a subscription-based version. It's a niche market, so growth potential is limited, but I don't want to sell it short.</p>
<p>I typically sell my services hourly, so I don't know the first thing about licensing code. </p>
<p>The questions I'm struggling with are:</p>
<ol>
<li>What should I charge?</li>
<li>What does a commercial software license look like?</li>
<li>How do I protect my work?</li>
</ol>
<p>I'm sure there are a few dozen more I should ask. What should I be thinking about?</p>
<p>Thanks in advance.</p>
<p>--Thanks for the replies, all--</p>
| <p>Answer this question: What are you afraid of? That they "steal" from you? As we Germans say: If you can trust someone, you don't need a contract. If you can't trust them, a contract won't save you.</p>
<p>So sit back and think of what additional benefit this could give you. If the company likes your software, might they be interested in paying you to adjust it to their needs? Could you get other paid work from them? Or hire you permanently? Is there a company around which has solved this problem already and which is willing to take you under the wing?</p>
<p>But as shooner said, if you're trying to run this as a one-man show, see a lawyer. Copyright law is a mess and never forget one thing: The world is ruled by lawyers and courts. If you don't make the correct sacrifice to these powers, they will ruin your life.</p>
|
Can Java annotations be unit tested? <p>I've recently started creating my own annotations and to sport TDD/BDD, I'd want to unit test my annotations to create a clear specification for them. However since annotations are basically merely fancy interfaces which to my knowledge can't be really instantiated directly, is there any way short of reflection to unit test an annotation?</p>
| <p>Annotations have some impact (otherwise, it would be pointless to use them). So don't test the annotation presence but the effect it should have.</p>
|
Scaling HTML layout to the screen size <p>Could you tell me how to fix a HTML layout automatically with the screen resolution? Example, I am coding HTML in screen resolution of 1024 by 768 pixels. If I switch to 800 by 600 pixels, I want my HTML windows changed automatically to fix the screen. </p>
<p>How could I do that?</p>
| <p>By <em>HTML window</em>, I assume that you are talking about HTML contents and not browser window.</p>
<p>If this is the case, the keywords for what you want to do are <code>liquid/fluid/elastic design</code>.</p>
<p>You may want to read <a href="http://www.alistapart.com/articles/elastic/" rel="nofollow">Elastic Design by Patrick Griffiths</a> on <a href="http://www.alistapart.com/" rel="nofollow">A List Apart</a> site, or <a href="http://www.google.com/search?q=liquid%2Bdesign" rel="nofollow">search google for liquid design</a>.</p>
|
jetty diplays the code of jsp files <p>I am trying to deploy my web application with jetty, but jetty diplays the code of jsp files at the adress: <a href="http://localhost:8080/index.jsp" rel="nofollow">http://localhost:8080/index.jsp</a>
has this a relation to my browser?or is it a problem of jetty?
Could someone help me!
thanks </p>
| <p>Make sure you include the jsp and jsp-api jars. Otherwise jetty is unable to render jsp pages.</p>
|
How do I set a global DateTime format in an ASP.NET project? <p>I have a server with German windows on it, but the DateTime values are stored on a mysql server in English format. How do i force every DateTime.ToString() method (like DateTime.Now.ToString()) to output an 'English' DateTime by default?</p>
| <p>I'd set the culture in the web.config so any culture specific conversion or parsing i.e. dates, will use the same culture regardless of the underlying operating system region.</p>
<p>i.e.</p>
<pre><code><globalization culture="en-GB" uiCulture="en-GB"/>
</code></pre>
|
How to record something other than Linear PCM on iPhone <p>I'm having a hard time trying to record something other than linear PCM on the iPhone :-(
The samples I've found (SDK's SpeakHere, Zdziarski's and Sadun's books and the one at trailsinthesand.com) all use linear PCM but I'd like a commonly used compressed format instead (no ima4 or whatever the name is...).</p>
<p>I just cannot figure out how to tweak the sample code to be used with, for example AAC, MP3 or AMR instead. Any suggestions and hints for how to do that are much appreciated! </p>
<p>(Btw, I do not think an MP3-encoder nor AMR-encoder are available due to licensing issues, but AAC does exist, or???)</p>
<p><strong>Edit/Update:</strong> I stumbled upon the following text in Apple's "iPhone Application Programming Guide", 2009-01-06, page 137, section: Recording Audio:<br />
"You can record audio in any of the formats listed in âPreferred Audio Formats in iPhone OSâ (page 140)", and as preferred audio formats on page 140 are: "For compressed audio when playing one sound at a time, and when you donât need to play audio simultaneously with the iPod application, use the AAC format packaged in a CAF or m4a file."<br />
Thus, I interpret that as a clear indication that it is indeed, not only possible, but even preferable, to record audio in AAC format wrapped up in a m4a file, which is just what I want. But still, I am not able to achieve that?!</p>
<p>Thanks,
/John</p>
| <p>Keep looking at those docs. In "Core Audio Essentials", the section "Core Audio Plug-ins: Audio Units and Codecs" notes that:</p>
<blockquote>
<p>iPhone OS contains the recording
codecs listed in Table 2-5. As you can
see, neither MP3 nor AAC recording is
available. This is due to the high CPU
overhead, and consequent battery
drain, of these formats.</p>
</blockquote>
<p>Table 2-5 lists several formats, but as the text notes does not include the ones you're looking for. If you want those formats you'll have to bring your own encoder.</p>
|
WCF Service reference intermittently breaking <p>I have a service reference on my local dev environment to a WCF service hosted elswhere on our LAN, and it will just stop working at times with an error along the lines of "The document at the url was not recognized as a known document type."</p>
<p>A system reboot doesn't fix it, rather it starts working again on its own several minutes later.</p>
<p>Anyone else ever experienced this?</p>
| <p>It's a network issue. When I get the problem, I just repair my LAN connection, clear my DNS cache and things work again.</p>
|
What is Oracle Native web services? <p>Native web services is a new feature of the XML DB technology. In google i found that it`s very close to SOA.</p>
<p>Can anyone simply explain:
1) what is the main usage of Native web services
2) what is the main difference of XML DB 11g and previous XML DB releases.</p>
<p>Thanks.</p>
| <p><a href="http://www.inside-oracle-apex.com/oracle-11g-native-web-services/" rel="nofollow">found via google:</a></p>
<blockquote>
<p>It allows you to publish your PL/SQL
packages/procedures/functions as a web
service with zero coding and zero
deployment effort! </p>
</blockquote>
|
How can I databind a gridview to an arraylist in .NET? <p>How can I databind a gridview to an arraylist in .NET?</p>
<p>I am using .NET 3.5 and Visual Studio 2008.</p>
| <p>In place of arraylist use generic class BindingList. It will allow you to bind this list in two direcions to DataGridView. So your change in BindingList will be reflected in DGV and vice versa.</p>
<p>Here you have more information about BindingList class:
<a href="http://msdn.microsoft.com/en-us/library/ms132679.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms132679.aspx</a></p>
|
Dictionary enumeration in C# <p>How do I enumerate a dictionary?</p>
<p>Suppose I use <code>foreach()</code> for dictionay enumeration. I can't update a key/value pair inside <code>foreach()</code>. So I want some other method.</p>
| <p>To enumerate a dictionary you either enumerate the values within it:</p>
<pre><code>Dictionary<int, string> dic;
foreach(string s in dic.Values)
{
Console.WriteLine(s);
}
</code></pre>
<p>or the KeyValuePairs</p>
<pre><code>foreach(KeyValuePair<int, string> kvp in dic)
{
Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " + kvp.Value);
}
</code></pre>
<p>or the keys</p>
<pre><code>foreach(int key in dic.Keys)
{
Console.WriteLine(key.ToString());
}
</code></pre>
<p>If you wish to update the items within the dictionary you need to do so slightly differently, because you can't update the instance while enumerating. What you'll need to do is enumerate a different collection that isn't being updated, like so:</p>
<pre><code>Dictionary<int, string> newValues = new Dictionary<int, string>() { 1, "Test" };
foreach(KeyValuePair<int, string> kvp in newValues)
{
dic[kvp.Key] = kvp.Value; // will automatically add the item if it's not there
}
</code></pre>
<p>To remove items, do so in a similar way, enumerating the collection of items we want to remove rather than the dictionary itself.</p>
<pre><code>List<int> keys = new List<int>() { 1, 3 };
foreach(int key in keys)
{
dic.Remove(key);
}
</code></pre>
|
how can I save results of a Fortran77 code into a text file? <p>I want to save results in a text file. How can I do that? Write command?</p>
| <p>Yes, the write command. The details should be in some book, or on the net, but here's a simple example:</p>
<pre><code>OPEN(UNIT=20, FILE='FILENAME.TXT', STATUS='NEW')
C STATUS='NEW' WILL CREATE A NEW FILE IF ONE DOESN'T EXITST, 'REPLACE' WILL
C OVERWRITE OLD ONE
WRITE(UNIT=20, *)(A(I),I=1,10)
CLOSE(UNIT=20)
</code></pre>
<p>In fortran77 it was always good practice to avoid low (below 10) unit numbers, because some of them were reserved - depending on the platform, compiler ... generally, start with those above 10.</p>
|
Private Member Access Java <p>Is the private member access at the class level or at the object level. If it is at the object level, then the following code should not compile</p>
<pre><code> class PrivateMember {
private int i;
public PrivateMember() {
i = 2;
}
public void printI() {
System.out.println("i is: "+i);
}
public void messWithI(PrivateMember t) {
t.i *= 2;
}
public static void main (String args[]) {
PrivateMember sub = new PrivateMember();
PrivateMember obj = new PrivateMember();
obj.printI();
sub.messWithI(obj);
obj.printI();
}
}
</code></pre>
<p>Please clarify if accessing the member i of obj within the messWithI() method of sub is valid</p>
| <p>As DevSolar has said, it's at the (top level) class level.</p>
<p>From <a href="http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6" rel="nofollow">section 6.6 of the Java Language Specification</a>:</p>
<blockquote>
<p>Otherwise, if the member or
constructor is declared private, then
access is permitted if and only if it
occurs within the body of the top
level class (§7.6) that encloses the
declaration of the member or
constructor.</p>
</blockquote>
<p>Note that there's no indication that it's restricted to members for a particular object.</p>
<p>As of Java 7, <a href="http://www.oracle.com/technetwork/java/javase/compatibility-417013.html#source" rel="nofollow">the compiler no longer allows access to private members of type variables</a>. So if the method had a signature like <code>public <T extends PrivateMember> void messWithI(T t)</code> then it would be a compiler error to access <code>t.i</code>. That wouldn't change your particular scenario, however.</p>
|
XmlDocument, XmlResolver and www.w3.org <p>One of my users had a single error while opening a file (I'm using standard xml 1.0):</p>
<pre><code>The remote name could not be resolved: 'www.w3.org'
</code></pre>
<p>I found a post here in <a href="http://stackoverflow.com/questions/217841/net-autogenerated-web-service-client-how-do-i-avoid-requesting-schemas-from-w3o">StackOverflow</a> that deals with this and it suggest setting the XmlResolver property to null. I've tried this, and all my documents still seem to load fine. However, the last thing I want is to break the file-reading mechanism of my app, so is it actually safe to disable the resolver?</p>
| <p>Another way to avoid connecting to the W3C site is to use <a href="http://msdn.microsoft.com/en-us/library/system.xml.resolvers.xmlpreloadedresolver.aspx" rel="nofollow"><code>XmlPreloadedResolver</code></a>. The <code>XmlPreloadedResolver</code> contains a number of "well-known" DTDs and (AFAIR) schemas embedded and whenever your xml contains a reference to one of these the resolver will serve it without trying to connect anywhere. </p>
|
Most advanced image compression today (not on browser)? <p>I am writing an application in Java to view images which contain a lot of text and graphics, like a screenshot of a webpage, actually its a image of a magazine article. Some parts are text, some parts are graphics.</p>
<p>My client program is written in Java, I can use any image format, what is the best image compression format I can get my hands on in Java? So I can compress and de-compress?</p>
<p>It would be nice if the image became clearly as it loaded, but thats not necessary, its not 1997 anymore (remember gif loading).</p>
| <p>You haven't supplied one key piece of information: does the compression need to be lossless or is lossy fine? And if lossy is fine withint what tolerance?</p>
<p>You can reduce an entire image to a single bit of information if you're prepared to a highly lossy compression format. :-)</p>
<p>Seriously though, the two main lossless formats are GIF and PNG (both in browser and out of) and the biggest (by far) lossy format is JPG. Other formats like BMP and TIF are nowhere near as efficient.</p>
<p>all three of these formats are well-supported in Java (either directly or with readily-available third party libraries). PNG tends to be better compression ratios than GIF.</p>
<p>See:</p>
<ul>
<li><a href="http://warp.povusers.org/grrr/PNGvsGIF/" rel="nofollow">PNG vs. GIF compression</a></li>
<li><a href="http://www.puidokas.com/gif-vs-png/" rel="nofollow">GIF vs. PNG</a>: this one gives reference to (and measures0 the <a href="http://www.apple.com/downloads/dashboard/developer/pngpong.html" rel="nofollow">PNGpong format</a>;</li>
</ul>
|
Extensibility without Open-Source <p>My company is currently in the process of creating a large multi-tier software package in C#. We have taken a SOA approach to the structure and I was wondering whether anyone has any advice as to how to make it extensible by users with programming knowledge.</p>
<p>This would involve a two-fold process: approval by the administrator of a production system to allow a specific plugin to be used, and also the actual plugin architecture itself.</p>
<p>We want to allow the users to write scripts to perform common tasks, modify the layout of the user interface (written in WPF) and add new functionality (ie. allowing charting of tabulated data). Does anyone have any suggestions of how to implement this, or know where one might obtain the knowledge to do this kind of thing?</p>
<p>I was thinking this would be the perfect corner-case for releasing the software open-source with a restrictive license on distribution, however, I'm not keen on allowing the competition access to our source code.</p>
<p>Thanks.</p>
<p>EDIT: Thought I'd just clarify to explain why I chose the answer I did. I was referring to production administrators external to my company (ie. the client), and giving them someway to automate/script things in an easier manner without requiring them to have a full knowledge of c# (they are mostly end-users with limited programming experience) - I was thinking more of a DSL. This may be an out of reach goal and the Managed Extensibility Framework seems to offer the best compromise so far.</p>
| <p>Just use interfaces. Define an IPlugin that every plugin must implement, and use a well defined messaging layer to allow the plugin to make changes in the main program. You may want to look at a program like Mediaportal or Meedios which heavily depend on user plugins.</p>
|
How can I open and close a browser window from a Java applet? <p>I would like to open a new window at Google.com, but then later close that window. My current code is as follows:</p>
<pre><code>link="http://www.google.com"
try
{
AppletContext a = getAppletContext();
URL url = new URL(link);
a.showDocument(url,"_blank");
}
catch (MalformedURLException e)
{
System.out.println( e.getMessage() );
}
</code></pre>
<p>This opens the window, but how do I close it later?</p>
| <p>I'd suggest using the JSObject interface to call into the browser for opening the windows. Then you can get the variable of the new window and use that to close it.</p>
<p>More documentation:</p>
<ul>
<li><a href="http://www.novell.com/documentation/extendas35/docs/help/books/TechWindowOpenClose.html#978293" rel="nofollow">Opening and Closing Windows from Javascript</a></li>
<li><a href="http://java.sun.com/products/plugin/1.3/docs/jsobject.html" rel="nofollow">JSObject from Java</a></li>
</ul>
|
What is the best way to create printable letters from an MVC application? <p>What's the best way to create printable letters from an MVC application? I'm looking for sort of a mail merge thing from my app that prints a form letter with various values filled in.</p>
<p>In ASP.NET, I previously did this by creating an HTML document and displaying it as <code>application/msword</code>, but I did that with code-behind, which isn't an (easy) option in MVC, and I don't know if that's the best method or not.</p>
<p>Note that this is an internal application, so it can be assumed everyone has Word on their computer. With that said, it would be nice to bypass Word, but I could go either way. The simpler the better. Any ideas/methods welcome.</p>
| <p>Since this is just HTML with the ContentType set to application/msword I can't see any reason why you would want to use code-behind.</p>
<p>A standard MVC view with a typical HTML template peppered with appropriate <code><%=...></code> where view data needs to be inserted would seem to be the sensible approach. Even where you might want to loop.</p>
<p>BTW, why isn't code-behind an easy option?</p>
|
IE (Z-index rendering problem) <p>I have an ASP.NET application that renders a 3rd party (Telerik's) menu control <em>under</em>
another control (RadDock) when the menu expands.</p>
<p>This artifact ONLY happens in IE7. Not in Safari/FF/Opera/Chrome (Have I left any out?) </p>
<p>The menu control needs to be rendered OVER the other control.</p>
<p>I have Google'd this a fair amount, but have yet to find a simple solution to fix it for IE7.</p>
<p>What is the easiest to solve this problem for IE?</p>
<p>Also do you know if this z-index problem has been resolved in the (pending?) IE8?</p>
<p>This Q is not meant to start a browser flame war. Please only respond if you have a
relevant comment.</p>
<p>Thank you kindly.</p>
| <p>I don't know if this is similar or not, but I had an issue with z-indexing where when the z-index was applied to the elements of a container, but not to the container itself, the z-index wasn't being properly applied to the child elements. This manifested itself as background borders appearing over the top of the menu items that should have been on top. I solved the issue by applying the same z-index to the container holding the menu items. I don't know how the Telerik controls set up their CSS, but you may want to check that the class being assigned to the container has an appropriate z-index as well as the menu items themselves.</p>
|
How to fix this JQuery intellisense in Visual Studio 2008 problem? <p>How can i solve this problem "Error updating JScript IntelliSense: D:\myProject\js\jquery-1.3.2.js: Object doesn't support this property or method @ 2139:1", i did all in this
<a href="http://stackoverflow.com/questions/218578/visual-studio-jscript-intellisense-error-with-jquery-1-2-6">Visual Studio jscript intellisense error with jQuery 1.2.6?</a></p>
<p>But no hope, should i edit something in my Visual studio options, or Visual studio has a problem?</p>
| <p>Make sure you've got the <a href="http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.3.2-vsdoc2.js" rel="nofollow">corresponding vsdoc file</a> sitting beside jquery-1.3.2.js (in /js/ in your case here), and that it's properly named <strong>jquery-1.3.2-vsdoc.js</strong>.</p>
<p>Also, while I don't think it's strictly necessary in your case, it generally can't hurt to have this hotfix installed: <a href="http://blogs.msdn.com/webdevtools/archive/2008/11/07/hotfix-to-enable-vsdoc-js-intellisense-doc-files-is-now-available.aspx" rel="nofollow">http://blogs.msdn.com/webdevtools/archive/2008/11/07/hotfix-to-enable-vsdoc-js-intellisense-doc-files-is-now-available.aspx</a></p>
<p>Finally, this is a helpful FAQ on Visual Studio JavaScript Intellisense, by Jeff King (the Program Manager in charge of tooling): <a href="http://blogs.msdn.com/webdevtools/archive/2008/11/18/jscript-intellisense-faq.aspx" rel="nofollow">http://blogs.msdn.com/webdevtools/archive/2008/11/18/jscript-intellisense-faq.aspx</a></p>
|
Elevator pitch for Git a/o DVCS <p>Imagine you have a friend on the phone (not VoIP) who asks: "What's so special about Git? I'm fine using Subversion." What would be your "elevator pitch" in order to describe the advantage of using a DVCS like Git?</p>
| <p>There was already <a href="http://stackoverflow.com/questions/871/why-is-git-better-than-subversion">a question similar to this</a>. Also, Eric Sink had a <a href="http://www.ericsink.com/entries/dvcs_dag_1.html" rel="nofollow">number</a> of <a href="http://www.ericsink.com/entries/dvcs_dag_2.html" rel="nofollow">articles</a> about <a href="http://www.ericsink.com/entries/dbts_fossil.html" rel="nofollow">DVCS</a>. Both the answers to the other question and the articles may help to build an informed decision. Simply saying that one is better over the other is probably not going to help (Sadly, that seems to be all that Linus does in that respect, which doesn't really help to convince peopleâat least not me :)).</p>
|
how to read values in the column of a table in sqlserver? <p>There is a table called Friends. It has columns named Names, Address, Phone no, Dob. We want to use Names which are in Friends table one by one. so I want to store all names in an array which is to be used later.</p>
| <p>Here's the rundown:</p>
<p>In your .config file:</p>
<pre><code><configuration>
<connectionStrings>
<add name="Test" connectionString="Data Source=[server name here];Initial Catalog=[db name here];User Name=blah;Password=blah"/>
</connectionStrings>
</configuration>
</code></pre>
<p>In your code:</p>
<pre><code>using System.Configuration;
using System.Data.SqlClient;
...
// In ASP.NET use WebConfigurationManager instead...
string connectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand("SELECT Name FROM Friends ORDER BY Name", connection);
List<string> nameList = new List<string>();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
nameList.Add(reader["Name"] as string);
}
}
string[] names = nameList.ToArray();
</code></pre>
|
Which browsers have problems caching XMLHTTPRequest responses? <p>Do any of the currently popular browsers have particular problems caching* XMLHttpRequest responses that I need to be aware of?</p>
<p>I'd like to be able to include XMLHttpRequest queries on every page as a method of dynamically loading content (ie JSON) or behaviour (like eval()ed Javascript) relevant to the type of page, but wanted to make sure that the resources it receives from the server could be cached, if the server sent the right headers.</p>
<p>I was concerned to read <a href="http://www.subbu.org/blog/2005/10/xmlhttprequest-and-caching">this article which mentions</a> that browsers such as Firefox 1.1 do not cache any content obtained via XMLHTTPRequest, and that it always requests new data is sent completely (with Cache-Control and no If-Modified-Since) regardless of headers sent by the server.</p>
<p>Obviously that article is very old - I don't even remember a Firefox 1.1; so what are the considerations I need to make for current popular browsers and is there any trick for when I specifically <em>want</em> responses to be cached?</p>
<p>*<em>To clarify my question, by caching, I mean client-side caching, where the server issues freshness information (in the form of a Cache-Control: max-age directive or an Expires: header) and the browser stores a copy of the response in its cache along with an expiry date, so that future requests for the same resource issued from subsequent pages can be satisfied from the browser cache without the need for any contact with the server at all. All major browsers do this correctly for most content, but I've heard that Firefox cannot do this for XMLHttpRequest content. What I'm asking is if anyone knows of cases where any of the modern browsers do not cache responses according to the spec when using XMLHttpRequest.</em></p>
| <p>Mark Nottingham has <a href="http://www.mnot.net/javascript/xmlhttprequest/cache.html">an excellent set of functional tests</a> that demonstrate browser XMLHttpRequest caching behaviour. Load up the page in the browsers you want to support and work out what techniques you can and cannot rely on to have your response cached.</p>
|
Can't import java.lang.instrument.Instrumentation <p>If I try to use</p>
<pre><code>import java.lang.instrument.Instrumentation;
</code></pre>
<p>it says this statement can not be resolved. What could be wrong? I am using jdk1.6.</p>
| <p>Are you sure that's <em>exactly</em> your import line? It certainly works for me. Try just compiling this trivial test class:</p>
<pre><code>import java.lang.instrument.Instrumentation;
public class Test {}
</code></pre>
|
How can I programmatically get the MAC address of an iphone <p>Does anyone know how to programmatically get an iPhone's MAC address and IP address?</p>
| <hr>
<p><strong>NOTE</strong> As of iOS7, you can no longer retrieve device MAC addresses. A fixed value will be returned rather than the actual MAC</p>
<hr>
<p>Somthing I stumbled across a while ago. Originally from <a href="http://www.iphonedevsdk.com/forum/iphone-sdk-development/5293-get-current-ip-address.html" rel="nofollow">here</a> I modified it a bit and cleaned things up.</p>
<p><a href="http://www.chrisandtennille.com/code/IPAddress.h" rel="nofollow">IPAddress.h</a><br>
<a href="http://www.chrisandtennille.com/code/IPAddress.c" rel="nofollow">IPAddress.c</a></p>
<p>And to use it</p>
<pre><code>InitAddresses();
GetIPAddresses();
GetHWAddresses();
int i;
NSString *deviceIP = nil;
for (i=0; i<MAXADDRS; ++i)
{
static unsigned long localHost = 0x7F000001; // 127.0.0.1
unsigned long theAddr;
theAddr = ip_addrs[i];
if (theAddr == 0) break;
if (theAddr == localHost) continue;
NSLog(@"Name: %s MAC: %s IP: %s\n", if_names[i], hw_addrs[i], ip_names[i]);
//decided what adapter you want details for
if (strncmp(if_names[i], "en", 2) == 0)
{
NSLog(@"Adapter en has a IP of %s", ip_names[i]);
}
}
</code></pre>
<p>Adapter names vary depending on the simulator/device as well as wifi or cell on the device.</p>
|
Crippling Test Environments <p>We have a web application that is sufficiently complicated that it's hard to accurately simulate production load.</p>
<p>One of our coping mechanisms has been to make sure that the hardware in the test environment is always slower that our production hardware, so load and performance problems will be more pronounced.</p>
<p>Are other folks out there doing this, what other strategies are you using?</p>
| <p>I have a 7-year-old 600mHz Celeron laptop with 256MB RAM that I keep around for performance profiling. For testing network latency, you could get a delay proxy (or write one trivially); it gets a packet, waits X milliseconds, then passes it on.</p>
|
wxPython: Making a scrollable DC <p>I am drawing inside a wx.Window using a PaintDC. I am drawing circles and stuff like that into that window. Problem is, sometimes the circles go outside the scope of the window. I want a scrollbar to automatically appear whenever the drawing gets too big. What do I do?</p>
| <p>Use a <code>wx.ScrolledWindow</code> and set the size of the window as soon as your 'drawing go outside' the window with</p>
<pre><code>SetVirtualSize(width,height)
</code></pre>
<p>If this size is bigger than the client size, then wx will show scrollbars. When drawing in the window make sure to use <code>CalcUnscrolledPosition</code> and <code>CalcScrolledPosition</code></p>
<p><a href="http://docs.wxwidgets.org/stable/wx%5Fwxscrolledwindow.html" rel="nofollow">Here</a> you can find some more information.</p>
|
Do I need to explicitly call the base virtual destructor? <p>When overriding a class in C++ (with a virtual destructor) I am implementing the destructor again as virtual on the inheriting class, but do I need to call the base destructor?</p>
<p>If so I imagine it's something like this...</p>
<pre><code>MyChildClass::~MyChildClass() // virtual in header
{
// Call to base destructor...
this->MyBaseClass::~MyBaseClass();
// Some destructing specific to MyChildClass
}
</code></pre>
<p>Am I right?</p>
| <p>No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.</p>
|
How does one troubleshoot log4net when it stops logging <p>It seems that Log4Net silently shuts down for reasons that are not obvious, and I'm at a loss how to troubleshoot it. My hunch is that a particular appender is failing on a specific log message and that seems to shut down the whole stack.</p>
<p>Is there a way to get Log4Net to throw an exeception (at least during our debug phase) rather than a slient shutting down of the service.</p>
| <p>Expanding on the previous answer -</p>
<p>To add a trace listener for the log4net.Internal.Debug trace, add this to your app config:</p>
<pre><code> <system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="c:\temp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
</code></pre>
<p>Replace the initializeData attribute value above with your desired log file path. Be sure the application or ASP.NET server process has permission to write to this file.</p>
<p>Another thing you can do is inspect the messages that are returned from the log4net configuration on startup. As of log4net version 1.2.11, the XmlConfigurator.Configure() methods return an ICollection containing strings listing problems encountered during the configuration process.</p>
<p>So if you've got something like this:</p>
<pre><code>XmlConfigurator.Configure();
</code></pre>
<p>change it to</p>
<pre><code>ICollection configMessages = XmlConfigurator.Configure();
</code></pre>
<p>and inspect configMessages in a debugger, or print them out somewhere, e.g.</p>
<pre><code>foreach (string msg in configMessages)
{
Console.WriteLine(msg);
}
</code></pre>
<p>If all else fails, download the log4net source, add the project to your solution, and reference the project instead of log4net.dll. Now you can step into the log4net calls in the debugger.</p>
|
One user can't run app <p>I have one user that can't run my iPhone app. It starts up fine but crashes once they select a row in the RootViewController. Selecting a row goes to another tableview. I'm using sqlite in the app bundle and deploy on initial install if no db is available. The db is there because the RootViewController wouldn't load otherwise. I've tried a few troubleshooting steps with the user such as:</p>
<ul>
<li>Delete app from iPhone and resync with iTunes. </li>
<li>Reboot iPhone.</li>
<li>Confirm version of iPhone.</li>
</ul>
<p>All of the above was tried to no avail.</p>
<p>I've not had any other user write in about such issues. Has anyone had such an issue and have some possible suggestions on how to resolve it?</p>
| <p>I would ask your user to delete the app from <em>both</em> the iPhone <em>and</em> iTunes and then reinstall it. That will help ensure they aren't getting the data restored.</p>
<p>You may also want to make sure they haven't jailbroken their phone. In general, I try to ask for a wide variety of information:</p>
<ul>
<li>Device type</li>
<li>Device generation</li>
<li>OS version</li>
<li>Jailbreak status</li>
<li>Language setting</li>
<li>Region setting</li>
<li>Whether they have WiFi, cellular Internet, and 3G on (I'd also ask about GPS if your app uses that)</li>
</ul>
<p>Finally, iTunes may be stashing crash logs on their hard drive (on Macs it's under <code>~/Library/Logs/CrashReporter/MobileDevice</code>; I don't know about Windows machines). Ask your user to try to locate ones related to your app and send them to you.</p>
|
Key-Value based databases, can someone explain to me how to use them practically? <p>There seems to be a big push for key/value based databases, which I believe memcache to be.</p>
<p>Is the value usually some sort of collection or xml file that would hold more meaningfull data?</p>
<p>If yes, is it generally faster to deserialize data then to do traditinally JOINS and selects on tables that return a row based result set?</p>
| <p>What has happened is that some really, <strong>really</strong>, <strong>REALLY</strong> big web sites like Google and Amazon occupy a teeny, tiny niche where their data storage and retrieval requirements are so different to anyone else's that a new way of storing/retrieving data is called for. I'm sure these guys know what they are doing, they are very good at what they do.</p>
<p>However, then this gets picked up and reported on and distorted into "relational databases aren't up to handling data for the web". Also, readers start to think "hey, if relational databases aren't good enough for Amazon and Google, they aren't good enough for me."</p>
<p>These inferences are both wrong: 99.9% of all databases (including those behind web sites) are not in the same ball park as Amazon and Google - not within several orders of magnitude. For this 99.9%, nothing has changed, relational databases still work just fine.</p>
|
Too much recursion while performing .next in jQuery 1.3.2 <p>I've just upgraded to jQuery 1.3.2, which has mostly been fine, but I'm missing something when it comes to the new event model (I think)</p>
<pre><code>$(document).ready(function()
{
$(".AspNet-Menu-NonLink").click(function()
{
$(this).next($("ul")).slideToggle("fast");
});
$(".AspNet-Menu-NonLink").next($("ul")).hide();
$(".AspNet-Menu-ChildSelected").next($("ul")).show();
});
</code></pre>
<p>This used to work, but the error "too much recursion" is popping out on this line: </p>
<pre><code>$(".AspNet-Menu-NonLink").next($("ul")).hide();
</code></pre>
<p>How can this cause recursion, hide() hides something, what's to go wrong?</p>
<p><strong>UPDATE</strong></p>
<p>I've discovered that if I remove the references to jQuery UI 1.7.1 script library the problem goes away. Even if I'm not calling anything in the jQuery UI library, but have it included I get the error. </p>
| <p>For starters, try using </p>
<pre><code>$(".AspNet-Menu-NonLink").next("ul").hide();
</code></pre>
<p>Instead. </p>
<p>Otherwise, you're implicitly searching for, and returning <em>all</em> <code>ul</code> elements on the page and then passing that <em>massive</em> result to the "<code>next</code>" function. </p>
<p>According to the <a href="http://docs.jquery.com/Traversing/next#overview" rel="nofollow">documentation</a>, '<code>next</code>' takes a string, an expression, that is used to filter its traversal. </p>
<p><code>$("ul")</code> however, executes a DOM query and returns a jQuery object. </p>
|
Create custom generic list with bitmapimage <p>In my WPF project there is a listbox in which I have to display images and next to each image their text (for example : date the photo was taken, location etc).
I have tried creating a generic List but I still can't assign it to the listbox</p>
<p>Something like</p>
<p>Bscially I have been trying something on this lines.</p>
<pre><code>public class LoadImages
{
public static List<ImageLoader> LoadImages()
{
List<ImageLoader> img = new List<ImageLoader>();
Uri uri = new Uri(@"http://somedomain.com/pic.jpg", UriKind.Absolute);
BitmapImage bi = new BitmapImage(uri);
img.Add(new ImageLoader("1_1",bi));
return img;
}
}
public class ImageLoader
{
string mediaid;
BitmapImage thumbnail;
public ImageLoader(string mediaid, BitmapImage b)
{
this.mediaid = mediaid;
this.thumbnail = b;
}
}
</code></pre>
<p>And my XAML looks like this.</p>
<pre><code> <ListBox Name="ListBox1" SelectionMode="Extended" ItemsSource="{Binding}"
Width="300" Height="300" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="{Binding thumbnail}"/>
<TextBlock Text="{Binding mediaid}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
<p>For the time being I have set the Window.DataContext</p>
<pre><code><Window.DataContext>
<ObjectDataProvider ObjectType="{x:Type local:LoadImages}" MethodName="LoadImages"/>
</Window.DataContext>
</code></pre>
<p>But everytime I run the app the listbox shows up empty.</p>
<p>Any suggestions.</p>
| <p>Image element do support Uris for Source property. Why not making your LoadImages class return a set of Uris instead of images? Also image element can do async job for you ;)</p>
|
Win32 printing - cannot set landscape mode <p>I've got an old app that I need to get to print in landscape mode. The documentation I've found says to get a DEVMODE structure, change a couple of fields, and put it back in. What I've got is:</p>
<pre><code> HANDLE printer_handle;
LPHANDLE printer_handle_pointer(&printer_handle);
OpenPrinter(printer_name.get(), printer_handle_pointer, NULL);
size_t devmode_size = DocumentProperties(hWnd, printer_handle_pointer, printer_name.get(), NULL, NULL, 0);
DEVMODE * devmode = reinterpret_cast<DEVMODE *>(new char[devmode_size]);
DocumentProperties(NULL, printer_handle_pointer, printer_name.get(), devmode, NULL, DM_OUT_BUFFER);
devmode->dmSize = sizeof( DEVMODE);
devmode->dmFields |= DM_ORIENTATION;
devmode->dmOrientation = DMORIENT_LANDSCAPE;
DocumentProperties(NULL, printer_handle_pointer, printer_name.get(), devmode, devmode, DM_IN_BUFFER | DM_OUT_BUFFER);
hdcPrint = CreateDC(NULL, printer_name.get(), NULL, devmode);
</code></pre>
<p>My current problem is that the first DocumentProperties (the one that returns the size of the DEVMODE structure) is returning a -1 (actually the unsigned equivalent), signifying an error condition. This happens in both Debug and Release mode (one report I saw on the web had this problem in Debug but not Release). The <code>printer_name.get()</code> is valid, but I don't know how to check the <code>hWnd</code> or <code>printer_handle_pointer</code> for correctness in the debugger.</p>
<p>So, I'd like it if somebody could tell me what I'm doing wrong, or how to diagnose it better, or how to tell if the handles are valid and point to valid information, I'd appreciate it.</p>
<p>I'm using VS 2008SP1 on Vista Business SP1, if that makes any difference. The original app was written with an earlier version of VS on some version of XP.</p>
| <p>Have you posted the real code? </p>
<p>Also, take a look at the DocumentProperties function signature:</p>
<pre><code>LONG DocumentProperties(
__in HWND hWnd,
__in HANDLE hPrinter,
__in LPTSTR pDeviceName,
__out PDEVMODE pDevModeOutput,
__in PDEVMODE pDevModeInput,
__in DWORD fMode
</code></pre>
<p>The third parameter takes a <code>HANDLE</code> and not a pointer to a <code>HANDLE</code> (or <code>LPHANDLE</code>) as you have in your code:</p>
<pre><code>DocumentProperties(NULL,
printer_handle_pointer, /* <--- ? */
printer_name.get(),
devmode,
NULL,
DM_OUT_BUFFER);
</code></pre>
<p>Use instead:</p>
<pre><code>DocumentProperties(NULL,
printer_handle, /* <--- ? */
printer_name.get(),
devmode,
NULL,
DM_OUT_BUFFER);
</code></pre>
<p>Take a look at <a href="http://support.microsoft.com/kb/167345" rel="nofollow">this</a> sample code to modify <code>Devmode</code> using <code>DocumentProperties</code> function.</p>
<p>I typically use <code>GetPrinterW</code> to get a <code>PRINTER_INFO_2W</code> structure. The <code>pDevMode</code> member returns you the devmode. I have had some luck using this devmode.</p>
|
How to access Cognos PowerPlay Cubes with other applications? <p>There are Cognos PowerPlay Cubes (Cognos v7.3) which are distributed via Email and then stored on local clients. At the moment, users use MS Access as an interface to access the data and reports in the Cubes.
Is there any other tool, application or programming language which allows to access the PowerPlay Cubes and the tables/graphs within?</p>
<p>The requirement is to implement a user interface that is much easier to use than the old MS Access one.</p>
<p>To access data directly with Cognos Studios is not an option, because it is obligatory that the data must be available offline too. </p>
<p>Thank you for any ideas.</p>
<p>Best Regards.</p>
| <p>You can access Cognos PowerPlay cubes offline using the Cognos Powerplay version 7.x client, which I believe is packaged with the Transformer application that is used to create the cubes. It will most likely be better than anything you develop yourself.</p>
<p>To my knowledge, there is no API for accessing the data stored directly in the cubes with a programming language. At least not in 7.x.</p>
|
Set ViewData outside the controller <p>I'm trying to create a logger that will write the queries LINQ executes to the page formatted with the great javascript library SyntaxHighlighter.</p>
<p>For that, I've set the DataContext's Log property to my custom logger, which is working well.</p>
<p>Now I just need to get the current Controller object (outside the controller execution context) so I can set some ViewData with what needs to be outputted.</p>
<p>Any suggestions?</p>
| <p>If you want to perform operations outside of the controller, then action-filters (etc) are a good bet; just inherit from <code>ActionFilterAttribute</code>, override <code>OnActionExecuting</code> (etc) to inject data into the view, and mark your controller with <code>[YourCustomFilter]</code>.</p>
<p><a href="http://stackoverflow.com/questions/672327/672550#672550">Like this</a></p>
<p><hr /></p>
<p>(original; I may have misunderstood)</p>
<p>It would be better to use dependency injection here, by passing the log-writer into the repository as a constructor argument (ideally via something like StructureMap, which works very well with MVC via StructureMapControllerFactory, or similar).</p>
|
Execute sql statement via JDBC with CLOB binding <p>I have the following query (column log is of type CLOB):</p>
<pre><code>UPDATE table SET log=? where id=?
</code></pre>
<p>The query above works fine when using the setAsciiStream method to put a value longer than 4000 characters into the log column.</p>
<p>But instead of replacing the value, I want to append it, hence my query looks like this:</p>
<pre><code>UPDATE table SET log=log||?||chr(10) where id=?
</code></pre>
<p>The above query DOES NOT work any more and I get the following error:</p>
<pre><code>java.sql.SQLException: ORA-01461: can bind a LONG value only for insert into a LONG column
</code></pre>
| <p>BLOBs are not mutable from SQL (well, besides setting them to NULL), so to append, you would have to download the blob first, concatenate locally, and upload the result again.</p>
<p>The usual solution is to write several records to the database with a common key and a sequence which tells the DB how to order the rows.</p>
|
How do you make a table read-only using ASP.NET's dynamic data scaffolding <p>How do you make individual tables and/or columns read-only so the edit button won't show in ASP.NET's Dynamic Data framework?</p>
<p>I'm using it against an entity data context.</p>
<p>Is it possible?</p>
| <p>See my article here <a href="http://csharpbits.notaclue.net/2009/01/making-field-read-only-via.html" rel="nofollow">Making a Field Read-Only via the ReadOnlyAttribute â Dynamic Data</a> should get you what you want.</p>
|
WPF Style Trigger <p>I am trying to get a row in a datagrid to turn red if the value of a checkbox within the datagrid is true. Any ideas? Here is what I have so far. I am currently turning the columns red if the mouse rolls over the row.</p>
<p></p>
<p>
</p>
<p>
<br />
</p>
| <p>Take a look at <a href="http://blogs.msdn.com/vinsibal/archive/2008/09/16/wpf-datagrid-styling-rows-and-columns-based-on-header-conditions-and-other-properties.aspx" rel="nofollow" title="Styling WPF DataGrid rows/columns">this blog post by Vincent Sibal</a>. Sibal gives several code examples of what you're trying to do and he also provides a good sample project you can download to see the source.</p>
|
Convert Anchor style for Submit buttons? <p>I have a CSS class that makes my links look like nice looking buttons. I would like to be able to apply the same style to Submit buttons and make them look the same as well. The trickiest part is that the anchor tags need to have a span inside them, I don't think that is possible with form submit buttons. So does anyone know how I can make the submit buttons match the links?</p>
<p>Here is the CSS:</p>
<pre><code>a.button {
background: transparent url('images/all_pages/bg_button_a.jpg') no-repeat scroll top right;
color: #FFF;
display: block;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:16px;
font-weight:bold;
height: 24px;
margin-right: 6px;
padding-right: 18px; /* sliding doors padding */
text-decoration: none;
}
a.button span {
background: transparent url('images/all_pages/bg_button_span.jpg') no-repeat;
display: block;
line-height: 14px;
padding: 5px 0 5px 18px;
}
a.button:hover {
background-position: bottom right;
}
a.button:hover span {
background-position: bottom left;
}
</code></pre>
<p>Thanks!</p>
| <p>Try using the <code><button></code> tag instead of <code><input type="submit"></code>. The <code><button></code> tag lets you nest elements like <code><span></code>, and generally gives you much more styling freedom.</p>
<p>Once you have switched your forms' submit buttons to use the <code><button></code> tag, you can then apply the same CSS to both your links and your buttons:</p>
<pre><code>a.button,
button {
/* ... */
}
a.button span,
button span {
/* ... */
}
a.button:hover,
a.button:focus,
button:hover,
button:focus {
/* ... */
}
a.button:hover span,
a.button:focus span,
button:hover span,
button:focus span {
/* ... */
}
</code></pre>
<p>To improve accessibility, each block of <code>:hover</code> styling above is extended to cover <code>:focus</code> states as well.</p>
<p>Here's a decent article on using the <code><button></code> tag: <a href="http://particletree.com/features/rediscovering-the-button-element/" rel="nofollow">http://particletree.com/features/rediscovering-the-button-element/</a></p>
|
SQL injections with prepared statements? <p>If I remember correctly, I think Jeff has mentioned in the Stack Overflow podcast a possible weakness in SQL prepared statements. I'm wondering what kind(s) of weakness(es) did he refer to? Was it possibly just about <a href="http://www.owasp.org/index.php/Preventing%5FSQL%5FInjection%5Fin%5FJava#Prepared%5FStatements">inappropriate usage</a> thereof, or something more sinister?</p>
<p>The podcast, to my remembering, didn't go deeper into the subject, it was just a pass-by-remark.</p>
| <p>I think what he said was that, when you use Prepared Statements, SQL server could cache your query execution plan, so, even if you modify some of the parameters on the executing query, the server could pick the wrong (probably cached) execution plan that would perform very badly.</p>
<p>He also mentioned a new feature of SQL Server 2008 to force the engine to re-evaluate execution plans that he used to overcome this situation.</p>
<p>With Prepared Statements, the only issue I have is this. Consider the following Java Code:</p>
<pre><code>String sql = "select * from table where name like ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "PATTERN%");
ResultSet rs = pstmt.executeQuery();
</code></pre>
<p>Here you would expect that, if you have an index on table(name) it will be used by the query plan. Well, it won't. Because PraparedStatement must precompile and expect the worst: '%PATTERN%', for example. So, it won't optimize. It took me a while to figure this one out. It was causing my database to suffer. :(</p>
<p>Hope it helps.</p>
|
How can I add non-sequential numbers to a range? <p>I am trying to iterate through the range(750, 765) and add the non-sequential numbers 769, 770, 774. If I try adding the numbers after the range function, it returns the range list, then the individual numbers:</p>
<pre><code>
>>> for x in range(750, 765), 769, 770, 774: print x
...
[750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764]
769
770
774
</code></pre>
<p>How can I get all the numbers in a single list?</p>
| <p>Use the built-in + operator to append your non-sequential numbers to the range.</p>
<pre><code>for x in range(750, 765) + [769, 770, 774]: print x
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.