input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Programatically converting from MS word to Excel <p>Is there anyway to problematically take a MS Word file and convert to excel. (Obviously, word would to guess where to put stuff). Any language would be fine</p>
| <p>That's a pretty wide-open question. The content of the Word document will affect how easy/hard this is.</p>
<p>One method you could look at is using Word automation to open the Word document and then write out a new file using comma-separated format and just name the file with a .xls extension. Upon opening this file up in Excel it should "just work".</p>
<p>If you need rich formatting in your output Excel document, you could use Excel automation to build your output document. Using this you'd have both Word automation (read) and Excel automation (write) in your program.</p>
<p>Another option that I've used (but it's a bit pricey) in a server environment is the Aspose libraries <a href="http://www.aspose.com" rel="nofollow">Aspose</a>. They have a pretty nice API (at least for Word, which is what I've used) and they eliminate the automation angle.</p>
|
Search for nearest value in an array of doubles in C++? <p>I have a sorted array of double values in C++. Is there an STL function that will return the <strong>index</strong> of the <strong>nearest</strong> value in the array to a given double value?</p>
<p>For example, given the following array</p>
<pre><code>double myarray[5] = { 1.0, 1.2, 1.4. 1.5, 1.9 };
</code></pre>
<p>the function call</p>
<pre><code>search(myarray, 1.6);
</code></pre>
<p>should return <code>3</code>, the index of the element nearest to 1.6, instead of <code>-1</code> (or some other flag value) indicating that the value 1.6 wasn't found.</p>
| <p>maybe <code>std::lower_bound</code> <code>std::upper_bound</code> will help you.</p>
|
Fast pixel plotting using SWT? <p>I'm looking for a fast and easy way to plot arbitrarily colored pixels in an SWT Canvas.
So far I'm using something like that:</p>
<pre><code>// initialization:
GC gc = new GC(canvas);
// inside the drawing loop:
Color cc = new Color(display, r, g, b);
gc.setForeground(cc);
gc.drawPoint(x, y);
cc.dispose();
</code></pre>
<p>This is horribly horribly slow. it takes about a second and a half to fill a 300x300 canvas with pixels.
I could create an image off-screen, set the pixels in it and then draw the image. This will be faster but I specifically want the gradual painting effect of plotting the image pixel by pixel on the canvas.</p>
| <p>I bet that what is killing performance is allocating and releasing 90,000 <code>Color</code> objects. Remember, in SWT, each <code>Color</code> object allocates native resources, which is why you have to <code>dispose()</code> it. This means each time you allocate and dispose a <code>Color</code> object, you have to transition from the JVM to native code and back.</p>
<p>Can you cache your <code>Color</code> instances while in the 300x300 pixel loop and then dispose of the objects after your loop? You'd need a somewhat intelligent cache that only holds a maximum of so many objects, and after that will dispose of some of its entries, but this should speed things up <strong>greatly</strong>.</p>
|
Escaping HTML in Rails <p>What is the recommended way to escape HTML to prevent XSS vulnerabilities in Rails apps?</p>
<p>Should you allow the user to put any text into the database but escape it when displaying it? Should you add before_save filters to escape the input?</p>
| <p>There are three basic approaches to this problem.</p>
<ol>
<li>use <code>h()</code> in your views. The downside here is that if you forget, you get pwnd.</li>
<li>Use a plugin that escapes content when it is saved. My plugin <a href="http://github.com/look/xss%5Fterminate/tree/master">xss_terminate</a> does this. Then you don't have to use <code>h()</code> in your views (mostly). There are others that work on the controller level. The downsides here are (a) if there's a bug in the escaping code, you could get XSS in your database; and (b) There are corner cases where you'll still want to use <code>h()</code>.</li>
<li>Use a plugin that escapes content when it is displayed. <a href="http://xss.rubyforge.org/">CrossSiteSniper</a> is probably the best known of these. This aliases your attributes so that when you call foo.name it escapes the content. There's a way around it if you need the content unescaped. I like this plugin but I'm not wild about letting XSS into my database in the first place...</li>
</ol>
<p>Then there are some hybrid approaches.</p>
<p>There's no reason why you can't use xss_terminate and CrossSiteSniper at the same time.</p>
<p>There's also a ERb implementation called <a href="http://www.kuwata-lab.com/erubis/">Erubis</a> that can be configured so that any call like <code><%= foo.name %></code> is escaped -- the equivalent of <code><%= h(foo.name) %></code>. Unfortunately, Erubis always seems to lag behind Rails and so using it can slow you down.</p>
<p>If you want to read more, I wrote a blog post (which Xavor kindly linked to) about <a href="http://railspikes.com/2008/1/28/auto-escaping-html-with-rails">using xss_terminate</a>.</p>
|
Where are all the places that VBA macros for Excel 2007 can be turned off? <p>Macros refuse to run for me in Excel 2007 on Windows Server 2003.
The macro and visual basic icons on the ribbon are grayed out.
If I open a workbook with a macro, I get the warning: " This workbook has lost its VBA project, ActiveX controls and any other programmability-related features."
If I try to make a new excel template in VSTO (Excel is closed at the time), I get the error: "Programmatic access to the Microsoft Office Visual Basic for Applications project system could not be enabled. . ."</p>
<p>I checked that VBA was installed (originally it wasn't, I added it via office setup). I also tried uninstalling and reinstalling office and VBA, no dice.
I made a macro-enabled workbook.
I set the workbook's location to trusted.
I configured all of the security settings available under Excel Options/Trust Center to allow-everything-no-prompts.
I set "Enable all macros" and "Trust access to the VBA object model".
I downloaded the group policy admin templates and verified none of this is being set via group policy.</p>
<p>That's everything I can find in Google to try, but clearly there is another place that VBA can be turned off. Where else can I look?</p>
| <p>Are you sure there isn't a system policy in place that inhibits VBA?</p>
<p>Edit: Some reading, if you've not already seen these:</p>
<p><a href="http://support.microsoft.com/kb/282847/en-us" rel="nofollow">http://support.microsoft.com/kb/282847/en-us</a></p>
<p><a href="http://support.microsoft.com/kb/287567" rel="nofollow">http://support.microsoft.com/kb/287567</a></p>
<p><a href="http://support.microsoft.com/kb/281954/en-us" rel="nofollow">http://support.microsoft.com/kb/281954/en-us</a> - Applies to earlier versions, but some/all may still be relevant to 2k7</p>
|
Sys.WebForms.PageRequestManagerServerErrorException: An unknown error <p>I have created a text area that allows users to enter html code. When I attempt to post this code back to the server, I get a popup window that says "Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occured while processing the request on the server. The status code returned from the server was: 500".</p>
<p>I believe this has something to do with the fact that what I am posting back contains html.</p>
<p>How do I do this safely and without causing this error message?</p>
<p>Thanks!</p>
| <p>It's a very generic error seemingly caused by any number of things unfortunately, from app recycling, corrupted cookies, RoleManager, anything..</p>
<p>For reference:</p>
<ul>
<li><a href="http://forums.asp.net/p/1046935/1576341.aspx#1576341" rel="nofollow">http://forums.asp.net/p/1046935/1576341.aspx#1576341</a></li>
<li><a href="http://forums.asp.net/p/1069384/1555817.aspx" rel="nofollow">http://forums.asp.net/p/1069384/1555817.aspx</a></li>
</ul>
<p>I would <em>strongly</em> advise against turning validation off, that's not fixing the problem it's merely hiding the symptom and it's opening the door to XSS to do so.</p>
|
Change selected and unfocused Listbox style to not be grayed out <p>I have a really simple WPF ListBox with SelectionMode set to Multiple.</p>
<pre><code><ListBox SelectionMode="Multiple" />
</code></pre>
<p>When the ListBox loses focus it's really hard to tell what's been selected because the selection colour changes from blue to a light grey colour. What's the easiest way of changing this behaviour so that it stays blue?</p>
<p>I know it's probably something to do with the ListItem's style, but I can't find where.</p>
<p>Cheers.</p>
<p><strong>Similar:</strong>
<a href="http://stackoverflow.com/questions/382006/wpf-listview-inactive-selection-color">WPF ListView Inactive Selection Color</a></p>
| <p>I have done something like this using the following in a merged ResourceDictionary, it may help you:</p>
<pre><code><Style TargetType="ListBoxItem">
<Style.Resources>
<!--SelectedItem with focus-->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightBlue" Opacity=".4"/>
<!--SelectedItem without focus-->
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey }" Color="LightBlue" Opacity=".4"/>
</Style.Resources>
</Style>
</code></pre>
|
What is the best way to programatically convert a word document with a table structure to XML <p>So, I have this word document that has a whole bunch of tables some of which are pretty long. It spans many many pages in some cases. I need to programmatically convert this thing to XML. </p>
<p>I was initially told we could just copy paste into Excel and save it as a CSV, then I could convert from there which would be pretty easy. However, due to the formatting of some of the fields there would need to be a lot of extra manipulation on the spreadsheet after copying to Excel to get it to look right and to have the CSV come out correctly.</p>
<p>I should note that this is an add-on for an old app written in VB.Net 1.1 (cue frowny face) :(. However, I'm debating just writing a separate command line tool in C# 3.5 if that'll make it easier. Seems like C# has some Word interop stuff that I doubt was in the 1.1 framework, but I haven't investigated that too far.</p>
<p>So, I'm just looking for the best/quickest way this can be achieved. It doesn't matter so much how it's achieved as long as it is achieved and it's done programmatically. Some of the steps could be done manually if they aren't too tough. Like if getting it to some other format first would save a bunch of coding and isn't too difficult that would be fine.</p>
<p>Has anyone done anything like this before? Any ideas? </p>
<p><b>Update</b>
Ok, so here is an example of exactly what I'd need to do.</p>
<p>I have a word doc that looks something like this...</p>
<pre><code>PROTOCOL: BIRDS
Field Name Data Type Required Length Total Digits Fraction Digits ValidValues/Comparison Description
OBSERVATION_ID Text Yes 16 n/a n/a Unique observation identification. Primary key.
</code></pre>
<p>So, there's the table with it's name and vendor (Protocol and Birds in this case). As an example it just has one field. Valid values/comparisons can have multiple things separated by commas where each thing would be enclosed by value tags inside the XML.</p>
<p>Now what I basically need to do is get that to convert to this XML...</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Formats xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="Formats.xsd">
<VendorFormats Vendor="PROTOCOL" LastModified="2005-9-13">
<Format Name="BIRDS" Version="3" VersionDate="2005-9-10">
<BaseTable>BIRDS</BaseTable>
<StageTable>STAGE_BIRDS</StageTable>
<Fields>
<Text Name="OBSERVATION_ID" Required="Y">
<NullValue />
<Description>Unique observation identification. Primary key.</Description>
<Length>16</Length>
</Text>
</Fields>
</Format>
</VendorFormats>
</Formats>
</code></pre>
<p>There will always be a base table and a stage table where base table is the same name as whatever follows the colon at the beginning of the (PROTOCOL: BIRDS, so it would be BIRDS) and the stage table is always STAGE_ then what follows the colon. You'll also notice the version and the last modified and version date in the XML. These things can be worried about later and perhaps manually added.</p>
| <p>You should realize that there is no such thing as a MS Word document. There are numerous formats and some early format are not deserving of the name, but are better described as memory dumps of hacky compressed text.
You're not really in need of XML, that is a later concern. You have to take control of the data in the document. Unless that is one of the newest, somewhat documented formats, you have but one option: hack it out. Write a program to manipulate the document, until you get what you want.
The only one who knows MS-Word formats is MS-Word herself. So if you can convince her to dump the content to a more-or-less defined format like RTF, you have a better starting point.</p>
|
applet fails to load class from jar <p>Some users are complaining that the applet no longer works, When they view the java console they are greeted with a java.lang.noClassDefFoundError and checking my access log's I see they have downloaded the jar file that contains the class, and then issue a get request for the particular class.</p>
<p>Different users break on different classes.</p>
<p>Some users are fine.</p>
<p>Any ideas what could cause this/fix this.</p>
<p>I have checked to make sure the file is in their java cache, cleared the cache etc. nothing seems to fix them.</p>
<p>If they hit a qa site it breaks as well.</p>
| <p>The jar is getting corrupted in transit, We are looking at getting patches from oracle/bea for the server.</p>
<p>It appears that if a connection is too slow (Modem speeds) that weblogic will signal the end of a transfer by sending a packet with len=0.</p>
<p>The network will signal java saying the download completed successfully and then java fails with a java.lang.noClassDefFoundError.</p>
|
Catching when user selects an item from a CComboBox <p>This is as basic as it gets.</p>
<p>I want to catch when the user selects an item from a CComboBox (actually, a subclass of CComboBox).</p>
<p>Tried lots of combinations of OnCblSelChange, OnCommand. Guess I haven't hit the right combo yet (no pun intended). </p>
<p>OS is Vista but I'm forcing an XP-style dialog (That shouldn't matter, should it?)</p>
<p>I'm able to catch events for classes derived from CEdit and CFileDialog.</p>
<p>I am at my wits end here. Any assistance would be ever-so appreciated.</p>
<p>Any source code would, of course, be more than ever-so appreciated.</p>
| <p>Unfortunately, it seems that all messages (even <code>SELEND_OK</code>) for combo box changing are sent <em>before</em> the text has actually changed, so DoDataExchange will give you the previous text in the CComboBox. I have used the following method, <a href="http://msdn.microsoft.com/en-us/library/12h9x0ch%28VS.80%29.aspx" rel="nofollow">as suggested by MSDN</a>:</p>
<pre><code>void MyDialog::DoDataExchange(CDataExchange* pDX)
{
DDX_Text(pDX, IDC_COMBO_LOCATION, m_sLocation);
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(MyDialog, CDialog)
ON_CBN_SELENDOK(IDC_COMBO1, &MyDialog::OnComboChanged)
ON_CBN_EDITUPDATE(IDC_COMBO1, &MyDialog::OnComboEdited) // This one updates immediately
END_MESSAGE_MAP()
...
void MyDialog::OnComboChanged()
{
m_myCombo.GetLBText(m_myCombo.GetCurSel(), m_sSomeString);
}
void MyDialog::OnComboEdited()
{
UpdateData();
}
</code></pre>
<p>It seems to work quite nicely.</p>
|
What is the simplest way to lock an object in Django <p>I want to raise error when a user tries to delete an object when some other users are active in update_object view. I feel some sort of mutex-like locking mechanism is needed for that. Do you have any suggestions?</p>
| <p>So, there are a handful of ways to do what you're asking. But a good number of them are not going to be implementation independent: you could use locks or rlocks, but they will really only work on 100% threaded servers and probably not at all in a fork/pre-fork implementation.</p>
<p>That more or less means the locking implementation will be up to you. Two ideas:</p>
<ol>
<li><code>.lock</code> file on your file system</li>
<li><code>locked</code> property in your model class</li>
</ol>
<p>In both cases, you have to manually set the lock object on update and check against it on delete. Try something like:</p>
<pre><code>def safe_update(request,model,id):
obj = model.objects.get(id)
if obj.locked:
raise SimultaneousUpdateError #Define this somewhere
else:
obj.lock()
return update_object(request,model,id)
# In models file
class SomeModel(models.Model):
locked = models.BooleanField(default = False)
def lock(self):
self.locked = True
super(models.Model,self).save()
def save(self):
# overriding save because you want to use generic views
# probably not the best idea to rework model code to accomodate view shortcuts
# but I like to give examples.
self.locked = False
# THIS CREATES A DIFFERENT CRITICAL REGION!
super(models.Model,self).save()
</code></pre>
<p>This is indeed a clumsy implementation that you'll have to clean up. You may not be comfortable with the fact that a different critical region has been created, but I don't see how you'll do much better if your using the database as an implementation without making the implementation much more complicated. (One option would be to make the locks entirely separate objects. Then you could update them after the save() method is called. But I don't feel like coding that up.) If you really want to use a file-based locking system, that would also solve the problem. If you're database-hit-paranoid, this might be the thing for you. Something like:</p>
<pre><code>class FileLock(object):
def __get__(self,obj):
return os.access(obj.__class__+"_"+obj.id+".lock",os.F_OK)
def __set__(self,obj,value):
if not isinstance(value,bool):
raise AttributeError
if value:
f = open(obj.__class__+"_"+obj.id+".lock")
f.close()
else:
os.remove(obj.__class__+"_"+obj.id+".lock")
def __delete__(self,obj):
raise AttributeError
class SomeModel(models.Model):
locked = FileLock()
def save(self):
super(models.Model,self).save()
self.locked = False
</code></pre>
<p>Anyway, maybe there's some way to mix and match these suggestions to your taste?</p>
|
Gracefully handle validation errors in a XML file in C# <p>The description is bit on the longer side please bear with me. I would like to process and validate a huge XML file and log the node which triggered the validation error and continue with processing the next node. A simplified version of the XML file is shown below. </p>
<p>What I would like to perform is on encountering any validation error processing node 'A' or its children (both XMLException and XmlSchemaValidationException) I would like to stop processing current node log the error and XML for node 'A' and move on to the next node 'A'.</p>
<pre><code><Root>
<A id="A1">
<B Name="B1">
<C>
<D Name="ID" >
<E>Test Text 1</E>
</D>
<D Name="text" >
<E>Test Text 1</E>
</D>
</C>
</B>
</A>
<A id="A2">
<B Name="B2">
<C>
<D Name="id" >
<E>Test Text 3</E>
</D>
<D Name="tab1_id" >
<E>Test Text 3</E>
</D>
<D Name="text" >
<E>Test Text 3</E>
</D>
</C>
</B>
</Root>
</code></pre>
<p>I am currently able to recover from the XmlSchemaValidationException by using a ValidationEventHandler with XMLReader which throws a Exception that I handle in the XML Processing code. However for some cases XMLException is being triggered which leads to termination of the process. </p>
<p>The following snippets of the code illustrate the current structure I am using; it is messy and code improvement suggestions are also welcome.</p>
<pre><code> // Setting up the XMLReader
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Auto;
settings.IgnoreWhitespace = true;
settings.CloseInput = true;
settings.IgnoreComments = true;
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, "schema.xsd");
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
XmlReader reader = XmlReader.Create("Sample.xml", settings);
// Processing XML
while (reader.Read())
if (reader.NodeType == XmlNodeType.Element)
if (reader.Name.Equals("A"))
processA(reader.ReadSubtree());
reader.Close();
// Process Node A
private static void processA(XmlReader A){
try{
// Perform some book-keeping
// Process Node B by calling processB(A.ReadSubTree())
}
catch (InvalidOperationException ex){
}
catch (XmlException xmlEx){
}
catch (ImportException impEx){
}
finally{ if (A != null) A.Close(); }
}
// All the lower level process node functions propagate the exception to caller.
private static void processB(XmlReader B){
try{
// Book-keeping and call processC
}
catch (Exception ex){
throw ex;
}
finally{ if (B != null) B.Close();}
}
// Validation event handler
private static void ValidationCallBack(object sender, ValidationEventArgs e){
String msg = "Validation Error: " + e.Message +" at line " + e.Exception.LineNumber+
" position number "+e.Exception.LinePosition;
throw new ImportException(msg);
}
</code></pre>
<p>When a XMLSchemaValidationException is encountered the finally block will invoke close() and the original XMLReader is being positioned on the EndElement of the subtree and hence the finally block in processA will lead to processing of the next node A.</p>
<p>However when a XMlException is encountered invoking the close method is not positioning the original reader on the EndElement node of the subtree and an InvalidOperationException is being throw.</p>
<p>I tried to use methods like skip, ReadToXYZ() methods but these are invariably leading to XMLExcpetion of InvalidOperationException when invoked on any node that triggered an exception.</p>
<p>The following is a excerpt from MSDN regarding the ReadSubTree method.</p>
<blockquote>
<p>When the new XmlReader has been
closed, the original XmlReader will be
positioned on the EndElement node of
the sub-tree. Thus, if you called the
ReadSubtree method on the start tag of
the book element, after the sub-tree
has been read and the new XmlReader
has been closed, the original
XmlReader is positioned on the end tag
of the book element.</p>
</blockquote>
<p>Note: I cannot use .Net 3.5 for this, however .Net 3.5 suggestions are welcome. </p>
| <p>See this question:<br />
<a href="http://stackoverflow.com/questions/32505/xml-parser-validation-report">http://stackoverflow.com/questions/32505/xml-parser-validation-report</a></p>
<p>You need to distinguish between <em>well-formed</em> xml (it follows the rules required to be real xml) and <em>valid</em> xml (follows additional rules given by a specific xml schema). From the spec:</p>
<blockquote>
<p>Once a fatal error is detected, however, the processor must not continue normal processing (i.e., it must not continue to pass character data and information about the document's logical structure to the application in the normal way).</p>
</blockquote>
<p>For better or worse, the xml tools included with Visual Studio need to follow that spec very closely, and therefore will not continue processing if there is a well-formedness error. The link I provided might give you some alternatives.</p>
|
Inundated with marketing tracking pixels (Campaigns with multiple vendors)! <p>We have some third parties that are sending us traffic and have asked us to put a tracking pixel on the confirmation page so they can track through the sales.</p>
<p>We are currently using Google analytics for our own usage.</p>
<p>Google will <a href="http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55540" rel="nofollow">remember the original referral</a> through cookies. This may be a good or bad thing. If someone purchases through company B's link but they had originally found our site through company A - then company A still gets the 'referal'. That doesn't seem fair, but it seems to be the way google analytics works:</p>
<blockquote>
<p>For example, if this is the user's
first visit to your site, the tracking
code will add the campaign tracking
information to the cookie. If the user
previously found and visited your
site, the tracking code increments the
session counter in the cookie.
Regardless of how many sessions or how
much time has passed, Google Analytics
"remembers" the original referral.
This gives Analytics true
multi-session tracking capability.</p>
</blockquote>
<p>Currently we only have one tracking pixel on our 'receipt page' from a company that we're not even doing business with. Having a second company ask me for us to add one makes me thing 'wait a minute - we're going to suddenly be inundated with these things!'. Plus it means someone can look at the source and see all the people we do business with.</p>
<p>This isn't Oprah - you cant ALL have tracking pixels. Right ?</p>
<p>How should we manage sales from multiple traffic sources in the most honest way for both sides - especially if they already have a system set up that they insist on using?</p>
| <p>Here's how I solved the problem at our company: we gave our partners a URL that has a parameter in the query string. This parameter triggers a cookie. On the "goal"/confirmation page (where the tracking pixel is usually inserted), we insert some logic to see if the cookie value is correlated with a one of our recognized partners (chained if-else or switch statement). If a match is found, then the tracking pixel is displayed.</p>
<p>Even though you asked this question a while ago, I hope that this still helps you or someone else with the same problem!</p>
|
What would be a good way to add a help system to Silverlight applications? <p>What would be a good way to integrate a help system into Silverlight applications?
The original manual is written in MS Word, so I will need some means to transfer it to whatever format you suggest. Also if your answer is HTML can you explain in details the integration process (HTML popup windows are effectively blocked by most of the browsers).</p>
| <p>I've written some code to convert Word documents to XAML to aid in the process:
<a href="http://www.codeplex.com/Word2007ToXaml" rel="nofollow">Word 2007 XAML Generator</a></p>
<p>Michael</p>
|
Problems with DataGridTemplateColumn with ComboBox <p>I have a DataGrid template column with ComboBox. When I select a value and press enter the bound data is not updated (I see empty cell).</p>
<p>XAML:</p>
<pre><code><Window x:Class="WpfGrid2.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WpfToolkit"
>
<Window.Resources>
<x:Array x:Key="people" Type="sys:Object" />
<x:Array x:Key="knownLastNames" Type="sys:String">
<sys:String>Smith</sys:String>
<sys:String>Johnson</sys:String>
<sys:String>Williams</sys:String>
</x:Array>
</Window.Resources>
<StackPanel>
<dg:DataGrid x:Name="_grid" ItemsSource="{DynamicResource people}" CanUserAddRows="True" AutoGenerateColumns="False">
<dg:DataGrid.Columns>
<dg:DataGridTemplateColumn Header="LastName" MinWidth="100">
<dg:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{DynamicResource knownLastNames}" SelectedItem="{Binding LastName}"></ComboBox>
</DataTemplate>
</dg:DataGridTemplateColumn.CellEditingTemplate>
<dg:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding LastName}" />
</DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
</dg:DataGrid.Columns>
</dg:DataGrid>
<Button>test</Button>
</StackPanel>
</Window>
</code></pre>
<p>Code-Behind:</p>
<pre><code>namespace WpfGrid2
{
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
List<Person> people = new List<Person>();
this.Resources["people"] = people;
}
}
}
</code></pre>
<p>If I change ComboBox to TextBox, it works fine</p>
<pre><code><TextBox Text="{Binding LastName}" />
</code></pre>
<p>What is wrong?</p>
| <p>I don't know if this is a feasible solution to your problem, but if you change the ItemsSource binding of the Combo-Box to a StaticResource, the binding works. </p>
<pre><code>...
<ComboBox ItemsSource="{StaticResource knownLastNames}" ... />
...
</code></pre>
<p>I am pretty sure that what is happening is that when the ComboBox is unloaded (when the EditTemplate is unloaded due to submitting the new record), the DynamicResource attempts to lookup the resource again, and fails (because the ComboBox is no longer in the visual tree, it won't find the resource defined above it in the visual tree). This will set the ItemsSource to null, and also set the SelectedItem to null, thus setting LastName to null. </p>
<p>With a StaticResource, the collection is only searched for once, before the ComboBox is shown, so it is not reset to null.</p>
|
Universal Comment Identifier for .NET <p>What is the most prohibitive aspect of having a universal comment identifier for all .net languages?</p>
<p>For example, in each language the symbol "??" would identify a comment. (I'm not saying that it <em>should</em> be "??"... just an example.)</p>
| <p>In C#, the '??' operator denotes null coalescence. Repurposing this for comments would render a large amount of code non-operational.</p>
<p>I know you said it's just an example, but this is the problem you're facing - finding a single token that isn't used in any .NET language. I don't think it's a practical goal.</p>
<p>One of the goals of .NET was to allow multiple languages to target the runtime environment, while allowing those languages to retain their own distinction. Your idea runs directly against the grain of this goal.</p>
|
Why should I implement ICloneable in c#? <p>Can you explain to me why I should inherit from <code>ICloneable</code> and implement the <code>Clone()</code> method?</p>
<p>If I want to do a deep copy, can't I just implement my method? Let's say <code>MyClone()</code>?</p>
<p>Why should I inherit from <code>ICloneable</code>? What are the advantages? Is it just a matter of making code "more readable"?</p>
| <p>You shouldn't. Microsoft recommends against implementing <code>ICloneable</code> because there's no clear indication from the interface whether your <code>Clone</code> method performs a "deep" or "shallow" clone.</p>
<p>See <a href="http://blogs.msdn.com/brada/archive/2003/04/09/49935.aspx">this blog post from Brad Abrams</a> back in 2003(!) for more information.</p>
|
std::map design: why map accept comparator as template parameter <p>Map type from STL have next type: </p>
<pre><code>std::map< Key, Data, Compare, Alloc >
</code></pre>
<p>As one of template parameters we could pass <code>Compare</code> predicate, why map accept this predicate as template parameter and not as object in constructor? </p>
<p>It could has more flexible interface with something like <code>boost::function< bool, const T&, const T& ></code> in constructor.<br />
Ofcourse I'm understend that when STL was designed boost does not exists, but designers could be create something similar on boost::function. </p>
<p>I belive it has some deep reasons.</p>
<p><strong>EDITED</strong><br />
Sorry for dummy question, map have same posibility :)<br />
My question doesn't have sense after your answers.</p>
| <p>The template argument is the <em>type</em> of the predicate, not the value. The value <em>can</em> be provided as an argument to the constructor. You can specify any value that matches the type. As given, the default type is <code>std::less<Key></code>, which pretty much only has one value, but you should be able to specify your own type for the <code>Compare</code> argument, including <code>boost::function</code>, and then use various values to control the behavior of your map objects.</p>
|
If you break long code lines, how do you indent the stuff on the next line? <p>Sometimes you have to write in your source long lines, that are better to break. How do you indent the stuff ceated by this.</p>
<p>You can indent it the same:</p>
<pre><code>very long
statement;
other statement;
</code></pre>
<p>That makes it harder to differentiate from the following code, as shown in the example. On the other hand you could indent it one level:</p>
<pre><code>very long
statement;
other statement;
</code></pre>
<p>That makes it easier, but it can happen, that the long line is the start of a nested block, that you want to indent, like this:</p>
<pre><code>if ((long test 1) &&
(long test 2) &&
(long test 3)) {
code executed if true;
}
</code></pre>
<p>In this case again it's hard to read. The third possibility I can think of, is to not break long lines at all, modern editors can handle it and create soft linebreaks. But with another editor you have to scroll sideways and you cannot influence the position, the editor breaks your long line.</p>
<p>What possibility do you prefer? Do you have other ideas to solve this? Can you support your preference with a good justification?</p>
| <p>I like braces on their own line because I fine it easier to see the condition and inner block all as one item (if you know what I mean):</p>
<pre><code>if ((long test 1)
&& (long test 2)
&& (long test 3))
{
code executed if true;
}
</code></pre>
<p>and I like starting additional conditional lines with what the condition is because I find that the "joining" condition is very important and it tends to get overlooked at the end of the previous line.</p>
<p>I also try and indent such that the effect of parenthesis are obvious (though trying to avoid long conditionals is generally a good thing).</p>
<p>I try and structure stuff so that I can easily "scan" for "stuff" :)</p>
|
What's the best way to tell if a Python program has anything to read from stdin? <p>I want a program to do one thing if executed like this:</p>
<pre><code>cat something | my_program.py
</code></pre>
<p>and do another thing if run like this</p>
<pre><code>my_program.py
</code></pre>
<p>But if I read from stdin, then it will wait for user input, so I want to see if there is anything to read before trying to read from stdin.</p>
| <p>If you want to detect if someone is piping data into your program, or running it interactively you can use isatty to see if stdin is a terminal:</p>
<pre><code>$ python -c 'import sys; print sys.stdin.isatty()'
True
$ echo | python -c 'import sys; print sys.stdin.isatty()'
False
</code></pre>
|
What do + and * mean in regex? <p>I got an answer to my question here: <a href="http://stackoverflow.com/questions/699253/how-to-find-out-if-file-is-tab-or-space-delimited-in-perl/699256#699256">http://stackoverflow.com/questions/699253/how-to-find-out-if-file-is-tab-or-space-delimited-in-perl/699256#699256</a></p>
<p>but it would really help me if someone could break down the regex and explain what is going on and why it wont work on the last line of the file. </p>
<pre><code>~/^(\d+\s+)+?$/
</code></pre>
<p>I thought the above had '+' in theback so if i add '*' it will work because * means zero or more...but that did not work</p>
| <pre><code>Regex: /^(\d+\s+)+?$/
Parts: 1 2 3 456
</code></pre>
<ol>
<li>Match from the start of a line</li>
<li>Find one or more numbers</li>
<li>Followed by one or more spaces (or tabs)</li>
<li>Find one or more of <strong>2</strong> and <strong>3</strong></li>
<li>But don't be greedy in that match (that is, stop when you can, don't keep going until you can't)</li>
<li>Match the end of a line.</li>
</ol>
<p>It should match a string of an entire line of space or tab separated numbers. I'm not exactly sure about why it'd be failing on the last line.. perhaps there's no space character at the end? Since each number must be followed by at least one space, that might be it.</p>
|
Make UserControl remove itself <p>Does anyone see anything wrong with this:</p>
<pre><code>this.Controls.Remove(this);
</code></pre>
<p><code>this</code> is a class which extends user control. When I step through this section of code it looks like everything is fine, however nothing happens to the form. I would expect the control to be gone.</p>
<p>Thanks,</p>
<p>brian</p>
| <p>As mentioned, you're removing the control from itself...that's not likely what you want. I assume you want to remove the control from it's <em>parent</em> - so you probably want <code>this.Parent.Controls.Remove(this);</code>.</p>
<p>Luckily, since you didn't mention platform, the code is the same for <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.parent.aspx">WebForms</a> or <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.parent.aspx">WinForms</a>.</p>
|
Lucene analyzer and dots <p>Am newbie to Lucene.</p>
<p>Is there any way I can make Lucene analyzer not ignore dots in the string??
for example,if my search criteria is: "A.B.C.D",Lucene should give me only those documents in the search results which have "A.B.C.D" and not "ABCD"....</p>
| <p>It's all about the analyzer you use. The <a href="http://lucene.apache.org/core/old_versioned_docs/versions/3_0_2/api/core/org/apache/lucene/analysis/standard/StandardAnalyzer.html" rel="nofollow"><code>StandardAnalyzer</code></a> does <a href="http://stackoverflow.com/questions/660298/multifieldqueryparser-is-removing-dots-from-the-acronym/661316#661316">some complicated things</a> with dotted names, in an attempt to "Do What You Mean". Perhaps the <a href="http://lucene.apache.org/core/old_versioned_docs/versions/3_0_2/api/all/org/apache/lucene/analysis/WhitespaceAnalyzer.html" rel="nofollow"><code>WhitespaceAnalyzer</code></a> will be a better match for your needs.</p>
<pre><code>public static void main(String[] args) throws Exception {
RAMDirectory dir = new RAMDirectory();
IndexWriter iw = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
Document doc = new Document();
doc.add(new Field("text", "A.B.C.D DEF", Field.Store.YES, Field.Index.ANALYZED));
iw.addDocument(doc);
iw.close();
IndexSearcher searcher = new IndexSearcher(dir);
QueryParser queryParser = new QueryParser("text", new WhitespaceAnalyzer());
// prints 0
System.out.println(searcher.search(queryParser.parse("ABCD"), 1).totalHits);
// prints 1
System.out.println(searcher.search(queryParser.parse("A.B.C.D"), 1).totalHits);
}
</code></pre>
|
Is it possible to create a class that represents another type in Python, when directly referenced? <p>So if I have a class like:</p>
<pre><code>CustomVal
</code></pre>
<p>I want to be able to represent a literal value, so like setting it in the constructor:</p>
<pre><code>val = CustomVal ( 5 )
val.SomeDefaultIntMethod
</code></pre>
<p>Basically I want the CustomVal to represent whatever is specified in the constructor.</p>
<p>I am not talking about custom methods that know how to deal with CustomVal, but rather making it another value that I need.</p>
<p>Is this possible?</p>
<p>Btw 5 is just an example, in reality it's a custom COM type that I want to instance easily.</p>
<p>So by referencing CustomVal, I will have access to int related functionality (for 5), or the functionality of the object that I want to represent (for COM).</p>
<p>So if the COM object is RasterizedImage, then I will have access to its methods directly:</p>
<pre><code>CustomVal.Raster () ...
</code></pre>
<p>EDIT: This is what I mean: I don't want to access as an attribute, but the object itself:</p>
<pre><code>CustomVal
</code></pre>
<p>instead of:</p>
<pre><code>CustomVal.SomeAttribute
</code></pre>
<p>The reason I want this is because, the COM object is too involved to initialize and by doing it this way, it will look like the original internal implementation that app offers.</p>
| <p>The usual way to wrap an object in Python is to override <code>__getattr__</code> in your class:</p>
<pre><code>class CustomVal(object):
def __init__(self, value):
self.value = value
def __getattr__(self, attr):
return getattr(self.value, attr)
</code></pre>
<p>So then you can do</p>
<pre><code>>>> obj = CustomVal(wrapped_obj)
>>> obj.SomeAttributeOfWrappedObj
</code></pre>
<p>You can also override <code>__setattr__</code> and <code>__delattr__</code> to enable setting and deleting attributes, respectively (see <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fgetattr%5F%5F" rel="nofollow">the Python library documentation</a>).</p>
|
navigating through different drive letters in python os.system <p>I am having a problem with a bit of code on one windows machine but not all windows machines. i have the following code:</p>
<pre><code>path = "F:/dir/"
os.system(path[0:2] + " && cd " + path + " && git init")
</code></pre>
<p>On all but one of my windows systems it runs fine but on a windows 2003 server it gives a "directory not found" error but if i run the same command flat from the command prompt than it works.</p>
<p>I'm sorry if my question comes off as vague but I'm totally stumped </p>
| <p><a href="http://docs.python.org/library/os.path.html" rel="nofollow">os.path</a> contains many usefull path manipulation functions. Probably just handling the path cleanly will resolve your problem.</p>
<pre><code>>>> import os
>>>
>>>
>>> path = "F:/dir/"
>>>
>>> clean_path = os.path.normpath(path)
>>> clean_path
'F:\\dir'
>>> drive, directory = os.path.splitdrive(clean_path)
>>> drive
'F:'
>>> directory
'\\dir'
</code></pre>
<p>Also, you might want to look into using the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module, it gives you more control over processes.</p>
<p><a href="http://docs.python.org/library/subprocess.html#subprocess-replacements" rel="nofollow">Replacing Older Functions with the subprocess Module</a></p>
|
Inserting with asp:ListView inside asp:FormView <p>I have a asp:listview which uses the SelectedValue of the FormView.</p>
<p>I have editing working with the listview fine, and insert will insert a record but it doesnt insert the SelectedValue of the parent FormView...</p>
<p>What am I missing?</p>
| <p>I added this</p>
<pre><code> protected void ProposalAddressListView_ItemInserting(object sender, ListViewInsertEventArgs e)
{
e.Values[" My FormView Selected Value "] = MyFormView.DataKey.Value;
}
</code></pre>
<p><strong>Update:</strong>
Just found similar question, <a href="http://stackoverflow.com/questions/212257/listview-with-linq-datasource-insert-template">ListView with LINQ Datasource insert template</a></p>
|
Python: Testing for unicode, and converting to time() <p>Sometimes self.start is unicode:</p>
<p>eg.</p>
<pre><code>>>>self.start
u'07:30:00'
</code></pre>
<p>Which makes datetime.combine complain</p>
<pre><code>start = datetime.combine(self.job_record.date, self.start)
</code></pre>
<p>How does one:</p>
<ol>
<li>Test for unicode?</li>
<li>Convert from u'07:30:00' to datetime.time?</li>
</ol>
| <p>Checking for unicode:</p>
<pre><code>>>> import types
>>> type(u'07:30:00') is types.UnicodeType
True
>>> type('regular string') is types.UnicodeType
False
</code></pre>
<p>Converting strings to time:</p>
<pre><code>>>> import time
>>> time.strptime(u'07:30:00', '%H:%M:%S')
(1900, 1, 1, 7, 30, 0, 0, 1, -1)
</code></pre>
|
C# AssemblyFileVersion usage within a program <p>I'm working on a program, and I'm trying to display the assembly <em>FILE</em> version </p>
<pre><code> public static string Version
{
get
{
Assembly asm = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);
return String.Format("{0}.{1}", fvi.FileMajorPart, fvi.FileMinorPart);
}
}
</code></pre>
<p>At the moment, this only returns the first two version numbers in the "AssemblyVersion", not "AssemblyFileVersion." I'd really like to just reference the AssemblyFileVersion rather than store an internal variable called "Version" that I have to update both this and the assembly version...</p>
<pre><code>[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("3.5.0")]
</code></pre>
<p>That's my AssemblyFileVersion from AssemblyInfo.cs. I'd like to just reference the "3.5.x" part, not the "1.0.*" :/</p>
<p>Thanks,
Zack</p>
| <p>Use ProductMajorPart/ProductMinorPart instead of FileMajorPart/FileMinorPart :</p>
<pre><code> public static string Version
{
get
{
Assembly asm = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);
return String.Format("{0}.{1}", fvi.ProductMajorPart, fvi.ProductMinorPart);
}
}
</code></pre>
|
Adding to built-in ExcludeFromBuild ItemGroup with Web Deployment project <p>I've added a Web Deployment Project to my solution to create a clean deployment of my web application. This works mostly as expected... i.e. builds the source & then copies the files to be deployed to a /Release folder (and excludes things like source files and my .svn folders, etc).</p>
<p>But now I want to explicitly exclude some other files (for the sake of simplicity lets just say one file called somefile.txt). So, I add an item group to the wdproj file as follows:</p>
<pre><code><ItemGroup>
<ExcludeFromBuild Include="somefile.txt" />
</ItemGroup>
</code></pre>
<p>This does indeed exclude the specific file as requested, but now the files excluded by default are no longer excluded. Specifically, now all my svn files are in the Release folder & there's also a Source folder at the same level with all the source in it.</p>
<p>Basically, it seems that defining the ExcludeFromBuild item group is overwriting some set of built-in defaults, rather than adding to them.</p>
<p>Not exactly a show stopper, but not ideal... So, does anyone know how to simply add a file to the default ExcludeFromBuild group? Or is it a case of using the defaults Vs. excluding everything by hand Vs. deleting the files you don't after a default build?</p>
| <p>Well for anyone who comes looking, I thought I should answer my own question... I didn't find the exact solution I was looking for, so I just added everything I needed excluded manually to the ExcludeFromBuild ItemGroup (to mimic what the default options seemed to do & then also exclude my specific file). My ExcludeFromBuild list ended up looking like this:</p>
<pre><code><ItemGroup>
<ExcludeFromBuild Include="$(SourceWebPhysicalPath)\somefile.txt" />
<ExcludeFromBuild Include="$(SourceWebPhysicalPath)\obj\**\*.*" />
<ExcludeFromBuild Include="$(SourceWebPhysicalPath)\**\.svn\**\*.*" />
<ExcludeFromBuild Include="$(SourceWebPhysicalPath)\**\.svn\**\*" />
<ExcludeFromBuild Include="$(SourceWebPhysicalPath)\**\*.csproj" />
<ExcludeFromBuild Include="$(SourceWebPhysicalPath)\**\*.scc" />
<ExcludeFromBuild Include="$(SourceWebPhysicalPath)\**\*.user" />
<ExcludeFromBuild Include="$(SourceWebPhysicalPath)\**\*.vspscc" />
<ExcludeFromBuild Include="$(SourceWebPhysicalPath)\**\*.log" />
<ExcludeFromBuild Include="$(SourceWebPhysicalPath)\**\*.svclog" />
</ItemGroup>
</code></pre>
<p>Basically excludes all log files, user/project files, svn files, source safe files, etc plus the custom files I wanted to ignore in the first place.</p>
|
Bind GridView via jQuery ajax <p>I am new to jQuery, trying to populate a GridView or Telerik RadGrid using jQuery. Not sure how to go about it and unable to find any examples. Any help is appreciated. Thanks.</p>
<p>Essentially I am trying to display a modal window with a textbox and button. The user enters a search criteria presses the button and a gridview in the same modal window is populated with the results.</p>
<p>The user than selects records in the grid presses another button and the selected users are inserted into the database table, modal window is closed and a grid on the parent page is refreshed showing the new added users.</p>
<pre><code><input type="button" id="btnAddNewUserj" value="Add New User" />
$(document).ready(function() {
$("#btnAddNewUserj")
.click(function() { ShowNewUserDialog(); return false });
$("#btnSearch")
.click(function() { FindUsers(); return false });
});
function ShowNewUserDialog() {
$("#newuserDialog").dialog({ modal: true, bgiframe: true }).dialog("open");
}
function FindUsers() {
// HOW TO DO THIS?
// Show selectable list of users from the database in grid.
}
<div id="newuserDialog" title="Add New User" style="display:none;">
<div>
<input id="txtSearchFor" type="text" />&nbsp;&nbsp;
<input id="btnSearch" type="button" value="Search" class="Button" /></div>
<p> DISPLAY RESULTS HERE </p>
<div style="margin:10px 6px;">
<input type="button" id="btnjAdd" value="Add" class="Button" />&nbsp;&nbsp;
<input type="button" id="btnjCancel" value="Cancel" class="Button" />
</div>
</div>
</code></pre>
| <p>A couple of thoughts here. You cannot populate a GridView or Telerik Grid using jQuery. jQuery is a client side technology and those two grids are server side. </p>
<p>You can use jQuery to hit a web service and build out and HTML table with the results (which is basically what a GridView does). </p>
<p>I'm guessing however, that you would be better served just using native GridView databinding. You can use a .Net UpdatePanel around the grid if you want to prevent full post backs. </p>
|
How do I time a Cocoa app? <p>What is an easy way to time a Cocoa application? (Alternatively, any good way to measure performance would suffice).</p>
<p>(I have two different frameworks and would like to compare their performances over some fixed input data)</p>
| <p>Instruments will keep a clock for you, although you may find that the frameworks' difference is within the margin of how quickly you can start the app working on the data.</p>
<p>You can use Shark and the CHUD framework to do a better job of this. The framework lets you programmatically start and stop profiling; you'll start at the beginning of the work and end at the end of the work, and then have a nice Shark document to show for it. The Shark manual has more details.</p>
|
Best way to store configuration settings for T4 <p>I need to create some files using Visual Studio T4 (templating). What is the best way to import some configuration settings into multiple .tt files and have it accessible in the templating code portion.</p>
| <p>The simplest way to store configuration is by placing it as code in a shared .tt file, which you can include from multiple templates (i.e. if you need a connection string, make it a constant in a class feature block). However, if that is not an option and you need to access settings in .config file, I agree with John's suggestion.</p>
|
DIV with Image and Text <p>I want to create a DIV with a header of 6px height and inside the div body, I want to align an Image and Text next to each other. The height of the DIV body should be fixed.</p>
| <p>Here's a very simple example of how to do what you want (using inline styles):</p>
<pre><code><div>
<div style="height:6px;width:500px;background-color:#3399CC;"></div>
<div style="clear:both"/>
<div style="float:left"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></div>
<div style="float:left">Your Text Here</div>
</div>
<div style="clear:both"/>
</code></pre>
<p>You can test this code and try editing it in real time here: <a href="http://htmledit.squarefree.com/" rel="nofollow">http://htmledit.squarefree.com/.</a></p>
|
Java Socket Programming <h2>Java Socket Program did not work for WAN</h2>
<p>I have written a TCP IP socket program which works fine in my LAN.
One of my friend is at bangalore He ran the server and I ran the
client with the host name of my friend's IP. In this case my
socket program did not work.</p>
| <p>You said that your program is attempting to connect to host 192.168.1.107 port 46216.</p>
<p>192 prefix specifies it is a class C address and is private. Making your program connect to that will force it to remain on the local network searching for that node. You will need to find the IP address of your router (you can use <a href="http://whatismyip.org/" rel="nofollow">http://whatismyip.org/</a> to find this out). Then go into your router settings and forward port 46216 to 192.168.1.107 (your node), or even better, your MAC address which is not subject to change (in case your router is running DHCP).</p>
<p>on a side note, it isn't good to hardcode IP addresses. Simply use a textfield to avoid having to redistribute the client when your IP is changed, as it is likely you have a dynamic IP from your ISP.</p>
|
Zend Framework - Static form elements <p>I have got a form which a user can use to create a new store and to edit an existing one. When this form is being used to edit a store there are certain fields that I want the user to see but not edit eg. store_id. I have explored the different Zend_Form_Elements hoping to find some kind of static element but with no luck. </p>
<p>So my question is, how do I display information using Zend_Form that a user can't edit?</p>
<p>Thanks.</p>
| <p><code>readonly</code> alone is not enough, because users will still be able to edit it if they really want. You should use <code>$element->setIgnore(true)</code> that will ensure that <code>Zend_Form_Element</code> won't try to populate the element from POST/GET, and I'd double check that also. You have to make sure the values you are getting into the databases can never contain this element.</p>
<p>Finally, if you would like your element to be displayed in a different way than just with <code>readonly</code>, you can do that by changing the element decorators.</p>
|
How to disable tabbing in a tab panel in gwt <p>I have a tab panel in the gwt. I want allow the user to select the tab only by mouse. For this one I have disable the tabindex for all the tab in my tabpanle. I tried with this code:</p>
<pre><code>DOM.setElementAttribute(cdrMeseTabPanel.getElement(), "tabIndex", "-1" );
</code></pre>
<p>but it is not working.</p>
<p>Any ideas please?</p>
| <p>Try setting the tabIndex to an empty property:</p>
<pre><code>DOM.setElementAttribute(cdrMeseTabPanel.getElement(), "tabIndex", "" );
</code></pre>
|
How do I add an object with the entity framework when it has a foreign key object that already exists <p>I have 2 tables:</p>
<pre><code>tblAuthors
- id
- username
tblPosts
- id
- authorid
</code></pre>
<p>So if I create a new Post</p>
<pre><code>var post = new Post { Id=Guid.NewId(), Author=new Author { UserName="username", Id="id in database } };
</code></pre>
<p>The author of the post is already in the database, but the post itself is not...</p>
<p>So I want to do:</p>
<pre><code>entities.AddToPosts(obj);
</code></pre>
<p>but it tries to add the Author and the Post... is there a way to have it Save the author and add the post? Or just ignore the Author completely?</p>
<p>I have both the Post and the Author as my own POCO business objects, that were pulled from the database and then converted to my business layer. I don't want to have to re-pull them because I could have modified either in my business layer. So I just want to attach the objects.</p>
<p>I don't want to keep the data objects around, I pull them out and convert them to business objects and then don't touch them again until I want to push back to the database and I convert the business objects to data objects.</p>
| <p>Shouldn't you first retrieve the Author record from the database to be able to set it in the Post object?</p>
<p>So you would you get:</p>
<pre><code>var author = Author.Select(a => a.Id).FirstOrDefault();
var post = new Post { Id=Guid.NewId(), Author=author };
entities.AddToPosts(obj);
</code></pre>
<p>Maybe you could use the <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attach.aspx" rel="nofollow">Attach</a> and <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attachto.aspx" rel="nofollow">AttachTo</a> ObjectContext to attach the object, but is not mentioned in the MSDN library whether a query to the database is executed. With some tracing you could check whether a database query occurs.</p>
|
Is there a Python library to interact with Genesys? <p>I work within a contact center and we use Genesys with an Alcatel PBX. We currently use .NET libraries to wrap the DLL's provided to us, but I'm wondering if there are any Python libraries out there before I attempt to write my own?</p>
<p>Thanks</p>
<p>Edit:</p>
<p>Jython with the Java SDK library works a treat.</p>
| <p>If they are providing a C library, you can use ctypes to interact with it.</p>
|
java tcp ip socket programming regardless of proxy type <p>How to write TCP IP socket programming in java. If the client is behind any type of proxy (may be http or socks or no proxy).</p>
<p>Thanks
Bapi</p>
| <p>When I faced such kind of problem I had to code myself http layer (over HTTP CONNECT) and used existing (in standard library) socks layer. However the main problem is to get the proxy settings. As far as I was doing it for a Web Start application, I could use default browser settings.</p>
|
Subtraction without minus sign <p>How can i do subtraction of integers in C without using either the unary or binary '-' operator?</p>
<p>Or can we do the same for other data types like float/double?</p>
| <p>have a look at the <a href="http://en.wikipedia.org/wiki/Two%27s%5Fcomplement">two's complement</a></p>
|
Database deploy (vsdbcmd.exe): DatabaseName and DefaultDataPath are ignored? <p>Visual Studio database edition comes with a tool, vsdbcmd.exe, that should allow someone to deploy a .dbschema file (which is generated by the database project on build) to a database. It does this by first building the script, then executing it:</p>
<blockquote>
<p>vsdbcmd.exe /a:Deploy /cs:"Data Source=(local);Integrated Security=True;Pooling=False" /dsp:Sql /dd /model:"..\Database.dbschema" /p:TargetDatabase=TargetDB /manifest:"..\Database.deploymanifest"</p>
</blockquote>
<p>I would expect that it can deploy the script to a different database server without problems. However, the complete path to the actual .mdf file is encoded in the script, along with some other references to the original databse. Either there isn't an option to control this, or I can't find it.</p>
<p>Is anyone using this? How do you deploy? Should I have used a different kind of database project (I remember having the choice way back when between "Database project" and "Server project", but I don't know whether that matters)?</p>
<p><strong>EDIT</strong></p>
<p>I can override the .sqlcmdvars just fine, but this does not solve the problem. This is an extract from the generated .sql file using a command like above:</p>
<pre><code>GO
:setvar DatabaseName "TargetDB"
:setvar DefaultDataPath "C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\"
</code></pre>
<p>So there is the "targetdb" target database gets recorded correctly. But, a few lines further:</p>
<pre><code>CREATE DATABASE [$(DatabaseName)]
ON
PRIMARY(NAME = [Original], FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\Original.mdf', SIZE = 3072 KB, MAXSIZE = UNLIMITED, FILEGROWTH = 1024 KB)
LOG ON (NAME = [Original_log], FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\Original_log.ldf', SIZE = 1024 KB, MAXSIZE = 2097152 MB, FILEGROWTH = 10 %)
</code></pre>
<p>where Original.mdf is the name of the original database (i.e. the db where we deploy during development, and that is set in the project properties of the database project). This is where the deployment fails, either because that exact path may be different on the target machine, or on my machine because that db already exists.</p>
<p>These values just seem hardcoded in the generated script.</p>
| <p>This can be (is) caused when doing a <em>Database Schema Synchronization -> Database Project</em>. (My environment is VS2010 Enterprise RTM).</p>
<p>The generated ALTER DATABASE statements are generated to mirror the <em>source</em> database without taking any substitution values into account (it will also include initial database sizes, etc). The problem does not appear on an Initial Database Import.</p>
<p>Edit the files found under...</p>
<p><strong>Schema Objects\Database Level Objects\Storage\Files</strong></p>
<p>...and fix them to contain the correct <code>$(DefaultDataPath)$(DatabaseName).mdf</code>/<code>$(DefaultLogPath)$(DatabaseName)_log.ldf</code> values -- or other -- as appropriate. (Now mark them as "Skip" in your Schema Compare :-P)</p>
<p>With the above "correction" keeping the values external will once again work and is the preferred method of managing such properties.</p>
<p>Happy coding.</p>
|
Control access to WebDav/Apache using Python <p>I want to give users access to WebDav using Apache, but I want to autenticate them first and give each user access to a specific folder. All authentication must be done against a Django-based database. I can get the Django-authentication working myself, but I need help with the part where I authenticate each user and provide them with a dedicated webdav user-specific area.</p>
<p>Any hints?</p>
| <p>First, for you other readers, my authentication was done against Django using a <a href="http://www.davidfischer.name/2009/10/django-authentication-and-mod_wsgi/" rel="nofollow">WSGI authentication script</a>.</p>
<p>Then, there's the meat of the question, giving each Django user, in this case, their own WebDav dir separated from other users. Assuming the following WebDAV setup in the Apache virtual sites configuration (customarily in <em>/etc/apache2/sites-enabled/</em>)</p>
<pre><code><Directory /webdav/root/on/server>
DAV On
# No .htaccess allowed
AllowOverride None
Options Indexes
AuthType Basic
AuthName "Login to your webdav area"
Require valid-user
AuthBasicProvider wsgi
WSGIAuthUserScript /where/is/the/authentication-script.wsgi
</Directory>
</code></pre>
<p>Note how there's no public address for WebDav set up yet. This, and the user area thing, is fixed in two lines in the same config file (put these after the ending clause):</p>
<pre><code>RewriteEngine On
RewriteRule ^/webdav-url/(.*?)$ /webdav/root/on/server/%{LA-U:REMOTE_USER}/$1
</code></pre>
<p>Now, webdav is accessed on <a href="http://my-server.com/webdav-url/" rel="nofollow">http://my-server.com/webdav-url/</a> The user gets a login prompt and will then land in a subdirectory to the webdav root, having the same name as their username. <em>LA-U:</em> makes Apache "look ahead" and let the user sign in <em>before</em> determining the mounting path, which is crucial since that path depends on the user name. Without some rewrite-rule there will be no URL, and the user won't get a login prompt. In other words, LA-U avoids a catch-22 for this type of login handling.</p>
<p><strong>Precautions</strong>: requires mod_rewrite to be enabled, and user names must be valid as dir names without any modification. Also, the user dirs won't be created automatically by these commands, so their existence must be assured in some other way.</p>
|
Is it possible to move components around the screen using the standard android apis? <p>I would like to produce an <code>android</code> user interface which allows the user to move added <code>components</code>/<code>widgets</code> around the screen by selecting them and then dragging them around.</p>
<p>Is this possible using the standard android apis?</p>
| <p>Yes. It depends what you are trying to achieve.</p>
<p>It can be done <em>using</em> the standard APIs, but this functionality is not <em>part of</em> the standard APIs. That is, there is no <code>widget.DragOverHere()</code> method unless you write one.</p>
<p>That said, it would not be terribly complicated to do. At a minimum, you would need to write a custom subclass of View and implement two methods: <code>onDraw(Canvas c)</code> and <code>onTouch(MotionEvent e)</code>. A rough sketch:</p>
<pre><code>class MyView extends View {
int x, y; //the x-y coordinates of the icon (top-left corner)
Bitmap bitmap; //the icon you are dragging around
onDraw(Canvas c) {
canvas.drawBitmap(x, y, bitmap);
}
onTouch(MotionEvent e) {
switch(e.getAction()) {
case MotionEvent.ACTION_DOWN:
//maybe use a different bitmap to indicate 'selected'
break;
case MotionEvent.ACTION_MOVE:
x = (int)e.getX();
y = (int)e.getY();
break;
case MotionEvent.ACTION_UP:
//switch back to 'unselected' bitmap
break;
}
invalidate(); //redraw the view
}
}
</code></pre>
|
How can I write a program which can test throughput of disk? <p>How can I write a program which can test throughput of disk in Windows systems using c++?</p>
<p>What's the mainly steps and APIs that I can use to programming?</p>
| <p>In outline:</p>
<ul>
<li>write a known (large) amount of data to disk ( see write() )</li>
<li>start clock (see time() or clock() )</li>
<li>read data from disk (see read() )</li>
<li>stop clock (see above)</li>
<li>report results (see cout)</li>
</ul>
|
Image field on ReportViewer <p>Anybody tried to display image field (image/byte array) data type on reportviewer.</p>
<p>Regards,
Peter</p>
| <p>Yes. ReportViewer requires a Base64 Image encoding in order to display the image properly.</p>
<p>If your image is in a Byte array, it will need to be converted to Base64:</p>
<pre><code> Public Function ConvertImageToBase64String(ByVal img As Image) As String
Dim output As String = ""
Dim outputArray() As Byte
Dim stream As New MemoryStream
img.Save(stream, Drawing.Imaging.ImageFormat.Bmp)
outputArray = stream.ToArray()
stream.Close()
output = Convert.ToBase64String(outputArray)
Return output
End Function
</code></pre>
|
VS: Automatic "ArgumentNull' check? <p>It's often the case when I need to check a method's arguments for not being null, something like:</p>
<pre><code>public static bool operator <=
(ApplicationVersion i_app1, ApplicationVersion i_app2)
{
if (i_app1 == null) throw new ArgumentNullException("i_app1");
if (i_app2 == null) throw new ArgumentNullException("i_app2");
[...]
}
</code></pre>
<p>Is there a way to do this (semi)automatically, like Code snippets? Autocomplete? Resharper?</p>
| <p>Resharper has this feature. If you have cursor over parameter name - say i_app1 and hit Alt-Enter - it offers the option to check for null.</p>
|
Creating navigation links in Struts 2 <p>Is there some way to replicate rails' "link-to-unless-current"?</p>
<p>Ie. if i have a list of links in my navigation, and I want to mark the current page with a different css style (or even have it be plain text, not a link)?</p>
<p>Now I just made a method in my action-class (getPage()) which returns a name that I assign for each action, and test for that when building my navigation... Works but not pretty, and I have to manually set the page name (couldn't struts somehow automaticalyy get it from the context).</p>
<p>Using Struts 2, Tiles, JSP + Struts taglibs.</p>
| <p>To get the current url you you can use the Url tag without any params, actions, etc:</p>
<pre><code><s:url var="currenturl" includeParams="get" escapeAmp="false"/>
</code></pre>
<p>Then assuming you construct your navigation Url something like:</p>
<pre><code><s:url var="url" action="someAction" escapeAmp="false">
<s:param name="id" value="id"/>
</s:url>
</code></pre>
<p>Then you can then use a normal if tag to test whether the current url matches on that you've constructed.</p>
<pre><code><s:if test="#url eq #currenturl">
</s:if>
</code></pre>
<p>For example, to change the class, you can do a conditional inline to your anchor definition:</p>
<pre><code><a href="<s:property value="#url"/>" <s:if test="#url eq #currenturl">class="current"</s:if>>XXX</a>
</code></pre>
<p>Use the includeParams="get" if the parameters in your URL are meaningful for navigation otherwise exclude that and use an if like:</p>
<pre><code><s:if test="#url.startsWith(#currenturl)">
</code></pre>
|
Database Replication MSSQL 2000 to 2005 <p>I am trying to replicate a database from SQL server 2000 to 2005 they are located on two different servers both running Windows Server 2003 R2. Im am using SERVER1(SQL2000) as the Transactional publisher and distributor and SERVER2(SQL2005) is the subscriber. I can set up the publication and subscription but when I try to syncronize them I get the following error:</p>
<p>SERVER1-TestReplication-TestReplication-IBSCNVII-ReplicationCNVII_2-99956FE2-402A-48D5-B801-2CBADF12BD3E has server access (reason: Could not obtain information about Windows NT group/user '', error code 0x5. [SQLSTATE 42000] (Error 15404)).</p>
<p>Do I need to add my domain user to a certain user group on server? Any ideas?</p>
| <p>0x5 means "access denied" and that you're not allowed to query active directory user information. Likely, the sql server service account does not have proper domain privileges to perform look ups in AD. This could be caused by an account password simply being expired and therefore not enabling SQL to validate against AD or some other issue like services running as local system and not a domain account.</p>
<p>I would recommend confirming that both SQL servers are using a valid domain account and not something like local system. Then check that that domain account isn't locked up or expired.</p>
|
How can I import only a couple of functions from a Ruby module? <p>Suppose I have a module with the methods : function1,function2,function3. I want to import function1 and function2 but not function3. Is there a way to do this in ruby?</p>
| <p>Not sure if there is a clean way to just add the methods you want, but you can remove the methods that you don't want by using <code>undef_method</code>.</p>
<pre><code>module Foo
def function1
end
def function2
end
def function3
end
end
module MiniFoo
include Foo
not_wanted_methods = Foo.instance_methods - %w(function1 function2)
not_wanted_methods.each {|m| undef_method m}
end
class Whatever
include MiniFoo
end
</code></pre>
|
ASP.net weekly schedule control <p>Can anyone recommend a free asp.net control that I can use for the following:</p>
<ul>
<li>Weekdays Monday-Saturday along the top row</li>
<li>Time of day along left hand side</li>
<li>Template fields for the actual data</li>
<li>Databindable</li>
<li>Cells span the rows based on the start time and end time</li>
</ul>
<p>Here is a control that I found that is pretty good, but I am trying to find alternatives:
<a href="http://www.codeproject.com/KB/custom-controls/schedule.aspx" rel="nofollow">Databound Schedule controls</a></p>
| <p><a href="http://www.daypilot.org/">DayPilot</a> is a pretty good general purpose calendaring/schedule control.</p>
<p>The full version is not free, but there is a "lite" version available which is not only free but open source!</p>
|
NHibernate Error reporting advice <p>This is not so much a problem as advice on best practice really. I am writing an ASP.Net MVC application, and in my DAL i am using NHibernate, but what do you do if an exception is thrown in your DAL?</p>
<p>Do you catch the exception in the DAL, log the error and then re-throw the exception?
Do you not even attempt to catch exeptions at all and use the Application_Error() method in the global.asax as a generic catch all?
Do you catch the exception log it and return a bool to the controller indicating a success or failure, or do you do something completly different?</p>
<p>Leading on from this how then do you handle informing the users? Do you show a generic "Error Occured - please try again" type page or do you show a more informative error?</p>
| <p>This is exactly one of those 'it depends' questions. This is what I do:</p>
<ul>
<li>Handle all exceptions in Application_Error (or similar sink-like location)</li>
<li>If the exception is base for business logic - say cannot have duplicates, just catch it and act upon it.</li>
<li>If it is an infrastructure exception and there is a good chance you can fix it by retrying - handle it in DAL.</li>
<li>Propagating specific exception info to user has hardly any benefit because usually the user cannot do anything about it anyway. So a generic error message usually makes do.</li>
<li>All unexpected and selected expected exceptions need to be logged with as much info as possible. It is also advisable that you get email with the exception info.</li>
</ul>
<p>Now specifically to NHibernate - if NH throws an exception it is advised that you close and discard the currently active ISession and just fail. Because the session might be in an unknown/inconsistent state and trying to resurrect it can do more harm than good.</p>
<p>Obviously depending on scale and type of your app and number of various systems/programmers/etc. involved you really might to handle the logging yourself.</p>
|
using mouseover/mouseout in gridview with alternating rows <p>I currently have a gridview with alternating colors, Silver and White, with a blue header (not selectable, obviously). Initially, I had this onmouseover/onmouseout thing working but for some reason, yesterday morning it failed to work, and all day yesterday, I have been struggling, googling for answers and coming up short. Here is the databound function:</p>
<pre><code>protected void GridView_OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + j.ToString() + "')");
e.Row.Attributes.Add("onmouseover", "HighlightOn(this)");
e.Row.Attributes.Add("onmouseout", "HighlightOff(this)");
}
}
</code></pre>
<p>And here is the onmouseover and onmouse out functions:</p>
<pre><code>function HighlightOn(rowid)
{
if (document.getElementById(gridViewCtlId).disabled == false)
{
if ($(selectedIndex).val() != rowid.rowIndex)
{
rowid.style.backgroundColor = '#8FBAEF';
}
}
}
function HighlightOff(rowid)
{
if (document.getElementById(gridViewCtlId).disabled == false)
{
if ($(selectedIndex).val() != rowid.rowIndex)
{
var modIdx = rowid.rowIndex % 2;
if (modIdx == 0)
{
rowid.style.backgroundColor = 'Silver';
}
else
{
rowid.style.backgroundColor = 'White';
}
}
}
}
</code></pre>
<p>selectedIndex is being set by this:</p>
<pre><code>function getSelectedRow(rowIdx)
{
getGridViewControl(rowIdx);
if (gridViewCtl != null)
{
$(selectedIndex).val(rowIdx);
return gridViewCtl.rows[rowIdx];
}
return null;
}
</code></pre>
<p>This function just gets the row by giving it the id of the row in a gridview (used for the onclick event to change the color of the row).</p>
<p>The problem is this: When I click on a row, it becomes highlighted. When I then move the mouse, the other rows become somewhat highlighted, which is correct, but when I click on another row, and move the mouse out of that row, it becomes de-highlighted. And when i click on it again, does it stay highlighted. selectedIndex is just a hidden field on the page. Does anyone see why this doesn't function properly? Thanks.</p>
| <p>First of all you can solve this problem with some CSS (not supported in IE6):</p>
<pre><code>
tbody tr:hover td {
background-color: orange;
}
</code></pre>
<p>If I were to use JavaScript I would use an <a href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript" rel="nofollow">unobtrusive technique</a>. Then you can skip the C#. Here is how you can do it:</p>
<pre><code>
$(function () {
$("tbody tr")
.mouseenter(function () {
$(this).addClass("Highlight");
})
.mouseleave(function () {
$(this).removeClass("Highlight");
});
});
</code></pre>
<p>You need some CSS for this to work:</p>
<pre><code>
tbody tr.Highlight td {
background-color: orange;
}
</code></pre>
|
eclipse indexer problem with cmake project <p>I've created the eclipse project with cmake. I use vtk with qt. Dir structure is as follows:</p>
<pre><code>parent_dir:
source - source.h, source.cpp
build - this is where the .project resides
</code></pre>
<p>I've fired up the eclipse with workspace dir <em>/path/parent</em> .</p>
<p>I have followed the instructions described in
<a href="http://www.cmake.org/Wiki/Eclipse%5FCDT4%5FGenerator" rel="nofollow">http://www.cmake.org/Wiki/Eclipse_CDT4_Generator</a> .
Everything builds fine, but navigation is not working. That is, the eclipse gives me the warning that the <em>source.h</em> is not indexed yet. </p>
<p>Furthermore, autocompletion doesn't work with qt and vtk related classes. I had checked with Project|Properties, where the qt and vtk includes are included. What am I doing wrong? I would really like to have autocompletion nd navigation in eclipse working with my project. I'm using eclipse ganymede on ubuntu 8.04 64-bit.</p>
<p>thx in advance</p>
| <p>According to the Wiki, you should have your build tree outside the source tree.</p>
<blockquote>
<p>This linked resource isn't created if
the build directory is a subdirectory
of the source directory because
Eclipse doesn't allow to load projects
which have linked resources pointing
to a parent directory. So we recommend
to create your build directories not
as children, but as siblings to the
source directory.</p>
</blockquote>
<p>You'll need to do something like this:</p>
<pre><code>mkdir /home/user/parent_dir_build
cd /home/user/parent_dir_build
cmake /home/user/parent_dir
</code></pre>
|
Using google analytics to track multiple companies in a single website <p>I've been tasked with implementing Google Analytics inside our (ASP.NET) application. Here is the scenario:</p>
<ol>
<li>A single web-site on one domain</li>
<li>Multiple companies all use this single website</li>
<li>Statistics need to be collected on a per company basis as well as the whole</li>
<li>Report access needs to be allocated on a per company basis or for all (Would also be nice if you could assign a range of reports to a specific user)</li>
</ol>
<p>From the documentation available, I'm not sure whether to use:</p>
<p>Filters (Apply filter on virtual url to segment companies)</p>
<pre><code><script type="text/javascript">
var pageTracker = _gat._getTracker("UA-12345-1");
pageTracker._initData();
pageTracker._trackPageview("/site.com/companyName/var1/var2");
</script>
</code></pre>
<p>Or Segments</p>
<pre><code><script type="text/javascript">
var pageTracker = _gat._getTracker("UA-12345-1");
pageTracker._initData();
pageTracker._trackPageview();
pageTracker._setVar("companyName");
pageTracker._setVar("var1");
pageTracker._setVar("var2");
</script>
</code></pre>
| <p>Virtual addresses work fine with Google Analytics. You will see the content page there giving you a list like</p>
<p>/companyA/welcome.aspx<br />
/companyA/aboutus.aspx<br />
/companyC/orderstatus.aspx<br />
/companyB/welcome.aspx<br />
/companyA/confirmorder.aspx<br />
/companyC/welcome.aspx </p>
<p>You can then filter the list by company name, and it will just show "<em>welcome" or "companyA</em>" It will also show you the graph for content matching the query.</p>
<p>The columns there will show; Page, Pageviews, Unique Pageviews, Avg. Time on Page, Bounce Rate, % Exit, $ Index. </p>
<p>Hope this helps.</p>
|
Union two or more tables, when you don't know the number of tables you are merging <p>I am working with MS SQL 2005.
I have defined a tree structure as:</p>
<pre><code>1
|\
2 3
/|\
4 5 6
</code></pre>
<p>I have made a SQL-function Subs(id), that gets the id, and returns the subtree table.
So, Subs(3) will return 4 rows with 3,4,5,6, while Subs(2) will return one row, with 2.</p>
<p>I have a select statement that returns the above Ids (joining this tree with other tables)</p>
<p>I want after the select statement that returns the above Ids<br>
(which will result in a table with for example 2 rows:)</p>
<pre><code>2
3
</code></pre>
<p>to be able to run the Subs-function as <br></p>
<pre><code>Subs(2)
union
Subs(3).
</code></pre>
<p>(The result should be the rows with id 2,3,4,5,6)</p>
<p>The problem is that I don't know how to pass the arguments and I don't know how to make the dynamic use of union. </p>
<p>Is it possible to solve this at this level, or should I take it to the upper-level (C#)?</p>
| <p>I do not think you need UNION here, with SQL Server 2005 you can achieve the desired result using CROSS APPLY:</p>
<pre><code>select
f.*
from
resultsTable rt
cross apply dbo.subs(rt.ID) f
</code></pre>
<p>That is assuming that the resultTable is the one that stores the results of your first query, and the name of the field is ID</p>
|
variable database name <p>Is there any way in MySQL to put the name of the database into a variable?
For example, when I have a database called 'db1', can I do something like this:</p>
<pre><code>set @db= 'db1';
select * from @db.mytable;
</code></pre>
<p>EDIT: There is another example of what I want to do:</p>
<pre><code>set @dbfrom= 'db1';
set @dbto= 'db2';
insert into @dbto.mytable (col1,col2,col3) select col2,col1,col3 from @dbfrom.mytable;
</code></pre>
| <p>With considerable effort, yes.</p>
<pre><code>SET @db = 'db1';
SET @q = CONCAT('SELECT * FROM ', @db, '.mycol');
PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code></pre>
|
What's the significance of Oct 12 1999? <p>In the SignOut method of <a href="http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.aspx">System.Web.Security.FormsAuthentication</a>, the ASP.NET team chose to expire the FormsAuth cookie by setting the expiration date to "Oct 12 1999".</p>
<pre><code>HttpCookie cookie = new HttpCookie(FormsCookieName, str);
cookie.HttpOnly = true;
cookie.Path = _FormsCookiePath;
cookie.Expires = new DateTime(0x7cf, 10, 12);
</code></pre>
<p>What's the significance of October 12th, 1999? Is it an inside joke, or is there some valid reason to set your cookie expiration to that particular date?</p>
<p><strong>Edit:</strong>
The theories below are interesting, but they are just guesses. Since <a href="http://stackoverflow.com/users/598/haacked">Phil</a>, <a href="http://stackoverflow.com/users/6380/scott-hanselman">Scott</a>, and other members of the ASP.NET team are on StackOverflow, I thought it would be fun to offer a <strong>bounty</strong>. Hopefully someone can track down the original developer and get an authoritative answer. </p>
<p><strong>Awarded:</strong>
To Scott Hanselman for escalating this one all the way to <a href="http://weblogs.asp.net/scottgu/about.aspx">ScottGu</a>. I was really hoping for some sort of super-secret, Illuminati-esque meaning, but looks like it was just the old "one year ago" trick.</p>
| <p>Elementary my dear Watson:</p>
<ul>
<li>Oct 12 1999 is exactly 80 days before 1-1 2000. </li>
<li>For some people the year 2000 was the end of the world</li>
<li>As we know, <a href="http://en.wikipedia.org/wiki/Around%5Fthe%5FWorld%5Fin%5FEighty%5FDays">it takes 80 days to go around the world</a>.</li>
<li>So oct 12 1999 was the last possible day to go around the world.</li>
<li>As we know internet is wrapped around the world. </li>
<li>So packets (and also cookies) travel around the world.</li>
<li>The expiration date of Oct 12 1999 is the symbolic last day a packet could be send.</li>
<li>There is no need to send it later than this date.</li>
<li>So this is the symbolic date for do not expire.</li>
</ul>
|
Is it OK to return a const reference to a private member? <p>I need to implement read-only access to a private member container. If I return a constant reference is it possible to const_cast it and obtain a full access to the member? What's the technique to be used?</p>
<p>Thanks.</p>
| <h2>Is it safe to return a const reference to a private member</h2>
<p>Yes as long as the lifetime of the reference does not exceed the lifetime of the object which returned it. If you must expose the private member you do not want modified, this is a good way to do so. It's not foolproof but it's one of the better ways to do so in C++</p>
<h2>Is it possible to use const_cast to actually mess around with member</h2>
<p>Yes and there is nothing you can do to prevent this. There is no way to prevent someone from casting away const in C++ at any time. It's a limitation / feature of C++. </p>
<p>In general though, you should flag every use of const_cast as a bug unless it contains a sufficiently detailed comment as to why it's necessary. </p>
|
Which is the best managed .NET e-mail component with support for S/MIME? <p>I need a replacement for <code>System.Net.Mail.MailMessage</code> that is able to send signed and/or encrypted e-mails. </p>
<p>Is there an open source library covering that? </p>
<p>Or do you have some experiences with some of those:</p>
<ul>
<li><a href="http://www.chilkatsoft.com/mime-dotnet.asp" rel="nofollow">Chilkat Mail</a></li>
<li><a href="http://www.quicksoftcorp.com/emdotnet/" rel="nofollow">Easymail</a></li>
<li><p><a href="http://www.dart.com/ptmlnet.aspx?source=adwords&gclid=CO7lrbCpzZkCFQMEZgody0ZKtw" rel="nofollow">Dart Mail for .NET</a></p></li>
<li><p>You got more?</p></li>
</ul>
| <p>It seems like you <em>can</em> in fact send S/MIME encrypted emails using the BCL of .NET. It requires a bit of a hack (not too bad however), but you could wrap the solution easy enough... See <a href="http://social.microsoft.com/Forums/en-US/netfxnetcom/thread/74e4711e-1f66-43a7-9e3b-bc9cfbcd1b73/" rel="nofollow">this MSDN forum thread</a> and possibly also <a href="http://social.msdn.microsoft.com/Forums/en-US/ncl/thread/ca93b37d-b8ad-4793-96a5-46d663c6cfad" rel="nofollow">this one</a>. Note that an example is additionally provided for <a href="http://www.rebex.net/secure-mail.net/" rel="nofollow">Rebex Secure Mail</a>, a commercial product, if you're having no luck with the BCL solution. Saying that, I would definitely recommend using the solution provided in the System.Net namespace if at all possible, despite requiring a bit of custom configuration.</p>
|
Roles for white-label service access <p>Okay,</p>
<p>I know I'm doing something wrong - but can't figure out a better way.
I am developing a website which is going to allow users to setup their own mini-websites.</p>
<p>Something like Ning.
Also, I have only 1 basic login and access to each mini website is provided (right now) via roles.</p>
<p>So the way I am doing this right now is:</p>
<p>Everytime a new mini website is created - say blah, I create 2 roles in my application.
<strong>blah_users</strong> and <strong>blah_admin</strong></p>
<p>The user creating the mini website is given the role - blah_admin and every other user wanting to join this mini website (or network) is given the role - blah_user.</p>
<p>Anyone can view data from any website. However to add data, one must be a member of that mini site (must have the blah_user role assigned)</p>
<p>The problem that I am facing is that by doing a role based system, I'm having to do loads of stuff manually. Asp.Net 2 controls which work on the User.IsAunthenticated property are basically useless to me now because along with the IsAuthenticated property, I must also check if the user has the proper role.</p>
<p>I'm guessing there is a better way to architect the system but I am not sure how.
Any ideas?</p>
<p>This website is being developed in ASP.Net 2 on IIS 6.
Thanks a tonne!</p>
| <p>I afraid standard roles-related stuff of ASP.NET is not what you need. You can try to change authentication module so it will:</p>
<ol>
<li>Log you in with cookie.</li>
<li>Determine what roles does your visitor have. Perhaps you will use some special table that corresponds user and site.</li>
<li>Make custom principal with user roles enumerated and assign Identity and Principal to the current request.</li>
</ol>
<p>I also don't think that making special roles for each site is good idea. When you would have hundred sites, you would also have two hundred roles. Pretty unmanageable, I afraid. </p>
<p>When we were solving similar task, we were just not using standard controls. We had single set of roles used on all sites. Membership of concrete user is determined according to current site and his relations to this site. </p>
<p>Addition: Another possibility to investigate is Application that exists in ASP.NET authentication system. Maybe it's possible to isolate each subsite into separate application?</p>
<p><strong>Update:</strong> Method that works for our application.</p>
<ol>
<li><p>Do not make a lot of cloned roles. Use only two: users and admin. If your sites are public then "users" role could be just global - user on one site doesn't differ from user on another site. If "users" and "everyone" are different roles, then of course "users" should also be bound to a site.</p></li>
<li><p>Use standard ASP.NET Membership users, but do not use standard role mechanism. </p></li>
<li><p>Make a mechanism for storing relation between site and user. It could be simple table that holds site id, user is and role.</p></li>
<li><p>What you have to override is IsInRole method. (Method**s** to be exact, i'll cover it later). This method is in IPrinciple interface, so you have to make your own principal object. It's quite simple. </p>
<ol>
<li>Method IsInRole of this type should look take current site (from HttpRequest) look into the site-user table and get roles</li>
</ol></li>
<li><p>Then you have to associate your principal with a request. Do it in PostAuthenticateRequest event.</p></li>
<li><p>There is also RoleProvider. Honestly I'm not sure when is it used, but it also have IsInRole method. We can override it in the same way. But other methods of this provider are harder. For example AddUsersToRoles. It accepts array of user names and roles, but to what context (site) should it be added? To current? Not sure, because I don't know when this method is called. So it requires some experiments. I see (Reflector helps) that RopePrincipal by itself uses RoleProvider to fetch list of roles, so maybe it's implement only RoleProvider, using standard principal. For our application this is not a case, so I can't say what problems could be hidden here.</p></li>
</ol>
|
Is there an un-buffered I/O in Windows system? <p>I want to find low-level C/C++ APIs, equivalent with "write" in linux systems, that don't have a buffer. Is there one? </p>
<p>The buffered I/O such as fread, fwrite are not what I wanted.</p>
| <p>Look at <a href="http://msdn.microsoft.com/en-us/library/aa363858%28VS.85%29.aspx">CreateFile</a> with the FILE_FLAG_NO_BUFFERING option</p>
|
Are there any strategies to avoid satisficing? <blockquote>
<p><strong>Satisficing</strong> (a portmanteau of "satisfy" and "suffice") is a decision-making strategy which attempts to meet criteria for adequacy, rather than to identify an optimal solution. A satisficing strategy may often be (near) optimal if the costs of the decision-making process itself, such as the cost of obtaining complete information, are considered in the outcome calculus. <em><a href="http://en.wikipedia.org/wiki/Satisficing" rel="nofollow">(Source)</a></em></p>
</blockquote>
<p>Most decisions in software engineering are easy enough to take without pondering for hours on the subject. The first solution that comes to mind is usually good enough, so we can quickly use that and proceed to the next decision.</p>
<p>However, there are also those rare cases where you have to solve a more difficult and / or critical problem. Those problems can cost you a lot of money or time when solved in a suboptimal way.</p>
<p>In those cases I am usually trying to come up with several completely different solutions/approaches of solving the problem. I then pick one and refine it until I am fully satisfied with my solution.</p>
<p>Usually this works, but sometimes I can only come up with one adequate, but not really good, solution. I am aware that my solution is not very good and the problem is critical enough to warrant some more effort. However, knowledge of the solution I already found blocks my creativity, so I just can't find a second one (at least not right away). I am stuck with my mediocre idea and, unless I can ask someone else, I have to implement it to move forward.</p>
<p>Are there techniques to overcome this? The two things I can think of is holding a brainstorming session with someone else or going for a walk.</p>
<p>What do you do in those cases?</p>
| <p>I would normally have two problems with putting a problem aside for a week: a) my boss probably wouldn't go for it because the business will usually need a solution sooner as opposed to later, and b) I have the attention span of a gold fish, so if I drop a problem for that long, I will have to take time to walk through the problem because I've filled my brain with dozens of other problems in the meantime. </p>
<p>That's not entirely bad, because sometimes I do find a better, more elegant solution when I'm forced to refresh myself on the code and the business constraints that define the problem, but sometimes I just spend half a day running myself into the same dead-ends.</p>
<p>All that being said, the idea of putting a problem aside is a good one, but it's the time frame that's important. I've often realized a solution while eating breakfast the morning following an end of the day spaghetti-code brain lock up fiasco.</p>
<p>Trying to articulate the problem to colleagues often helps, just because the effort will expose gaps in your understanding of the problem. Usually the other person won't find a better solution unless they're actually working with you on the problem from the beginning, just because they won't understand all the constraints that you've probably spent days mapping out in your head.</p>
<p>To answer the original question, my preferred method after taking a break and running it by some colleagues, is to implement the adequate solution and just get something working.</p>
<p>One reason is that if the client decides that wasn't what they wanted, because they never really know what they want in the first place, you won't have spent too much time on something that'll be thrown out anyway. Another reason is that the adequate solution might just be that: adequate. You can move on. The best reason is that an implementation gets you into the hard questions quickly, and from there you might start to see a better solution.</p>
<p>It's like building models as an architect. You can do lots of drawings, and even spend a lot of time on nice renderings, but it's really more effective to quickly get a glue gun and starting throwing cardboard models together. Once you can see it in 3D you can start to see where things don't line up properly, and you haven't wasted your time on nice renderings that will gloss over the shortcomings.</p>
|
ExternalInterface.call() not getting return value <p>I have a Javascript function that returns the innerHTML of a div. I am attempting to call this function from Actionscript and store the return value. I know that the Javascript function is being called because there is an alert that displays the return data, The data that is returned to Actionscript, however, is null. I am not sure what is causing this. Here is a code example of what I am attempting to do:</p>
<pre><code>Javascript:
function JSFunc () {
var x = document.getElementById("myDiv");
alert(x.innerHTML);
return x.innerHTML;
}
Actionscript:
import flash.external.*;
if (ExternalInterface.available) {
var retData:Object = ExternalInterface.call("JSFunc");
if(retData != null) {
textField.text = retData.toString();
} else {
textField.text = "Returned Null";
}
} else {
textField.text = "External Interface not available";
}
</code></pre>
<p>Like I said earlier, the alert shows up with the contents of the div but the text in the textfield is always "Returned Null", meaning that the ExternalInterface is available. I should add that I can only test this in IE7 and IE8. Any advice on what to do would be much appreciated. </p>
| <p><a href="http://osmanu.com/flex/EITest/EITest.html" rel="nofollow">This is a working sample</a> based on the code you provided. You can right click it to view the source. I suspect the problem lies in the HTML for 'myDiv' or when you are making the actionscript call.</p>
|
Get unique identifier of a Thread in Java 1.4 <p>In Java 1.4, is there any better way of getting a Thread's ID than using <code>Thread.getName()</code>?</p>
<p>I mean, <code>getName()</code> in unit tests returns something like <code>"Thread-1"</code>, but in WebLogic 10 I get <code>"[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'.xml"</code>.</p>
| <p><a href="http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getId%28%29">Thread.getId</a> (it can theoretically <a href="http://stackoverflow.com/questions/591627/thread-getid-global-uniqueness-question">overflow</a>, but it is defined not to and in practice will not).</p>
<p>1.5 is going through its End of Service Life period now, but if you are using old dusty-decks 1.4, then you can implement your own with <a href="http://java.sun.com/javase/6/docs/api/java/lang/ThreadLocal.html"><code>ThreadLocal</code></a>. (Note, don't follow the Java SE 6 API docs too closely!)</p>
|
How do I rename a filename after uploading with php? <p>How do I rename the file either before or after it gets uploaded? I just want to rename the filename, not the extension.</p>
<pre><code>$changeTXT = $_SESSION['username'];
$uploaderName = strtolower($changeTXT);
$changeTXT = strtolower($changeTXT);
$changeTXT = ucfirst($changeTXT);
$filelocation = $_POST['userfile'];
$filename = $_POST['filename'];
$max_size = $_POST['MAX_FILE_SIZE'];
$file = $_FILES['userfile'];
$allowedExtensions = array("wma", "mp3", "wav");
function isAllowedExtension($fileName) {
global $allowedExtensions;
return in_array(end(explode(".", $fileName)), $allowedExtensions);
}
if($file['error'] == UPLOAD_ERR_OK) {
if(isAllowedExtension($file['name'])) {
$uploaddir = "uploads/".$uploaderName."/";
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "Thank you for uploading your music!<br /><br />";
} else {
echo "Your file did not upload.<br /><br />";
}
echo "\n";
echo "<a href='index.php'>Return</a> to index.<br /><br />$uploaddir";
} else {
echo "You have tried to upload an invalid file type.<br /><br />";
}
} else die("Cannot upload");
</code></pre>
| <p>When using <code>move_uploaded_file</code> you get to pick the filename, so you can pick anything you want.</p>
<p>When you upload the file, its put into a temporary directory with a temporary name, <code>move_uploaded_file()</code> allows you to move that file and in that you need to set the name of the file as well.</p>
|
How to implement REST in a web application? <p>I want to know how I could implement REST in my web application. I want to create a web application based on this service, but I don't know how to do it. Now, i'm using J2EE and Tomcat. What things should be considered for these technologies?</p>
<p><strong>EDIT:</strong>
Sorry, I mean RESTful service.</p>
| <p>REST is not specific interface or technology, but a style. The best example is the web itself - your browser sends an HTTP request to a web server, which responds with a web page.</p>
<p>Representational State Transfer in this context: The representation is the web page, the state is the information contained in it. We could change the representation by switching to serving up xml instead of html, but the information would be the same.</p>
<p>In a RESTful service, you use this style to send data objects back and forth - the state is transferred from the server to you, and then you send a new state back again. </p>
<p>So, in a sense, Tomcat will already do REST for you, if you put your server pages as resources: <a href="http://carsales.com/cars/porsche2149">http://carsales.com/cars/porsche2149</a> could be the resource for your car, to which you could use HTTP POST or PUT to change the details of it.</p>
<p>The hallmarks of REST are using URIs to denote resources, as above, using JSON or XML as the interchange medium (although AHAH and other formats are used), and arguing about how to DELETE collections.</p>
<p>First, work out what your resources will be, and organise your URI system to fit it (use URL rewriting etc). Then determine the representation(s) you want to use. Finally, write the backend to deal with passing state representations around, and update the database.</p>
|
SQL Server Agent Job for the first 4 days of Month <p>I was wondering if anyone knew how to create a job that will run the first 4 days of the month in SQL Server 2000? I found how to run a job once on the first or second day, but the only way I figured I could run each of the four days would be to create a job for each day meaning I would have 4 jobs created. I was hoping for a better way.</p>
| <p>Instead of creating 4 jobs, you can create one job with 4 schedules.</p>
<p>Fire up enterprise manager, create your job as you normally would and on the schedules tab of the Job properties add 4 schedules, one for each day of the month you'd like the job to run.</p>
|
Launching Ruby without the prefix "Ruby" <p>I'm on OS X (with bash) and a newbie at unix. I want to know if it's possible to amend some file such that to run a ruby program, I don't need "ruby file.rb", but instead can just run "ruby.rb".</p>
<p>Is there a reason NOT to do this?</p>
<p>Thanks!</p>
| <p>Yes you can do this.</p>
<p>Assuming <code>ruby.rb</code> has something like this in it:</p>
<pre><code>#!/usr/bin/env ruby
puts 'Hello world'
</code></pre>
<p>At the command line: <code>chmod +x ruby.rb</code></p>
<p>This makes it executable.</p>
<p>Then you can execute it like this:</p>
<pre><code>./ruby.rb
</code></pre>
<p>For more details see <a href="http://en.wikibooks.org/wiki/Programming:Ruby%5FCreating%5FRuby%5Fprograms">wikibooks</a>.</p>
<p>EDIT (Jörg W Mittag): Using <code>#!/usr/bin/env ruby</code> instead of <code>#!/usr/bin/ruby</code> as the shebang line is more portable, because on every Unix produced in the last 20 years, the <code>env</code> command is known to live in <code>/usr/bin</code>, whereas Ruby installations are typically all over the place. (E.g., mine lives in <code>/home/joerg/jruby-1.2.0/bin/ruby</code>.)</p>
|
Assertion in VS2008 but not in VS2005 <p>After switching from VS2005 to VS2008 SP1, I found an issue that I can't explain.<br />
A program works fine under VS2005 in both release and debug mode. Under VS2008, when entering the debugger an assert is raised.<br />
If I let the program run (in debug or release mode), no assertion at all.</p>
<p>I spent almost two days on this and I don't understand what I do wrong.</p>
<p><strong>Description of the program:</strong>
I have a MFC dialog based program that creates a user thread (CWinThread) that creates the main dialog of the application.<br />
A worker thread loops infinitely and posts each second a message to the dialog. The message is processed in the gui thread.</p>
<p><strong>Some parts of my code:</strong></p>
<p>The InitInstance of the gui thread:</p>
<pre><code>BOOL CGraphicalThread::InitInstance()
{
CGUIThreadDlg* pDlg = new CGUIThreadDlg();
pDlg->Create(CGUIThreadDlg::IDD);
m_pMainWnd = pDlg;
AfxGetApp()->m_pMainWnd = pDlg;
return TRUE;
}
</code></pre>
<p>The worker thread:</p>
<pre><code>UINT ThreadProc(LPVOID pVoid)
{
do
{
AfxGetApp()->m_pMainWnd->PostMessage(WM_APP+1, (WPARAM)new CString("Hello"), NULL);
Sleep(1000);
}
while(!bStopThread);
return 0;
}
</code></pre>
<p>The dialog message handler is like this:</p>
<pre><code>LRESULT CGUIThreadDlg::OnMsg(WPARAM wp, LPARAM lp)
{
CListBox* pList = (CListBox*)GetDlgItem(IDC_LIST1);
CString* ps = (CString*)wp;
pList->InsertString(-1, *ps);
delete ps;
return 1L;
}
</code></pre>
<p>This works perfectly fine with VS2005.
But with VS2008, but as soon as a put a breakpoint and enter the debugging mode, I have an assertion raised ???<br />
wincore.cpp line 906</p>
<pre><code>CObject* p=NULL;
if(pMap)
{
ASSERT( (p = pMap->LookupPermanent(m_hWnd)) != NULL ||
(p = pMap->LookupTemporary(m_hWnd)) != NULL);
}
ASSERT((CWnd*)p == this); // must be us
// Note: if either of the above asserts fire and you are
// writing a multithreaded application, it is likely that
// you have passed a C++ object from one thread to another
// and have used that object in a way that was not intended.
// (only simple inline wrapper functions should be used)
//
// In general, CWnd objects should be passed by HWND from
// one thread to another. The receiving thread can wrap
// the HWND with a CWnd object by using CWnd::FromHandle.
//
// It is dangerous to pass C++ objects from one thread to
// another, unless the objects are designed to be used in
// such a manner.
</code></pre>
<p>If I remove the GUI thread and create the dialog into the CWinApp thread, the problem doesn't occur anymore.</p>
<p>Does anybody have any idea?<br />
Am I doing something wrong?</p>
<p>Thank you</p>
| <pre><code>// Note: if either of the above asserts fire and you are
// writing a multithreaded application, it is likely that
// you have passed a C++ object from one thread to another
// and have used that object in a way that was not intended.
// (only simple inline wrapper functions should be used)
//
// In general, CWnd objects should be passed by HWND from
// one thread to another. The receiving thread can wrap
// the HWND with a CWnd object by using CWnd::FromHandle.
//
// It is dangerous to pass C++ objects from one thread to
// another, unless the objects are designed to be used in
// such a manner.
</code></pre>
|
Header <h2> floating to be below the next UL list <p>I have a multiple unordered lists, with a h2 titling each list by subject.</p>
<p>Here is the html</p>
<pre><code><h2>Early Childhood Education</h2>
<ul class="course-list">
<li><a href="/academics/courses/child_growth_and_development/" title="Child Growth and Development">Child Growth and Development</a></li>
<li><a href="/academics/courses/curriculum_and_methods_in_teaching_early_childhood_education/" title="Curriculum and Methods in Teaching Early Childhood Education">Curriculum and Methods in Teaching Early Childhood Education</a></li>
<li><a href="/academics/courses/introduction_to_early_childhood_education/" title="Introduction to Early Childhood Education">Introduction to Early Childhood Education</a></li>
<li><a href="/academics/courses/introduction_to_education/" title="Introduction to Education">Introduction to Education</a></li>
<li><a href="/academics/courses/practicum_i_early_childhood/" title="Practicum I: Early Childhood">Practicum I: Early Childhood</a></li>
<li><a href="/academics/courses/practicum_ii_early_childhood/" title="Practicum II: Early Childhood">Practicum II: Early Childhood</a></li>
<li><a href="/academics/courses/practicum_in_education/" title="Practicum in Education">Practicum in Education</a></li>
</ul>
<h2>Emergency Medical Technician</h2>
<ul class="course-list">
<li><a href="/academics/courses/emergency_medical_technician_emt_basic/" title="Emergency Medical Technician (EMT) â Basic">Emergency Medical Technician (EMT) â Basic</a></li>
<li><a href="/academics/courses/emergency_medical_technician_emt_paramedic_i/" title="Emergency Medical Technician (EMT) â Paramedic I">Emergency Medical Technician (EMT) â Paramedic I</a></li>
<li><a href="/academics/courses/emergency_medical_technician_emt_paramedic_ii_field_internship_part_i/" title="Emergency Medical Technician (EMT) â Paramedic II (Field Internship â Part I)">Emergency Medical Technician (EMT) â Paramedic II (Field Internship â Part I)</a></li>
<li><a href="/academics/courses/emergency_medical_technician_emt_paramedic_iii/" title="Emergency Medical Technician (EMT) â Paramedic III">Emergency Medical Technician (EMT) â Paramedic III</a></li>
<li><a href="/academics/courses/emergency_medical_technician_emt_paramedic_iv_field_internship_part_ii/" title="Emergency Medical Technician (EMT) â Paramedic IV (Field Internship â Part II)">Emergency Medical Technician (EMT) â Paramedic IV (Field Internship â Part II)</a></li>
<li><a href="/academics/courses/emt_basic_fieldwork/" title="EMT-Basic Fieldwork">EMT-Basic Fieldwork</a></li>
<li><a href="/academics/courses/report_writing_for_healthcare_professionals/" title="Report Writing for Healthcare Professionals">Report Writing for Healthcare Professionals</a></li>
</ul>
<h2>English</h2>
<ul class="course-list">
<li><a href="/academics/courses/african_american_literature/" title="African American Literature">African American Literature</a></li>
<li><a href="/academics/courses/basic_acting_technique/" title="Basic Acting Technique">Basic Acting Technique</a></li>
<li><a href="/academics/courses/contemporary_american_poetry/" title="Contemporary American Poetry">Contemporary American Poetry</a></li>
<li><a href="/academics/courses/english_i_college_writing/" title="English I: College Writing">English I: College Writing</a></li>
<li><a href="/academics/courses/english_ii_introduction_to_literature/" title="English II: Introduction to Literature">English II: Introduction to Literature</a></li>
<li><a href="/academics/courses/essentials_of_english/" title="Essentials of English">Essentials of English</a> *</li>
<li><a href="/academics/courses/interpersonal_communication/" title="Interpersonal Communication">Interpersonal Communication</a></li>
<li><a href="/academics/courses/interviewing_practices_and_principles/" title="Interviewing Practices and Principles">Interviewing Practices and Principles</a></li>
<li><a href="/academics/courses/introduction_to_drama_study/" title="Introduction to Drama Study">Introduction to Drama Study</a></li>
<li><a href="/academics/courses/introduction_to_poetry/" title="Introduction to Poetry">Introduction to Poetry</a></li>
<li><a href="/academics/courses/introduction_to_technical_writing/" title="Introduction to Technical Writing">Introduction to Technical Writing</a></li>
<li><a href="/academics/courses/journalism/" title="Journalism">Journalism</a></li>
<li><a href="/academics/courses/journalism_ii/" title="Journalism II">Journalism II</a></li>
<li><a href="/academics/courses/literature_for_children/" title="Literature for Children">Literature for Children</a></li>
<li><a href="/academics/courses/literature_of_the_western_world/" title="Literature of the Western World">Literature of the Western World</a></li>
<li><a href="/academics/courses/major_american_writers/" title="Major American Writers">Major American Writers</a></li>
<li><a href="/academics/courses/major_english_writers/" title="Major English Writers">Major English Writers</a></li>
<li><a href="/academics/courses/modern_american_novel/" title="Modern American Novel">Modern American Novel</a></li>
<li><a href="/academics/courses/nonfiction_literature/" title="Nonfiction Literature">Nonfiction Literature</a></li>
<li><a href="/academics/courses/public_speaking/" title="Public Speaking">Public Speaking</a></li>
<li><a href="/academics/courses/science_fiction/" title="Science Fiction">Science Fiction</a></li>
<li><a href="/academics/courses/service_learning_volunteer_project/" title="Service Learning â Volunteer Project">Service Learning â Volunteer Project</a></li>
<li><a href="/academics/courses/shakespeare/" title="Shakespeare">Shakespeare</a></li>
<li><a href="/academics/courses/storytelling/" title="Storytelling">Storytelling</a></li>
<li><a href="/academics/courses/the_short_story/" title="The Short Story">The Short Story</a></li>
<li><a href="/academics/courses/voice_and_diction/" title="Voice and Diction">Voice and Diction</a></li>
<li><a href="/academics/courses/western_mythology/" title="Western Mythology">Western Mythology</a></li>
<li><a href="/academics/courses/women_in_literature/" title="Women in Literature">Women in Literature</a></li>
<li><a href="/academics/courses/writing_workshop_i/" title="Writing Workshop I">Writing Workshop I</a></li>
</ul>
</code></pre>
<p>Here is the CSS</p>
<pre><code>.col-middle .course-list li {
width:50%;
float:left;
}
</code></pre>
<p>Here is a screen shot of what it looks like: <a href="http://i40.tinypic.com/2141nd3.png" rel="nofollow">http://i40.tinypic.com/2141nd3.png</a></p>
<p>The problem you see in the screen shot is the text within the h2 tags is floating up a line if there is some space after the list above it.</p>
<p>I fixed that by setting overflow:auto; within the ul style, but that made the left half of the list discs dissapear (as you see here: <a href="http://i39.tinypic.com/2i8y62r.png" rel="nofollow">http://i39.tinypic.com/2i8y62r.png</a>)</p>
<p>Also, I'd like to create some spacing between the bottom of the ul list, and the h2 header.</p>
| <p>You might wrap each h2/ul pair in a div. This is even good for semantics, since the two are related and therefore could be said to be part of a logical division. Then you can float the whole div and keep the elements grouped.</p>
|
What would this sql query (w count and group by) look like when translated to linq? <p>How would the following sql query look when translated to linq?</p>
<pre><code>SELECT
myId, Count(myId)
FROM MyTable
GROUP BY myId
</code></pre>
<p>I've tried the following:</p>
<pre><code>var q = from a in db.MyTable
group a by a.Id into g
let count = g.Count()
select new
{
Count = Id,
Key= g.Key
};
</code></pre>
<p>but it raises an exception on enumeration indicating that there is no db function with a mapping named 'Key'. I'm using LLBLGen on this particular app and I suspect that's where the problem is rooted. I want to verify that my linq syntax is correct before I start digging though. Anyone see anything wrong?</p>
| <p>Try this:</p>
<pre><code>var q = from a in db.MyTable
group a by a.Id into g
select new { Id=g.Key, Count=g.Count() };
</code></pre>
<p>That's nearly the same as yours, but your <code>Count</code> is obtained in a different way which looks wrong to me.</p>
<p>If LLBLGen doesn't understand <code>IGrouping.Key</code> though, it could be tricky...</p>
<p>To check whether your LINQ syntax is correct or not, I'd recommend building a very simple in-memory list to use as your table. Here's an example:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
class Test
{
static void Main()
{
var data = new[] {
new { Id="X", Name="Jon" },
new { Id="Y", Name="Marc" },
new { Id="X", Name="Holly" },
};
var query = from a in data
group a by a.Id into g
select new { Id=g.Key, Count=g.Count() };
foreach (var entry in query)
{
Console.WriteLine(entry);
}
}
}
</code></pre>
<p>This looks like it's giving the right results to me.</p>
|
Jquery Hidden Field in Table <p>I was wondering if anyone knew of a way to access a hidden field (by client id) within a table row using jquery.</p>
<pre><code>$("#tblOne").find("tr").click(function() {
var worker = $(this).find(":input").val();
});
</code></pre>
<p>I find that the above works for a row that has only one input, but I need some help figuring out a way to get the value by the inputs name.</p>
<p>Here's the example of a table row. How would I access the two fields by their id's?</p>
<pre><code><table id="tblOne">
<tr>
<td>
<asp:HiddenField id="hdnfld_Id" Text='<% Eval("ID") %>'></asp:HiddenField>
</td>
<td>
<asp:HiddenField id="hdnfld_Id2" Text='<% Eval("ID2") %>'></asp:HiddenField>
</td>
</tr>
</table>
</code></pre>
| <p>I normally use a positive lookup to match the id, this method avoids requiring the client id</p>
<p>(id contains foo)
$(this).find("input[id*='foo']").val(); </p>
|
Concatenate collection of XML tags to string with LINQ <p>I'm stuck with using a web service I have no control over and am trying to parse the XML returned by that service into a standard object.</p>
<p>A portion of the XML structure looks like this</p>
<pre><code><NO>
<L>Some text here </L>
<L>Some additional text here </L>
<L>Still more text here </L>
</NO>
</code></pre>
<p>In the end, I want to end up with one String property that will look like <strong>"Some text here Some additional text here Still more text here "</strong></p>
<p>What I have for an initial pass is what follows. I think I'm on the right track, but not quite there yet:</p>
<pre><code>XElement source = \\Output from the Webservice
List<IndexEntry> result;
result = (from indexentry in source.Elements(entryLevel)
select new IndexEntry()
{
EtiologyCode = indexentry.Element("IE") == null ? null : indexentry.Element("IE").Value,
//some code to set other properties in this object
Note = (from l in indexentry.Elements("NO").Descendants
select l.value) //This is where I stop
// and don't know where to go
}
</code></pre>
<p>I know that I could add a ToList() operator at the end of that query to return the collection. Is there an opertaor or technique that would allow me to inline the concatentation of that collection to a single string?</p>
<p>Feel free to ask for more info if this isn't clear.</p>
<p>Thanks.</p>
| <p>LINQ to XML is indeed the way here:</p>
<pre><code>var textArray = topElement.Elements("L")
.Select(x => x.Value)
.ToArray();
var text = string.Join(" ", textArray);
</code></pre>
<p>EDIT: Based on the comment, it looks like you just need a single-expression way of representing this. That's easy, if somewhat ugly:</p>
<pre><code>result = (from indexentry in source.Elements(entryLevel)
select new IndexEntry
{
EtiologyCode = indexentry.Element("IE") == null
? null
: indexentry.Element("IE").Value,
//some code to set other properties in this object
Note = string.Join(" ", indexentry.Elements("NO")
.Descendants()
.Select(x => x.Value)
.ToArray())
};
</code></pre>
<p>Another alternative is to extract it into a separate extension method (it has to be in a top-level static class):</p>
<pre><code>public static string ConcatenateTextNodes(
this IEnumerable<XElement> elements)
{
string[] values = elements.Select(x => x.Value).ToArray();
// You could parameterise the delimiter here if you wanted
return string.Join(" ", values);
}
</code></pre>
<p>then change your code to:</p>
<pre><code>result = (from indexentry in source.Elements(entryLevel)
select new IndexEntry
{
EtiologyCode = indexentry.Element("IE") == null
? null
: indexentry.Element("IE").Value,
//some code to set other properties in this object
Note = indexentry.Elements("NO")
.Descendants()
.ConcatenateTextNodes()
}
</code></pre>
<p><strong>EDIT: A note about efficiency</strong></p>
<p>Other answers have suggested using <code>StringBuilder</code> in the name of efficiency. I would check for evidence of this being the right way to go before using it. If you think about it, <code>StringBuilder</code> and <code>ToArray</code> do similar things - they create a buffer bigger than they need to, add data to it, resize it when necessary, and come out with a result at the end. The hope is that you won't need to resize too often.</p>
<p>The <em>difference</em> between <code>StringBuilder</code> and <code>ToArray</code> here is what's being buffered - in <code>StringBuilder</code> it's the entire contents of the string you've built up so far. With <code>ToArray</code> it's <em>just</em> references. In other words, resizing the internal buffer used for <code>ToArray</code> is likely to be cheaper than resizing the one for <code>StringBuilder</code>, <em>particularly</em> if the individual strings are long.</p>
<p>After doing the buffering in <code>ToArray</code>, <code>string.Join</code> is hugely efficient: it can look through <em>all</em> the strings to start with, work out <em>exactly</em> how much space to allocate, and then concatenate it without ever having to copy the actual character data.</p>
<p>This is in <a href="http://stackoverflow.com/questions/585860/string-join-vs-stringbuilder-which-is-faster/585897#585897">sharp contrast to a previous answer I've given</a> - but unfortunately I don't think I ever wrote up the benchmark.</p>
<p>I certainly wouldn't expect <code>ToArray</code> to be significantly slower, and I think it makes the code simpler here - no need to use side-effects etc, aggregation etc.</p>
|
SQL Server 2005: How to automatically include database name and brackets in queries <p>Good day,</p>
<p>In SQL Server 2005, when I write a new query, I like to drap and drop table and column names from the object explorer. However, when I drag and drop a table, is there a way to automatically include the database name? </p>
<p>(example: when I drag and drop the table Table1 in the query designer, I would like to have Database1.dbo.Table1 instead of just Table1)</p>
<p>Also, is there a way to automatically include '[' and ']' around the column and table names?</p>
<p>Thank you!</p>
| <p>Sorry, not from drag and drop from object explorer.</p>
<p>One of the tools suggested in this question may help:</p>
<p><a href="http://stackoverflow.com/questions/686394/686416">Need a tool to automatically indent and format SQL Server stored procedures</a></p>
|
NHibernate unexpected ORDER BY Statement <p>I am using NHibernate 2.0, and when I submit a request asking for the top 2 records to be returned, I get a number of ORDER BY clauses in my SQL. When I take out the Max results, the query looks fine (no ORDER BY statements). Why is NHibernate automatically adding this when I am looking for a subset of records? Thanks in advance </p>
<p>See SQL statements below:</p>
<p><strong>Unexpected ORDER BY</strong></p>
<pre>
exec sp_executesql
N'<b>SELECT TOP 2</b> Person1_36_0_, LastReco2_36_0_, SSN3_36_0_,
FirstName4_36_0_, LastName5_36_0_, MiddleIn6_36_0_, Title7_36_0_, Suffix8_36_0_,
DateOfBi9_36_0_, IsDeceased10_36_0_, Decease11_36_0_, Contact12_36_0_, MailHol13_36_0_,
MailHol14_36_0_, MailHol15_36_0_, Preferr16_36_0_, CreatedBy17_36_0_, Created18_36_0_,
ModifiedBy19_36_0_, Modifie20_36_0_
FROM <b>(SELECT ROW_NUMBER() OVER(ORDER BY __hibernate_sort_expr_0__) as row</b>,
query.Person1_36_0_, query.LastReco2_36_0_, query.SSN3_36_0_, query.FirstName4_36_0_,
query.LastName5_36_0_, query.MiddleIn6_36_0_, query.Title7_36_0_, query.Suffix8_36_0_,
query.DateOfBi9_36_0_, query.IsDeceased10_36_0_, query.Decease11_36_0_,
query.Contact12_36_0_, query.MailHol13_36_0_, query.MailHol14_36_0_, query.MailHol15_36_0_,
query.Preferr16_36_0_, query.CreatedBy17_36_0_, query.Created18_36_0_,
query.ModifiedBy19_36_0_, query.Modifie20_36_0_, query.__hibernate_sort_expr_0__
FROM
(SELECT this_.Person_id as Person1_36_0_, this_.[LastRecordVersion] as LastReco2_36_0_,
this_.[SSN] as SSN3_36_0_, this_.[FirstName] as FirstName4_36_0_, this_.[LastName] as
LastName5_36_0_, this_.[MiddleInitial] as MiddleIn6_36_0_, this_.[Title] as Title7_36_0_,
this_.[Suffix] as Suffix8_36_0_, this_.[DateOfBirth] as DateOfBi9_36_0_, this_.[IsDeceased]
as IsDeceased10_36_0_, this_.[DeceasedDate] as Decease11_36_0_, this_.[ContactMethod_id] as
Contact12_36_0_, this_.[MailHoldReason_id] as MailHol13_36_0_, this_.[MailHoldStartDate] as
MailHol14_36_0_, this_.[MailHoldEndDate] as MailHol15_36_0_, this_.[PreferredName] as
Preferr16_36_0_, this_.[CreatedBy] as CreatedBy17_36_0_, this_.[CreatedDate] as
Created18_36_0_, this_.[ModifiedBy] as ModifiedBy19_36_0_, this_.[ModifiedDate] as
Modifie20_36_0_, CURRENT_TIMESTAMP as __hibernate_sort_expr_0__
FROM MC_Person this_
WHERE this_.[SSN] = @p0) query) page
WHERE **page.row > 0 ORDER BY __hibernate_sort_expr_0__**',
N'@p0 nvarchar(9)',@p0=N'123456789'
</pre>
<p><strong>Correct SQL (without getting Top 2 records)</strong></p>
<pre>
exec sp_executesql
N'SELECT this_.Person_id as Person1_36_0_, this_.[LastRecordVersion] as LastReco2_36_0_,
this_.[SSN] as SSN3_36_0_, this_.[FirstName] as FirstName4_36_0_, this_.[LastName] as
LastName5_36_0_, this_.[MiddleInitial] as MiddleIn6_36_0_, this_.[Title] as Title7_36_0_,
this_.[Suffix] as Suffix8_36_0_, this_.[DateOfBirth] as DateOfBi9_36_0_, this_.[IsDeceased]
as IsDeceased10_36_0_, this_.[DeceasedDate] as Decease11_36_0_, this_.[ContactMethod_id] as
Contact12_36_0_, this_.[MailHoldReason_id] as MailHol13_36_0_, this_.[MailHoldStartDate] as
MailHol14_36_0_, this_.[MailHoldEndDate] as MailHol15_36_0_, this_.[PreferredName] as
Preferr16_36_0_, this_.[CreatedBy] as CreatedBy17_36_0_, this_.[CreatedDate] as
Created18_36_0_, this_.[ModifiedBy] as ModifiedBy19_36_0_, this_.[ModifiedDate] as
Modifie20_36_0_
FROM MC_Person this_
WHERE this_.[SSN] = @p0',
N'@p0 nvarchar(9)',@p0=N'123456789'
</pre>
| <p>It's the way that paging is implemented. So there's no special case for just taking the top n elements, because for example Oracle does not support this construct.</p>
<p>So anything that has either of the paging limits set is done this way.</p>
<p>Are you getting the correct results?</p>
|
How can I allow my user to insert HTML code, without risks? (not only technical risks) <p>I developed a web application, that permits my users to manage some aspects of a web site dynamically (yes, some kind of cms) in LAMP environment (debian, apache, php, mysql)</p>
<p>Well, for example, they create a news in their private area on my server, then this is published on their website via a cURL request (or by ajax).</p>
<p>The news is created with an WYSIWYG editor (fck at moment, probably tinyMCE in the next future).</p>
<p>So, i can't disallow the html tags, but how can i be safe?
What kind of tags i MUST delete (javascripts?)?
That in meaning to be server-safe.. but how to be 'legally' safe?
If an user use my application to make xss, can i be have some legal troubles?</p>
| <p>If you are using php, an excellent solution is to use <a href="http://htmlpurifier.org/">HTMLPurifier</a>. It has many options to filter out bad stuff, and as a side effect, guarantees well formed html output. I use it to view spam which can be a hostile environment. </p>
|
How do I save a web page to image <p>I have a WebBrowser control and I want to save the whole page viewed to image (any web page).
I tried using IHTMLElementRender interface but it didn't work for all web pages. Maybe I'm doing something wrong because sometimes the snapshot included the scrollers and sometimes it was just partial.
Do you have a working example that can save the whole web page to an image?</p>
<p>Thanks.</p>
| <p>There is a <a href="http://www.codeproject.com/KB/graphics/IECapture.aspx" rel="nofollow">great CodeProject article</a> that shows hows to accomplish this task using the IE engine. If you prefer to use another browser's rendering engine, this is a good place to start learning. There is also <a href="https://addons.mozilla.org/en-US/firefox/addon/1146" rel="nofollow">an addon</a> for Firefox which will do this, you could dig into the internals of it to get insight on how to accomplish this in firefox.</p>
|
copy the symbolic link in Solaris <p>I am trying to copy a link on Solaris OS but find that it does not simply copy the link instead copies the whole contents of the directory/file the link is poinitng to? Which is not in other OSes like AIX,HP-UX,Linux.</p>
<p>Is this a normal behaviour of Solaris OS?</p>
| <p>Charlie was close, you want the <code>-L</code>, <code>-H</code> or <code>-P</code> flags with the <code>-R</code> flag (probably just <code>-R -P</code>). Similar flags exist for <code>chmod(1)</code> and <code>chgrp(1)</code>. I've pasted an excerpt from the man-page below.</p>
<p>Example:</p>
<pre><code>$ touch x
$ ln -s x y
$ ls -l x y
-rw-r--r-- 1 mjc mjc 0 Mar 31 18:58 x
lrwxrwxrwx 1 mjc mjc 1 Mar 31 18:58 y -> x
$ cp -R -P y z
$ ls -l z
lrwxrwxrwx 1 mjc mjc 1 Mar 31 18:58 z -> x
$
</code></pre>
<p>Alternatively, plain old tar will happily work with symbolic links by default, even the venerable version that ships with Solaris:</p>
<pre><code>tar -cf foo | ( cd bar && tar -xf - )
</code></pre>
<p>(where foo is a symlink or a directory containing symlinks).</p>
<pre><code> /usr/bin/cp -r | -R [-H | -L | -P] [-fip@] source_dir... target
...
-H Takes actions based on the type and contents of the
file referenced by any symbolic link specified as a
source_file operand.
If the source_file operand is a symbolic link, then cp
copies the file referenced by the symbolic link for
the source_file operand. All other symbolic links
encountered during traversal of a file hierarchy are
preserved.
-L Takes actions based on the type and contents of the
file referenced by any symbolic link specified as a
source_file operand or any symbolic links encountered
during traversal of a file hierarchy.
Copies files referenced by symbolic links. Symbolic
links encountered during traversal of a file hierarchy
are not preserved.
-P Takes actions on any symbolic link specified as a
source_file operand or any symbolic link encountered
during traversal of a file hierarchy.
Copies symbolic links. Symbolic links encountered dur-
ing traversal of a file hierarchy are preserved.
</code></pre>
|
Role based or shopping cart style Java bean binding? <p>I have a POJO that I would like to expose as XML from a web service, preferably with JAX-B.</p>
<p>The fields that need to be exposed in XML depend on what type of user is making the request. For instance, we have a role for HumanResources and Finance users. A User might be defined as:</p>
<p>@XmlRootElement</p>
<p>public class User {</p>
<p>@XmlElement public String someHumanResourceData;</p>
<p>@XmlElement public String someFinanceData;</p>
<p>}</p>
<p>I want HR users to see the HR data, and Finance to see the Finance data, but nothing more than that. HR should not see Finance data.</p>
<p>Is there a recommended approach on how to do this? What are some search terms I could use to lookup more information on the Web?</p>
<p>A few ideas that I don't find appealing:
1) I could use subclassing to expose a FinanceUser and HumanResourceUser that only has the relevant data, and a parent User with the shared data. However, this is fragile and may work on a small example, I feel I need a more flexible, compositional approach for production.
2) A co-worker recommends a "shopping cart" approach in which the client requests what fields he/she wants with each request. I'm not finding a standard way to do this or even many other people who have done this approach. It sounds really home-grown and labor intensive to me.</p>
<p>Any other ideas? </p>
| <p>Why don't you just check the user's role in your server-side web service implementation?</p>
<p>What is your web service interface?</p>
<pre><code>public interface DarcysWebService {
public HumanResourceResponse getHumanResourceData(Authentication a, HumanResourceRequest req);
public FinanceResponse getFinanceData(Authentication a, FinanceRequest req);
}
</code></pre>
<p>I would then check the authentication data supplied (username, password) against your database of users (uuid, username, password, role), and then use the role to determine whether the response is a message saying "Error - you don't have access privileges" or to actually populate the data fields/objects in the response with the requested data.</p>
|
iPhone: Where is the Starting Point in an View-Based Application? <p>I can't find it. Actually I look for the part where I could try this:</p>
<pre><code>[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];
self.navigationController.view.bounds = CGRectMake(0,0,320,480);
self.navigationController.navigationBar.hidden = YES;
</code></pre>
| <p>The starting point would be your App delegate, the applicationDidFinishLaunching method. When you create a new application, x-code should create one of those for you.</p>
<pre><code>- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Do your thing here.
}
</code></pre>
|
(Ruby) If the array intersection operator ( & ) is inefficient, why is it available? <p>I asked a <a href="http://stackoverflow.com/questions/699448/ruby-how-do-you-check-whether-a-range-contains-a-subset-of-another-range">question</a> yesterday about comparing ranges for overlap and its been stuck in my throat ever since.</p>
<p>The consensus seems to be that my preferred answer which involves using the array intersection operator (&), is inefficient because comparing arrays is costly.</p>
<p>I wonder then, why this feature is in the language? Could it be that the language creators believed that sometimes you need an elegant way to achieve a solution even if it's expensive to do so? Is comparing arrays so costly that you should avoid it whenever possible? The whole attraction of Ruby for me is the focus on syntactic elegance over premature optimization. </p>
| <p><code>&</code> is not a particularly inefficient method. I think you misunderstood the criticism of the accepted answer.</p>
<p>Your preferred solution is inefficient because it converts the ranges to arrays. </p>
<p>A range such as <code>1..10000</code> has a relatively small memory footprint - it only stores the start and end points. But if you convert it to an array, you allocate memory for all 10,000 entries. </p>
|
.Net: Nested References <p>How smart is Garbage Collection when it comes to nested references? </p>
<p>Take this code for example:</p>
<pre><code>Public Class SomeClass
Private m_SomeOtherClass(Me)
End Class
</code></pre>
<p>I know that GC works by looking at how many references remain, and any object without any references ends up getting dumped. So in this case, where there's a reference coming from a member variable, is that a memory leak waiting to happen (unless you implement IDisposable, etc)?</p>
<p>Right now I'm assuming that the GC is smart enough for this, since it could probably check to see if any references are coming from the object itself, and just not count them towards the reference count. But I thought I would dig a little.</p>
| <p>It's absolutely fine. The GC works from a set of roots (local and static variables, etc) and finds all the references it can. If nothing else references this mutually-referencing object, it will be eligible for collection.</p>
|
Sample text that will invalidate ASP.NET text input? <p>I need to do some checking on a validation control but I am not sure what type of text ASP.NET will think is a security issue. Can someone give me some things to try? I tried various HTML tags and it seemed to accept them fine. This is a multiline rich textbox used for saving a field of text to the database. The code for saving is inside of an If Me.IsValid with no ELSE specified, but after the save function is called it proceeds to display a 'saved' message and redirect the page. Some users have been losing work so I think the problem is that Me.IsValid is false so the save function is called but does nothing... Anyways what can I try to invalidate this with? Note I did not write the code for this I am just troubleshooting it.</p>
| <p>It sounds like you are confusing Validator controls with ValidateRequest, an internal mechanism of ASP.Net for sanitizing requests.</p>
<p>Validator validation is entirely dependant on your validators. Are you using a RequiredFieldValidator? Then the invalid inputs are simply blank textboxes. Is it a RegularExpressionValidator? Then you need to enter something that doesn't match the regular expression. CustomValidator? Then you need to check the validation logic.</p>
<p>It sounds to me more like you're worried about the input being sanitized for running database queries with. The first thing to check is that in your Page directive, "ValidateRequest" isn't being set to "false". If it is, that would explain why HTML is being allowed through. </p>
<p>You should also check out the following:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/a2a4yykt.aspx" rel="nofollow">How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/7kh55542.aspx" rel="nofollow">Validating User Input in ASP.NET Web Pages</a></p>
<p>Then, if you'd like to try a database injection attack, just google for a basic SQL Injection tutorial.</p>
|
Django Model.object.get pre_save Function Weirdness <p>I have made a function that connects to a models 'pre_save' signal. Inside the function I am trying to check if the model instance's pk already exists in the table with:</p>
<pre><code>sender.objects.get(pk=instance._get_pk_val())
</code></pre>
<p>The first instance of the model raises an error. I catch the error and generate a slug field from the title. In a second instance, it doesn't throw the error. I checked the value of instance._get_pk_val() on both instances and they are the same: None</p>
<p>So:</p>
<pre><code># This one raises an error in the sluggit function
instance1 = Model(title="title 1")
instance1.save()
# This one doesn't raise an error
instance2 = Model(title="title 2")
instance2.save()
</code></pre>
<p>This is my 3rd day messing around with python and django. So I am sorry if it something newbish that I am not seeing.</p>
<p><strong>Edit:</strong> </p>
<p>The Model:</p>
<pre><code>class Test(models.Model):
title = models.CharField(max_length=128)
slug = models.SlugField(max_length=128)
slug.prepopulate_from=('title',)
signals.pre_save.connect(package.sluggit, sender=Test)
</code></pre>
<p>The Function Basics:</p>
<pre><code>def sluggit(sender, instance, signal, *args, **kwargs):
try:
sender.objects.get(pk=instance._get_pk_val())
except:
# Generate Slug Code
</code></pre>
<p>@S.Lot told me to override the save() method in the comments. I'll have to try that. I would still like to know why the second call to model.objects.get() isn't raising an error with this method.</p>
<p><strong>Edit 2</strong>
Thank you @S.Lot. Overriding the save method works perfectly. Still curious about the signal method. Hmm, weird.</p>
<p><strong>Edit 3</strong>
After playing around a little more, I found that using instance.objects.get() instead of sender.objects.get() works:</p>
<pre><code>def sluggit(sender, instance, signal, *args, **kwargs):
try:
sender.objects.get(pk=instance._get_pk_val())
except:
# Generate Slug Code
</code></pre>
<p>needs to be:</p>
<pre><code>def sluggit(sender, instance, signal, *args, **kwargs):
try:
instance.objects.get(pk=instance._get_pk_val())
except:
# Generate Slug Code
</code></pre>
<p>A bug? For some reason I thought sender.objects.get() would be the same as Test.objects.get().</p>
| <p>S.Lott is correct... use <code>save()</code>, as you've already acknowledged that you have started doing.</p>
<p>As for the signal question, I can honestly see nothing wrong with your code. I've even run it locally myself with success. Are you sure that you're representing it properly in the question? Or that instance2 isn't already an existing database object (perhaps a goof in your test code)?</p>
|
Context help for Java API & language in NetBeans <p>Is it possible to set up context help for Java API & language in NetBeans. </p>
<p>For example something like pressing F1 on <code>ServletContextListener</code> (for API) or on word <code>while</code> (for language) in source code and obtain help on these words.
(something like in Visual Studio for instance)</p>
<p>I am using NetBeans 6.5.</p>
| <p>Pressing Alt-F1 will bring up the javadoc in your default browser but you have to have the javadocs installed for the APIs that you're using.</p>
<p>To install the Java SE javadoc for example, go to <a href="http://java.sun.com/javase/downloads/index.jsp" rel="nofollow">java.sun.com</a> and download the documentation then in Netbeans go to <strong>Tools</strong> > <strong>Java Platform</strong> then click on the <strong>Javadoc</strong> tab. Next, click <strong>Add ZIP/Folder</strong> and select the file you just downloaded.</p>
<p><strong>Window</strong> > <strong>Other</strong> > <strong>Javadoc</strong> will show a panel with some basic info about the class/interface you highlight.</p>
|
Did test server port change in Rails 2.3? <p>I upgraded rails to 2.3.2 from 2.1.1 yesterday and a bunch of my tests started failing.</p>
<p>When I was running under 2.1.1, the test server was running on port 3000 so I had a HOST_DOMAIN variable that included the port - HOST_DOMAIN = "localhost.tst:3000". This is so my assert_redirected_to's would succeed.</p>
<p>Now, however, it seems that the test server is running on port 80, so the port in HOST_DOMAIN is causing tests to fail. </p>
<p>There's no specific reason I'm keeping the port in HOST_DOMAIN. I more want to know whether something in Rails 2.3 changed the port the test server runs on and where I can read more about why. I've searched a ton and can't find anything, so I'm going to my go-to place to ask development questions :)</p>
<p>Thanks in advance.</p>
| <p>Test request use "test.host", which would be port 80.
You can write</p>
<pre><code>@request.host = 'www.example.com'
@request.port = 3000
</code></pre>
<p><a href="http://lists.rubyonrails.org/pipermail/rails/2006-April/030204.html" rel="nofollow">http://lists.rubyonrails.org/pipermail/rails/2006-April/030204.html</a></p>
|
How can I show the numeric virtual keyboard on the Blackberry Storm? <p>I'm having some difficulty showing the virtual keyboard I want for the Blackberry Storm. I have an option to toggle the keyboard's visibility on a certain screen. Whenever the user types a number, it's handled by the screen, rather than any particular field (there are no textfields on this screen). This much works fine. I can show and hide the keyboard when the user chooses to.</p>
<p>My question is this: How do I make the keyboard that shows up the same as what would appear had the focus been on a BasicEditField with a numeric filter applied, without using a BasicEditField for the input?</p>
| <p>I don't think BlackBerry has exposed any APIs to allow for programmatic control over the type of virtual keyboard that is shown. I seem to remember reading about it in the BB forums (although unfortunately I can't find it now).</p>
<p>One thing you could try doing is using a BasicEditField with a numeric field, but place it offscreen so that it isn't visible. When you want to capture numeric input from the user, put focus on that element. I haven't tried this, it's just a thought.</p>
|
Store a collection of values in a config file <p>In a .Net 3.5 (Windows) service, I would like to store a small collection of values in the config file. Basically, I need to allow admins to add and remove values from this small collection. What do I need to add to the config file to store a collection of small values, and how can I read the collection in C#? </p>
<p>To clarify, the collection I am looking for is data like this:</p>
<pre><code><Illegal Characters>
<CustomCollection value="?"/>
<CustomCollection value="#"/>
<CustomCollection value=","/>
</Illegal Characters>
</code></pre>
| <p>There's a good article on creating a custom configuration section handler that loads the values as a list <a href="http://www.dotneat.net/2007/10/16/StoringACollectionOnYourAppconfigUsingSectionHandlers.aspx" rel="nofollow">here</a>.</p>
<p>Basically your <code>IConfigurationSectionHandler</code>'s Create method should look something like this:</p>
<pre><code>public object Create(object parent, object configContext, XmlNode section)
{
IList<string> illegal = new List<string>();
XmlNodeList processesNodes= section.SelectNodes("CustomCollection");
foreach (XmlNode child in processesNodes)
{
illegal.Add(child.Attributes["value"].InnerText);
}
return illegal;
}
</code></pre>
|
Rewriting C++ methods in C <p>How can I make equivalents to these methods in C? I read somewhere that they could be "replaced with functions that take a structure pointer as the first parameter," but I'm not sure how to do this, if that is the right thing to do.</p>
<pre><code>struct SCustomKeys
{
struct SCustomKey Save[10];
struct SCustomKey Load[10];
struct SCustomKey Slot[10];
struct SCustomKey PrintScreen;
struct SCustomKey LastItem; // dummy, must be last
//--methods--
struct SCustomKey &key(int i) { return ((SCustomKey*)this)[i]; }
struct SCustomKey const &key(int i) const { return ((SCustomKey*)this)[i]; }
};
</code></pre>
<p>Here's an example of how they are used:</p>
<pre><code>void ZeroCustomKeys (SCustomKeys *keys)
{
int i = 0;
SetLastCustomKey(&keys->LastItem);
while (!IsLastCustomKey(&keys->key(i))) {
keys->key(i).key = 0;
keys->key(i).modifiers = 0;
i++;
};
}
</code></pre>
<p>More context: <a href="http://pastebin.com/m649210e8" rel="nofollow">http://pastebin.com/m649210e8</a></p>
<p>Thanks for the help. I haven't been able to the suggested replacement for the C++ method working with this function yet though. Any ideas on how to approach this?</p>
<pre><code>void InitCustomKeys (struct SCustomKeys *keys)
{
UINT i = 0;
SetLastCustomKey(&keys->LastItem);
while (!IsLastCustomKey(&keys->key(i))) {
SCustomKey &key = keys->key(i);
key.key = 0;
key.modifiers = 0;
key.handleKeyDown = NULL;
key.handleKeyUp = NULL;
key.page = NUM_HOTKEY_PAGE;
key.param = 0;
i++;
};
//an example key
keys->PrintScreen.handleKeyDown = HK_PrintScreen;
keys->PrintScreen.code = "PrintScreen";
keys->PrintScreen.name = L"Print Screen";
keys->PrintScreen.page = HOTKEY_PAGE_MAIN;
keys->PrintScreen.key = VK_PAUSE;
}
</code></pre>
<p>And the new function I'm trying now is:</p>
<pre><code> struct SCustomKey* key(struct SCustomKeys *scs, int i) {
return &(((SCustomKey*)scs)[i]);
}
</code></pre>
| <p>Basically, instead of having a member function like:</p>
<pre><code>struct SCustomKey &key(int i) { return ((SCustomKey*)this)[i]; }
</code></pre>
<p>You will need to rewrite this as a function that takes a pointer to a SCustomKeys as it's first argument.</p>
<p>The function will look like:</p>
<pre><code>SCustomKey* key(SCustomKeys* customKeys, int i)
{ return ((SCustomKey*)(customKeys)+i); }
</code></pre>
<p>This should provide you with a pointer to the element you are trying to access.</p>
|
AS2 FLA Component with embeded classes <p>I'm trying to create an AS2 component which is easily skinnable.</p>
<p>I create an FLA component by creating a mc with some assets > component definition > link it to MyClass, and drop the fla into the Components dir. If I then drag the component into a new fla and try to render, it obviously throws the error that it can't find MyClass. I'd rather not provide the src files separately.</p>
<p>I've tried following some walk-throughs that described using the componentShim, but it seemed like that was only for AS3. </p>
<p>Any suggestions ?</p>
<p>TIA!</p>
| <p>It seems to me you're trying to create a compiled clip (SWC). You can find some Adobe documentation <a href="http://livedocs.adobe.com/flash/mx2004/main%5F7%5F2/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Flash%5FMX%5F2004&file=00003108.html#1140637" rel="nofollow">here</a>, but I'd rather go for <a href="http://www.communitymx.com/content/article.cfm?page=1&cid=DC2C0" rel="nofollow">this tutorial</a>. Seems to be more straight forward and easier to understand.</p>
|
SQL Query to Collapse Duplicate Values By Date Range <p>I have a table with the following structure: ID, Month, Year, Value with values for one entry per id per month, most months have the same value.</p>
<p>I would like to create a view for that table that collapses the same values like this: ID, Start Month, End Month, Start Year, End Year, Value, with one row per ID per value.</p>
<p>The catch is that if a value changes and then goes back to the original, it should have two rows in the table</p>
<p>So:</p>
<ul>
<li>100 1 2008 80</li>
<li>100 2 2008 80</li>
<li>100 3 2008 90</li>
<li>100 4 2008 80</li>
</ul>
<p>should produce</p>
<ul>
<li>100 1 2008 2 2008 80</li>
<li>100 3 2008 3 2008 90</li>
<li>100 4 2008 4 2008 80</li>
</ul>
<p>The following query works for everything besides this special case, when the value returns to the original.</p>
<pre><code>select distinct id, min(month) keep (dense_rank first order by month)
over (partition by id, value) startMonth,
max(month) keep (dense_rank first order by month desc) over (partition
by id, value) endMonth,
value
</code></pre>
<p>Database is Oracle</p>
| <p>I'm going to develop my solution incrementally, decomposing each transformation into a view. This both helps explain what's being done, and helps in debugging and testing. It's essentially applying the principle of functional decomposition to database queries.</p>
<p>I'm also going to do it without using Oracle extensions, with SQL that ought to run on any modern RBDMS. So no keep, over, partition, just subqueries and group bys. (Inform me in the comments if it doesn't work on your RDBMS.)</p>
<p>First, the table, which since I'm uncreative, I'll call month_value. Since the id is not actually a unique id, I'll call it "eid". The other columns are "m"onth, "y"ear, and "v"alue:</p>
<pre><code>create table month_value(
eid int not null, m int, y int, v int );
</code></pre>
<p>After inserting the data, for two eids, I have:</p>
<pre><code>> select * from month_value;
+-----+------+------+------+
| eid | m | y | v |
+-----+------+------+------+
| 100 | 1 | 2008 | 80 |
| 100 | 2 | 2008 | 80 |
| 100 | 3 | 2008 | 90 |
| 100 | 4 | 2008 | 80 |
| 200 | 1 | 2008 | 80 |
| 200 | 2 | 2008 | 80 |
| 200 | 3 | 2008 | 90 |
| 200 | 4 | 2008 | 80 |
+-----+------+------+------+
8 rows in set (0.00 sec)
</code></pre>
<p>Next, we have one entity, the month, that's represented as two variables. That should really be one column (either a date or a datetime, or maybe even a foreign key to a table of dates), so we'll make it one column. We'll do that as a linear transform, such that it sorts the same as (y, m), and such that for any (y,m) tuple there is one and only value, and all values are consecutive:</p>
<pre><code>> create view cm_abs_month as
select *, y * 12 + m as am from month_value;
</code></pre>
<p>That gives us:</p>
<pre><code>> select * from cm_abs_month;
+-----+------+------+------+-------+
| eid | m | y | v | am |
+-----+------+------+------+-------+
| 100 | 1 | 2008 | 80 | 24097 |
| 100 | 2 | 2008 | 80 | 24098 |
| 100 | 3 | 2008 | 90 | 24099 |
| 100 | 4 | 2008 | 80 | 24100 |
| 200 | 1 | 2008 | 80 | 24097 |
| 200 | 2 | 2008 | 80 | 24098 |
| 200 | 3 | 2008 | 90 | 24099 |
| 200 | 4 | 2008 | 80 | 24100 |
+-----+------+------+------+-------+
8 rows in set (0.00 sec)
</code></pre>
<p>Now we'll use a self-join in a correlated subquery to find, for each row, the earliest successor month in which the value changes. We'll base this view on the previous view we created:</p>
<pre><code>> create view cm_last_am as
select a.*,
( select min(b.am) from cm_abs_month b
where b.eid = a.eid and b.am > a.am and b.v <> a.v)
as last_am
from cm_abs_month a;
> select * from cm_last_am;
+-----+------+------+------+-------+---------+
| eid | m | y | v | am | last_am |
+-----+------+------+------+-------+---------+
| 100 | 1 | 2008 | 80 | 24097 | 24099 |
| 100 | 2 | 2008 | 80 | 24098 | 24099 |
| 100 | 3 | 2008 | 90 | 24099 | 24100 |
| 100 | 4 | 2008 | 80 | 24100 | NULL |
| 200 | 1 | 2008 | 80 | 24097 | 24099 |
| 200 | 2 | 2008 | 80 | 24098 | 24099 |
| 200 | 3 | 2008 | 90 | 24099 | 24100 |
| 200 | 4 | 2008 | 80 | 24100 | NULL |
+-----+------+------+------+-------+---------+
8 rows in set (0.01 sec)
</code></pre>
<p>last_am is now the "absolute month" of the first (earliest) month (after the month of the current row) in which the value, v, changes. It's null where there is no later month, for that eid, in the table.</p>
<p>Since last_am is the same for all months leading up to the change in v (which occurs at last_am), we can group on last_am and v (and eid, of course), and in any group, the min(am) is the absolute month of the <em>first</em> consecutive month that had that value: </p>
<pre><code>> create view cm_result_data as
select eid, min(am) as am , last_am, v
from cm_last_am group by eid, last_am, v;
> select * from cm_result_data;
+-----+-------+---------+------+
| eid | am | last_am | v |
+-----+-------+---------+------+
| 100 | 24100 | NULL | 80 |
| 100 | 24097 | 24099 | 80 |
| 100 | 24099 | 24100 | 90 |
| 200 | 24100 | NULL | 80 |
| 200 | 24097 | 24099 | 80 |
| 200 | 24099 | 24100 | 90 |
+-----+-------+---------+------+
6 rows in set (0.00 sec)
</code></pre>
<p>Now this is the result set we want, which is why this view is called cm_result_data. All that's lacking is something to transform absolute months back to (y,m) tuples.</p>
<p>To do that, we'll just join to the table month_value. </p>
<p>There are only two problems:
1) we want the month <em>before</em> last_am in our output, and
2) we have nulls where there is no next month in our data; to met the OP's specification, those should be single month ranges.</p>
<p>EDIT: These could actually be longer ranges than one month, but in every case they mean we need to find the latest month for the eid, which is:</p>
<pre><code>(select max(am) from cm_abs_month d where d.eid = a.eid )
</code></pre>
<p>Because the views decompose the problem, we could add in this "end cap" month earlier, by adding another view, but I'll just insert this into the coalesce. Which would be most efficient depends on how your RDBMS optimizes queries. </p>
<p>To get month before, we'll join (cm_result_data.last_am - 1 = cm_abs_month.am)</p>
<p>Wherever we have a null, the OP wants the "to" month to be the same as the "from" month, so we'll just use coalesce on that: coalesce( last_am, am). Since last eliminates any nulls, our joins don't need to be outer joins.</p>
<pre><code>> select a.eid, b.m, b.y, c.m, c.y, a.v
from cm_result_data a
join cm_abs_month b
on ( a.eid = b.eid and a.am = b.am)
join cm_abs_month c
on ( a.eid = c.eid and
coalesce( a.last_am - 1,
(select max(am) from cm_abs_month d where d.eid = a.eid )
) = c.am)
order by 1, 3, 2, 5, 4;
+-----+------+------+------+------+------+
| eid | m | y | m | y | v |
+-----+------+------+------+------+------+
| 100 | 1 | 2008 | 2 | 2008 | 80 |
| 100 | 3 | 2008 | 3 | 2008 | 90 |
| 100 | 4 | 2008 | 4 | 2008 | 80 |
| 200 | 1 | 2008 | 2 | 2008 | 80 |
| 200 | 3 | 2008 | 3 | 2008 | 90 |
| 200 | 4 | 2008 | 4 | 2008 | 80 |
+-----+------+------+------+------+------+
</code></pre>
<p>By joining back we get the output the OP wants.</p>
<p>Not that we have to join back. As it happens, our absolute_month function is bi-directional, so we can just recalculate the year and offset month from it.</p>
<p>First, lets take care of adding the "end cap" month:</p>
<pre><code>> create or replace view cm_capped_result as
select eid, am,
coalesce(
last_am - 1,
(select max(b.am) from cm_abs_month b where b.eid = a.eid)
) as last_am, v
from cm_result_data a;
</code></pre>
<p>And now we get the data, formatted per the OP:</p>
<pre><code>select eid,
( (am - 1) % 12 ) + 1 as sm,
floor( ( am - 1 ) / 12 ) as sy,
( (last_am - 1) % 12 ) + 1 as em,
floor( ( last_am - 1 ) / 12 ) as ey, v
from cm_capped_result
order by 1, 3, 2, 5, 4;
+-----+------+------+------+------+------+
| eid | sm | sy | em | ey | v |
+-----+------+------+------+------+------+
| 100 | 1 | 2008 | 2 | 2008 | 80 |
| 100 | 3 | 2008 | 3 | 2008 | 90 |
| 100 | 4 | 2008 | 4 | 2008 | 80 |
| 200 | 1 | 2008 | 2 | 2008 | 80 |
| 200 | 3 | 2008 | 3 | 2008 | 90 |
| 200 | 4 | 2008 | 4 | 2008 | 80 |
+-----+------+------+------+------+------+
</code></pre>
<p>And there's the data the OP wants. All in SQL that should run on any RDBMS, and is decomposed into simple, easy to understand and easy to test views.</p>
<p>Is is better to rejoin or to recalculate? I'll leave that (it's a trick question) to the reader. </p>
<p>(If your RDBMS doesn't allow group bys in views, you'll have to join first and then group, or group and then pull in the month and year with correlated subqueries. This is left as an exercise for the reader.)</p>
<p><hr /></p>
<p>Jonathan Leffler asks in the comments, </p>
<blockquote>
<p>What happens with your query if there
are gaps in the data (say there's an
entry for 2007-12 with value 80, and
another for 2007-10, but not one for
2007-11? The question isn't clear what
should happen there.</p>
</blockquote>
<p>Well, you're exactly right, the OP doesn't specify. Perhaps there's an (unmentioned) pre-condition that there are no gaps. In the absence of a requirement, we shouldn't try to code around something that might not be there. But, the fact is, gaps make the "joining back" strategy fail; the "recalculate" strategy doesn't fail under those conditions. I'd say more, but that would reveal the trick in the trick question I alluded to above.</p>
|
jQuery dialog theme and style <p>How do I change the background color of the title bar of a jQuery dialog?</p>
<p>I have looked at the themeroller but it does not seem to work for me.</p>
<p>Thanks</p>
| <p>You can change it by modifying the ui-dialog-titlebar CSS class, but I highly recommend you to use the <a href="http://jqueryui.com/themeroller/">ThemeRoller tool</a>.</p>
<p>See also:</p>
<ul>
<li><a href="http://docs.jquery.com/UI/Dialog/Theming">UI/Dialog/Theming</a></li>
<li><a href="http://docs.jquery.com/UI/Theming/API">UI/Theming/API</a></li>
</ul>
|
Form Styling with SPAN text instead of input or select controls <p>I've got CSS that formats labels above form input elements and I'd like to replace the input elements with text from the database if I'm just displaying read-only data.</p>
<p>No matter what I do, changing the input fields to a span or asp:label will not properly render the label above the text.</p>
<p>I'm using this CSS:</p>
<pre><code>div.formRow {
padding: 2px 0px;
}
span.formItem {
display: inline-block;
position: relative;
padding: 0px 5px;
}
span.formItem label {
position: absolute;
left: 5px;
top: 0px;
}
span.formItem input, span.formItem select {
margin-top: 20px;
}
</code></pre>
| <p>I'm guessing you need to add <code>display: block</code> to the input field replacement spans.</p>
|
Why doesn't my site work in IE6 or IE7? <p>For some reason my site <a href="http://tom.hsc.be" rel="nofollow">http://tom.hsc.be</a> displays a "Cannot display this message" error in those browsers while working correctly in Firefox, Opera, Safari and IE8.</p>
<p>It looks like this: <a href="http://www.reviewsaurus.com/images/pagedisplay.png" rel="nofollow">http://www.reviewsaurus.com/images/pagedisplay.png</a></p>
<p>This document was successfully checked as XHTML 1.0 Transitional!</p>
<p><strong>Found the problem</strong>:</p>
<p>Was using the following procedures to remove unnecessary characters, seems to be wrong though.</p>
<pre><code><?php
function callback($buffer)
{
$holdit=$buffer;
$holdit=str_replace(" ", " ", $holdit); // tab
$holdit=str_replace(" ", " ", $holdit); // double space
$holdit=str_replace("\n", " ", $holdit); // new line
$holdit=str_replace("\r", " ", $holdit); // new line
$holdit = eregi_replace("<!--[^>]*-->"," ",$holdit); // comment
return $holdit;
}
ob_start("ob_gzhandler");
ob_start("callback");
?>
</code></pre>
<p>Seems I don't need that function either, it is faster without it.<br />
(I should probably have opted for a single eregi_replace too)</p>
<p>Thank you everyone, I like Stack Overflow. :-)</p>
| <p>It doesn't have anything to do with HTML errors. The worst that can do is show a garbled or blank page.</p>
<p>There is some sort of server misconfiguration going on of WordPress and the <code>gzip</code> Content-Encoding.</p>
<p><a href="http://tom.hsc.be/" rel="nofollow">http://tom.hsc.be/</a> doesn't work in IE, but <a href="http://tom.hsc.be/index.php" rel="nofollow">http://tom.hsc.be/index.php</a> loads just fine. Inspecting the raw HTTP Response (using <a href="http://www.fiddler2.com/fiddler2/" rel="nofollow">Fiddler2</a>), the difference between the two responses is that on the request to <code>/</code>, WordPress (presumably) adds the following text to the gzipped HTTP response body:</p>
<pre><code><!-- Page not cached by WP Super Cache. No closing HTML tag. Check your theme. -->
</code></pre>
<p>Because of that addition to the gzipped content, it's no longer a proper gzip stream, and IE6/7 can't ungzip it.</p>
<p>Other browsers probably have better error handling, so they can handle the error just fine.</p>
<p>I don't know how you can fix that problem, but a <a href="http://www.google.com/search?q=site:wordpress.org+%22Page+not+cached+by+WP+Super+Cache.+No+closing+HTML+tag.+Check+your+theme.%22" rel="nofollow">Google search for that piece of text turns up a few hits on wordpress.org at least</a>.</p>
|
sorting and paging with gridview asp.net <p>I'm trying to get a gridview to sort and page manually with no success.</p>
<p>The problem is that when a user clicks the column they want to sort, it sorts that page, but doesn't sort the datasource (dataview) behind the gridview. So when they progress to a different page, their sort is lost. Pretty much I'm looking for a sort that will actually sort the datasource behind the gridview. Here is what I have so far:</p>
<pre><code>protected void GridView_OnSort(object sender, GridViewSortEventArgs e)
{
String sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
DataView myDataView = new DataView(mybll.GetItemsOrdered());
myDataView.Sort = sortExpression + " DESC";
GridView.DataSource = myDataView;
GridView.DataBind();
}
else
{
DataView myDataView = new DataView(mybll.GetItemsOrdered());
myDataView.Sort = sortExpression + " ASC";
GridView.DataSource = myDataView;
GridView.DataBind();
}
}
</code></pre>
<p>Any help would be appreciated. Thanks.</p>
| <p>Save your sorting order in a ViewState.</p>
<pre><code>private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression,string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
</code></pre>
<p>Why you don't want to use existing sorting functionality? You can always customize it.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/hwf94875.aspx">Sorting Data in a GridView Web Server Control</a> at MSDN</p>
<p>Here is an example with customization: </p>
<p><a href="http://www.netomatix.com/development/GridViewSorting.aspx">http://www.netomatix.com/development/GridViewSorting.aspx</a></p>
|
Making a template parameter a friend? <p>Example:</p>
<pre><code>template<class T>
class Base {
public:
Base();
friend class T;
};
</code></pre>
<p>Now this doesn't work... Is there a way of doing this?</p>
<p>I'm actually trying to make a general class sealer like this:</p>
<pre><code>class ClassSealer {
private:
friend class Sealed;
ClassSealer() {}
};
class Sealed : private virtual ClassSealer
{
// ...
};
class FailsToDerive : public Sealed
{
// Cannot be instantiated
};
</code></pre>
<p>I found this example on this site somewhere but I can't find it... (<a href="http://stackoverflow.com/questions/656224/when-should-i-use-c-private-inheritance/656523#656523">here</a>)</p>
<p>I know there are <a href="http://www.gamedev.net/reference/programming/features/cppseal/">other ways</a> of doing this but just now I'm curious if you actually can do something like this.</p>
| <p>It is explicitly disallowed in the standard, even if some versions of VisualStudio do allow it.</p>
<p>C++ Standard 7.1.5.3 Elaborated type specifiers, paragraph 2</p>
<blockquote>
<p>3.4.4 describes how name lookup proceeds for the identifier in an
elaborated-type-specifier. If the
identifier resolves to
a class-name or enum-name,
the elaborated-type-specifier introduces
it into the declaration the same
way a simple-type-specifier introduces
its type-name. If the identifier resolves
to a typedef-name or a
template type-parameter,
the elaborated-type-specifier is
ill-formed. [Note: this implies that,
within a class template with a
template type-parameter T, the
declaration <em>friend class T</em>; is
ill-formed. ]</p>
</blockquote>
<p>I recognize the code above as a pattern to seal (disallow the extension of) a class. There is another solution, that does not really block the extension but that will flag unadvertidly extending from the class. As seen in <a href="http://stlab.adobe.com/group__adobe__final.html">ADOBE Source Library</a>:</p>
<pre><code>namespace adobe { namespace implementation {
template <class T>
class final
{
protected:
final() {}
};
}}
#define ADOBE_FINAL( X ) private virtual adobe::implementation::final<T>
</code></pre>
<p>with the usage:</p>
<pre><code>class Sealed : ADOBE_FINAL( Sealed )
{//...
};
</code></pre>
<p>While it allows extension if you really force it:</p>
<pre><code>class SealBreaker : public Sealed, ADOBE_FINAL( Sealed )
{
public:
SealBreaker() : adobe::implementation::final<Sealed>(), Sealed() {}
};
</code></pre>
<p>It will restrict users from mistakenly do it.</p>
<p><strong>EDIT</strong>: </p>
<p>The upcoming C++11 standard does allow you to befriend a type argument with a slightly different syntax:</p>
<pre><code>template <typename T>
class A {
// friend class T; // still incorrect: elaborate type specifier
friend T; // correct: simple specifier, note lack of "class"
};
</code></pre>
|
Dividing lines between Session Object, User Object, and Login Controller <p>I'm developing my own PHP framework, and I'm trying to do things more "by the book".</p>
<p>I want to build login system. I have done this plenty of times, but now I just want to confirm/get some feedback on a system.</p>
<p>I know we need...</p>
<ul>
<li>A Session Object</li>
<li>A User Object</li>
<li>A Login Controller</li>
</ul>
<p>What my question is, is who holds what power?</p>
<p>Here's my thought - when you submit your un/pw, it obviously goes to the Login Controller. We need to look up that un/pw combo in the user database, and therefore I feel as if that should be done in the in the user object ... $User->authenticate($un, $pw). </p>
<p>All that should do i return true or false. Then the LoginController should tell the Session object to create a session ... $session->create(). But apart of me wonders if the User and Session object should be a bit closer knit, and not rely on a Controller.</p>
<p>Looking for opinions, thanks in advance.</p>
| <p>In my opinion, the user object shouldn't know about persistence (session) or the application (controllers). All it should care for is representing a user and handling user-related functions like authenticate.</p>
<p>The controller is all about application logic, and the session is part of the application. I feel like it's the controllers task to open the session and store the user object for later usage, once authenticated.</p>
<p>P.s. Did you publish your framework? Github it! :-D</p>
|
How do I generate multi-word terms recursively? <p>Say I have a string of words: <code>'a b c d e f'</code>. I want to generate a list of multi-word terms from this string.</p>
<p>Word order matters. The term <code>'f e d'</code> shouldn't be generated from the above example.</p>
<p><strong>Edit:</strong> Also, words should not be skipped. <code>'a c'</code>, or <code>'b d f'</code> shouldn't be generated.</p>
<p><strong>What I have right now:</strong></p>
<pre><code>doc = 'a b c d e f'
terms= []
one_before = None
two_before = None
for word in doc.split(None):
terms.append(word)
if one_before:
terms.append(' '.join([one_before, word]))
if two_before:
terms.append(' '.join([two_before, one_before, word]))
two_before = one_before
one_before = word
for term in terms:
print term
</code></pre>
<p><strong>Prints:</strong></p>
<pre><code>a
b
a b
c
b c
a b c
d
c d
b c d
e
d e
c d e
f
e f
d e f
</code></pre>
<p>How would I make this a recursive function so that I can pass it a variable maximum number of words per term?</p>
<p><strong>Application:</strong></p>
<p>I'll be using this to generate multi-word terms from readable text in HTML documents. The overall goal is a latent semantic analysis of a large corpus (about two million documents). This is why keeping word order matters (Natural Language Processing and whatnot).</p>
| <p>This isn't recursive, but I think it does what you want. </p>
<pre><code>doc = 'a b c d e f'
words = doc.split(None)
max = 3
for index in xrange(len(words)):
for n in xrange(max):
if index + n < len(words):
print ' '.join(words[index:index+n+1])
</code></pre>
<p>And here's a recursive solution:</p>
<pre><code>def find_terms(words, max_words_per_term):
if len(words) == 0: return []
return [" ".join(words[:i+1]) for i in xrange(min(len(words), max_words_per_term))] + find_terms(words[1:], max_words_per_term)
doc = 'a b c d e f'
words = doc.split(None)
for term in find_terms(words, 3):
print term
</code></pre>
<p>Here's the recursive function again, with some explaining variables and comments.</p>
<pre><code>def find_terms(words, max_words_per_term):
# If there are no words, you've reached the end. Stop.
if len(words) == 0:
return []
# What's the max term length you could generate from the remaining
# words? It's the lesser of max_words_per_term and how many words
# you have left.
max_term_len = min(len(words), max_words_per_term)
# Find all the terms that start with the first word.
initial_terms = [" ".join(words[:i+1]) for i in xrange(max_term_len)]
# Here's the recursion. Find all of the terms in the list
# of all but the first word.
other_terms = find_terms(words[1:], max_words_per_term)
# Now put the two lists of terms together to get the answer.
return initial_terms + other_terms
</code></pre>
|
Is there a better trivial Python WebDAV server code snippet than this? <p>Does anyone have a better code snippet for a trivial Python <a href="http://en.wikipedia.org/wiki/WebDAV" rel="nofollow">WebDAV</a> server? The code below (which is cobbled together from some Google search results) appears to work under Python 2.6, but I wonder if someone has something they have used before, a <em>little</em> more tested and complete. I'd prefer a stdlib-only snippet over a third-party package. It is for some test code to hit so does not have to be production-worthy.</p>
<pre><code>import httplib
import BaseHTTPServer
class WebDAV(BaseHTTPServer.BaseHTTPRequestHandler):
"""
Ultra-simplistic WebDAV server.
"""
def do_PUT(self):
path = os.path.normpath(self.path)
if os.path.isabs(path):
path = path[1:] # safe assumption due to normpath above
directory = os.path.dirname(path)
if not os.path.isdir(directory):
os.makedirs(directory)
content_length = int(self.headers['Content-Length'])
with open(path, "w") as f:
f.write(self.rfile.read(content_length))
self.send_response(httplib.OK)
def server_main(server_class=BaseHTTPServer.HTTPServer,
handler_class=WebDAV):
server_class(('', 9231), handler_class).serve_forever()
</code></pre>
| <p>Or try PyFileServer, which I picked up for further develpment by the name WsgiDAV (<a href="http://code.google.com/p/wsgidav/" rel="nofollow">http://code.google.com/p/wsgidav/</a>)<br>
<strong>Edit:</strong> the project has moved to GitHub (<a href="https://github.com/mar10/wsgidav" rel="nofollow">https://github.com/mar10/wsgidav</a>)</p>
|
Building a highly modular business application with WPF? <p>I'm fleshing out a WPF business application in my head and one thing that sparked my interest was how I should handle making it incredibly modular. For example, my main application would simply contain the basics to start the interface, load the modules, connect to the server, etc. These modules, in the form of class libraries, would contains their own logic and WPF windows. Modules could define their own resource dictionaries and all pull from the main application's resource dictionary for common brushes and such.</p>
<p>What's the best way to implement a system of this nature? How should the main interface be built so that the modules it loads can alter virtually any aspect of its user interface and logic?</p>
<p>I realize it's a fairly vague question, but I'm simply looking for general input and brainstorming.</p>
<p>Thanks!</p>
| <p>Check out <a href="http://msdn.microsoft.com/en-us/library/cc707819.aspx" rel="nofollow">Composite Client Application Guidance</a></p>
<p>The Composite Application Library is designed to help architects and developers achieve the following objectives:</p>
<p>Create a complex application from modules that can be built, assembled, and, optionally, deployed by independent teams using WPF or Silverlight. </p>
<p>Minimize cross-team dependencies and allow teams to specialize in different areas, such as user interface (UI) design, business logic implementation, and infrastructure code development. </p>
<p>Use an architecture that promotes reusability across independent teams. </p>
<p>Increase the quality of applications by abstracting common services that are available to all the teams. </p>
<p>Incrementally integrate new capabilities. </p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.