input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Freebase MQL filter where value != null? <p>I'm trying to write an MQL query that filters out null values.</p>
<p>The query I have now (can be executed using the <a href="http://www.freebase.com/tools/queryeditor">MQL Query Editor</a>):</p>
<pre><code>[
{
"/common/topic/image" : [
{
"id" : null
}
],
"article" : [
{
"content" : null
}
],
"name" : "bill gates",
"type" : "/common/topic"
}
]
</code></pre>
<p>The results I am getting:</p>
<pre><code>[
{
"/common/topic/image" : [
{
"id" : "/guid/9202a8c04000641f8000000004fb4c01"
},
{
"id" : "/wikipedia/images/commons_id/4486276"
}
],
"article" : [
{
"content" : null
},
{
"content" : "/guid/9202a8c04000641f800000000903535d"
}
],
"name" : "Bill Gates",
"type" : "/common/topic"
}
]
</code></pre>
<p>I'm trying to figure out how I can filter out the "content" : null match in the "article" array at query time. I looked through the MQL documentation but I didn't see a clear way to do this.</p>
| <p>To filter out articles that don't have any content assigned to them you'll have to expand the content id attribute and set the optional directive to false.</p>
<pre><code>[
{
"/common/topic/image" : [
{
"id" : null
}
],
"article" : [
{
"content" : {
"id" : null,
"optional" : false
}
}
],
"name" : "bill gates",
"type" : "/common/topic"
}
]
</code></pre>
<p>This will give you the following result:</p>
<pre><code>[
{
"/common/topic/image" : [
{
"id" : "/guid/9202a8c04000641f8000000004fb4c01"
},
{
"id" : "/wikipedia/images/commons_id/4486276"
}
],
"article" : [
{
"content" : {
"id" : "/guid/9202a8c04000641f800000000903535d"
}
}
],
"name" : "Bill Gates",
"type" : "/common/topic"
}
]
</code></pre>
<p>For more information about using the optional directive see the documentation <a href="http://mql.freebaseapps.com/ch03.html#optionaldirective">here</a>.</p>
|
ISNULL not working in TSQL Select <p>I have a TSQL SELECT that can return a null. I tried using ISNULL to replace it with 0 but for some reason it is not working. The table selecting from has the following columns:</p>
<ul>
<li>storeID --> int </li>
<li>penaltyPercent --> decimal(9,2) </li>
<li>penaltyDate --> dateTime</li>
</ul>
<pre class="lang-sql prettyprint-override"><code>SELECT ISNULL(penaltyPercent, 0.0) AS penaltyPercent
FROM dbo.Penalty
WHERE (penaltyDate = (SELECT MAX(penaltyDate) AS date
FROM dbo.Penalty AS Penalty_1
WHERE (penaltyDate <= @date) AND (storeID = @storeID))) AND
(storeID = @storeID)
</code></pre>
<p>When the date is before the first penalty date (when there should be 0 penalty), no result is returned. Not sure why this doesn't work. I have a work around but it is bugging me.</p>
<p>Here is a sample of the data being used:</p>
<pre><code>storeID penaltyDate penaltyPercent
182 10/1/2008 12:00:00 AM 0.020000
182 11/1/2008 12:00:00 AM 0.040000
182 12/1/2008 12:00:00 AM 0.070000
</code></pre>
| <p>When you say "When the date is before the first penalty date", do you mean when the value of <code>@date</code> is less than the value returned from this query?</p>
<pre><code>SELECT MIN(penaltyDate)
FROM Penalty
</code></pre>
<p>Because then your inner query is going to return null, and (if you're using ANSI nulls) this part will return false,</p>
<pre><code>WHERE (penaltyDate = ...
</code></pre>
<p>Because comparisons with null always return null. So instead of selecting one row with a null value, you're selecting no rows.</p>
<p>Addendum:</p>
<p>To confirm this is the problem, change your outer query's first line to </p>
<pre><code>SELECT ISNULL(MAX(penaltyPercent),0.0) AS penaltyPercent
</code></pre>
<p>It will work because of what I've described above.</p>
|
Need help with Converting Points to Shapes <p>below are a whole length of code i have copied from NEHE Production (Lesson 25)..
i was just trying to play around but seem to not able to change/convert each points into a individual spheres nor cylinder.. <br>somehow when i did my adjustment they are not arranged in the way they are suppose to and they won't rotate..<br>
i planed to add light in this tutorial later on as well..</p>
<p>thanks in advance for any help =]<br><br></p>
<pre><code>int InitGL(GLvoid)
{
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0);
glDepthFunc(GL_LESS);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
maxver=0;
objload("data/sphere.txt",&morph1);
objload("data/torus.txt",&morph2);
objload("data/Tube.txt",&morph3);
objallocate(&morph4,10300);
for(int i=0;i<10300;i++)
{
morph4.points[i].x=((float)(rand()%14000)/1000)-7;
morph4.points[i].y=((float)(rand()%14000)/1000)-7;
morph4.points[i].z=((float)(rand()%14000)/1000)-7;
}
objload("data/Tube.txt",&helper);
sour=dest=&morph1;
return TRUE;
}
void DrawGLScene(GLvoid)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(cx,cy,cz);
glRotatef(xrot,1,0,0);
glRotatef(yrot,0,1,0);
glRotatef(zrot,0,0,1);
xrot+=xspeed; yrot+=yspeed; zrot+=zspeed;
GLfloat tx,ty,tz;
VERTEX q;
glPointSize(2.0f);
//glBegin(GL_POINTS);
for(int i=0;i<morph3.verts;i++)
{
if(morph)
q=calculate(i);
else
q.x=q.y=q.z=0;
helper.points[i].x-=q.x;
helper.points[i].y-=q.y;
helper.points[i].z-=q.z;
tx=helper.points[i].x;
ty=helper.points[i].y;
tz=helper.points[i].z;
glColor3f(0,1,1);
glPushMatrix(); //i have modified this part onwards
gltranslaste(tx,ty,tz);
glutSolidSphere(2,6,6);
glPopMatrix();
/*glVertex3f(tx,ty,tz);
glColor3f(0,0.5f,1);
tx-=2*q.x; ty-=2*q.y; ty-=2*q.y;
glVertex3f(tx,ty,tz);
glColor3f(0,0,1);
tx-=2*q.x; ty-=2*q.y; ty-=2*q.y;
glVertex3f(tx,ty,tz);*/
}
//glEnd();
if(morph && step<=steps)
step++;
else
{
morph=FALSE; sour=dest; step=0;
}
}
</code></pre>
| <p>A good place to start is to replace glBegin(GL_POINTS) with glBegin(GL_TRIANGLES) or GL_QUADS or GL_POLYGONS.</p>
<p>See the help page on glBegin/End <a href="http://www.opengl.org/documentation/specs/man%5Fpages/hardcopy/GL/html/gl/begin.html" rel="nofollow">here</a>.</p>
|
Capturing the first frame of a video with WPF <p>I need to capture the first frame of a video uploaded on an asp.net website. I really would like to do this with WPF (if it's even possible), but if anyone knows an easier way, I am open to that too. </p>
<p>I have seen examples of this using MediaPlayer and RenderTargetBitmap in WPF, but each example assumes the video is accessible via a URI. In my scenario, I only have the file bytes and I do not want to store the video directly on the FS.</p>
<p><a href="http://blogs.msdn.com/delay/archive/2008/09/03/video-frame-grabbing-made-easy-how-to-quickly-capture-multiple-video-frames-with-wpf.aspx" rel="nofollow">http://blogs.msdn.com/delay/archive/2008/09/03/video-frame-grabbing-made-easy-how-to-quickly-capture-multiple-video-frames-with-wpf.aspx</a></p>
<p>Any help is greatly appreciated!</p>
| <p>I don't know that this is advisable at all, as it will more than likely require that you run a message pump of some kind, which is a really bad idea in an ASP.NET site.</p>
<p>Rather, I would use the DirectShow API to try and process the video. You <em>should</em> be able to stream the content as bytes using it, and you won't need a message loop to process the video.</p>
<p>You can access it through .NET using the DirectShow .NET wrapper, located here:</p>
<p><a href="http://directshownet.sourceforge.net/" rel="nofollow">http://directshownet.sourceforge.net/</a></p>
<p>And you will want to look at the Sample Grabber Example on MSDN:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms787867%28VS.85%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx</a></p>
<p>Mind you that you might not necessarily want the first frame, as with a number of videos, they can be black and not really be a good candidate for a thumbnail. Rather you might want to do what Vista does and look for the first non-black frame.</p>
|
Why does -[NSTextStorage replaceCharactersInRange: withAttributedString:] sometimes, sometimes not honor fonts in other character sets? <p>I'm trying to diagnose a problem in UKSyntaxColoredTextDocument 0.4 <a href="http://www.zathras.de/angelweb/blog-uksctd-oh-four.htm" rel="nofollow">http://www.zathras.de/angelweb/blog-uksctd-oh-four.htm</a> where text that actually lives in a different font than the one you have specified disappears as you type. (You can download and try out this cool utility to see this problem for yourself...)</p>
<p>Here's the background: This is some syntax coloring code that recolors as you type. It works great, but if you enter some characters that are not a part of the font set for that text view (e.g. Monaco, Helvetica) ... for instance, a symbol character or something in Japanese, which actually uses fonts like ZapfDingbatsITC or HiraKakuProN-W3 to display it, then those characters are not displayed as you type.</p>
<p>Let's say you have some text like this: fdsafd[â]sfdsâ¡[âââ][æ¥æ¬èª]...</p>
<p>If you paste that into the text field, and switch among syntax coloring from the popup, this invokes <code>oldRecolorRange:</code>, with this line:</p>
<pre><code>[[textView textStorage] replaceCharactersInRange: range withAttributedString: vString];
</code></pre>
<p>Here, things behave as I would expect. The ASCII text, the symbols, and the Japanese text are all visible. The value of [textView textStorage] starts out, and ends up, something like this: <i>(This is output of gdb; it's not showing the unicode characters, don't worry about that.)</i></p>
<pre>
df{
NSFont = "LucidaGrande 20.00 pt. P [] (0x001a3380) fobj=0x001a4970, spc=6.33";
}?{
NSFont = "ZapfDingbatsITC 20.00 pt. P [] (0x001ae720) fobj=0x001bb370, spc=5.56";
}fdsafd[{
NSFont = "LucidaGrande 20.00 pt. P [] (0x001a3380) fobj=0x001a4970, spc=6.33";
}?{
NSFont = "HiraKakuProN-W3 20.00 pt. P [] (0x001b59e0) fobj=0x001bb600, spc=6.66";
}]sfds[{
...
</pre>
<p>... even after setting the new value to be </p>
<pre>
dffdsafd[?]sfds[???][???] Nihddfdfffdfdd{
NSFont = "LucidaGrande 20.00 pt. P [] (0x001a3380) fobj=0x001a4970, spc=6.33";
}
</pre>
<p>In other words, the "foreign" fonts needed to display this string are preserved automatically somehow, even though the fonts are not specified in the replacement string.</p>
<p>However, when you type in one character at a time, a different call of <code>replaceCharactersInRange:withAttributedString:</code> in the method <code>recolorRange:</code> results in an attributed string that is <em>only</em> in the base font -- no foreign-character fonts have been added for us, so the characters out of the range of the main font are not visible at all!</p>
<pre>
dffdsafd[?]sfds[???][???] Nihddfdfffdfddx{
NSFont = "LucidaGrande 20.00 pt. P [] (0x001a3380) fobj=0x001a4970, spc=6.33";
}
</pre>
<p>Any idea why this method would be working one way in one circumstance and not in another? Is there some kind of switch that I can pass to give the <code>NSTextStorage</code>/<code>NSAttributedString</code> a hint that we want the text to display foreign characters?</p>
| <p>Try [[textView textStorage] fixFontAttributeInRange:range]; after the [[textView textStorage] replaceCharactersInRange: range withAttributedString: vString] in recolorRange:</p>
<p>I think the problem is editing the text storage again in response to processEditing, which is already the tail end of an edit. -[NSTextStorage processEditing] uses fixFontAttributeInRange:, but since you're trying to edit again, something is going wrong and the fix behavior is being dropped. </p>
<p>When you do it for the whole document, there is a normal beginEditing/endEditing/processEditing sequence which causes fixFontAttributeInRange: to be called happily.</p>
|
How do I make an http request using cookies on Android? <p>I'd like to make an http request to a remote server while properly handling cookies (eg. storing cookies sent by the server, and sending those cookies when I make subsequent requests). It'd be nice to preserve any and all cookies, but really the only one I care about is the session cookie.</p>
<p>With java.net, it appears that the preferred way to do this is using java.net.CookieHandler (abstract base class) and java.net.CookieManager (concrete implementation). Android has java.net.CookieHandler, but it does not seem to have java.net.CookieManager.</p>
<p>I could code it all by hand by inspecting http headers, but it seems like there must be an easier way.</p>
<p>What is the proper way to make http requests on Android while preserving cookies?</p>
| <p>It turns out that Google Android ships with Apache HttpClient 4.0, and I was able to figure out how to do it using the "Form based logon" example in the <a href="http://hc.apache.org/httpcomponents-client/examples.html">HttpClient docs</a>:</p>
<p><a href="http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/httpclient/src/examples/org/apache/http/examples/client/ClientFormLogin.java">http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/httpclient/src/examples/org/apache/http/examples/client/ClientFormLogin.java</a></p>
<p><hr /></p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class ClientFormLogin {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
"org=self_registered_users&" +
"goto=/portal/dt&" +
"gotoOnFail=/portal/dt?error=true");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
</code></pre>
|
How can I create a group footer in a WPF ListView ( GridView ) <p>I have a ListView that displays sales orders, and groups them by status. In WinForms I had a footer at the bottom of each group that displayed the Total sale price for each group, and I would like to do the same in WPF.</p>
<p>I have figured out how to group the orders, but I can't figure out how to create a footer.</p>
<p>This is my current group style:</p>
<pre><code><ListView.GroupStyle>
<GroupStyle HidesIfEmpty="True">
<GroupStyle.HeaderTemplate>
<DataTemplate>
<!--CollectionViewGroup.Name will be assigned the value of Status for that group.-->
<!--http://stackoverflow.com/questions/639809/how-do-i-group-items-in-a-wpf-listview-->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Path=Name}" HorizontalAlignment="Left" FontWeight="Bold" Foreground="Black"/>
<Line Grid.Column="1" Stroke="Black" X2="500" Fill="Black" VerticalAlignment="Center" />
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</code></pre>
| <p>If your looking for something like this:</p>
<p><img src="http://www.bendewey.com/code/GroupingSum.png" alt="WPF Grouping with Total Sums" /></p>
<p>Then you can use the Template property of the ContainerStyle for the GroupStyle. In this example I use a DockPanel, with the Grid you supplied Docked on the bottom and an ItemsPresenter filling the remainder. In addition in order to get the Items totaled you'd have to use a Converter, which is supplied at the bottom.</p>
<h2>Window.xaml</h2>
<pre><code><Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.Window3"
x:Name="Window"
Title="Window3"
xmlns:local="clr-namespace:WpfApplication1"
Width="640" Height="480">
<Window.Resources>
<local:MyDataSource x:Key="MyData" />
<CollectionViewSource x:Key="ViewSource" Source="{Binding Source={StaticResource MyData}, Path=Users}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Country" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Window.Resources>
<Grid x:Name="LayoutRoot">
<ListView ItemsSource="{Binding Source={StaticResource ViewSource}}">
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<DockPanel>
<Grid DockPanel.Dock="Bottom">
<Grid.Resources>
<local:TotalSumConverter x:Key="sumConverter" />
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<TextBlock Grid.Column="0" Text="Total: " FontWeight="Bold"/>
<TextBlock Grid.Column="0" Text="{Binding Path=Name}" />
</StackPanel>
<Line Grid.Column="1" Stroke="Black" X2="500" Fill="Black" VerticalAlignment="Center" />
<TextBlock Grid.Row="1" Grid.Column="1" HorizontalAlignment="Right" Text="{Binding Path=Items, Converter={StaticResource sumConverter}}" />
</Grid>
<ItemsPresenter />
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListView.GroupStyle>
<ListView.View>
<GridView>
<GridViewColumn Width="140" Header="Name" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Width="140" Header="Phone Number" DisplayMemberBinding="{Binding Phone}"/>
<GridViewColumn Width="140" Header="Country" DisplayMemberBinding="{Binding Country}" />
<GridViewColumn Width="140" Header="Total" DisplayMemberBinding="{Binding Total}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
</code></pre>
<h2>MyDataSource.cs</h2>
<pre><code>public class MyDataSource
{
public ObservableCollection<User> Users { get; set; }
public MyDataSource()
{
Users = new ObservableCollection<User>();
LoadDummyData();
}
private void LoadDummyData()
{
Users.Add(new User()
{
Name = "Frank",
Phone = "(122) 555-1234",
Country = "USA",
Total = 432
});
Users.Add(new User()
{
Name = "Bob",
Phone = "(212) 555-1234",
Country = "USA",
Total = 456
});
Users.Add(new User()
{
Name = "Mark",
Phone = "(301) 555-1234",
Country = "USA",
Total = 123
});
Users.Add(new User()
{
Name = "Pierre",
Phone = "+33 (122) 555-1234",
Country = "France",
Total = 333
});
Users.Add(new User()
{
Name = "Jacques",
Phone = "+33 (122) 555-1234",
Country = "France",
Total = 222
});
Users.Add(new User()
{
Name = "Olivier",
Phone = "+33 (122) 555-1234",
Country = "France",
Total = 444
});
}
}
</code></pre>
<h2>User.cs</h2>
<pre><code>public class User
{
public string Name { get; set; }
public string Phone { get; set; }
public string Country { get; set; }
public double Total { get; set; }
}
</code></pre>
<h2>TotalSumConverter.cs</h2>
<pre><code>public class TotalSumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var users = value as IEnumerable<object>;
if (users == null)
return "$0.00";
double sum = 0;
foreach (var u in users)
{
sum += ((User)u).Total;
}
return sum.ToString("c");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new System.NotImplementedException();
}
}
</code></pre>
|
Why doesn't git-svn use the Subversion repositories UUID instead of its URL <p>Relocating a git-svn mirror of a Subversion repository isn't trivial:</p>
<p><a href="http://stackoverflow.com/questions/268736/git-svn-whats-the-equivalent-to-svn-switch-relocate">git-svn: whatâs the equivalent to <code>svn switch ârelocate</code>?</a></p>
<p>So why doesn't git-svn use the repository's UUID instead of its URL in the git-svn-id? The UUID uniquely identifies the repository, so it seems a natural identifier to use and would handle relocatations much easier.</p>
| <p>The git wiki has the answer, use the first method documented here:</p>
<p><a href="https://git.wiki.kernel.org/index.php/GitSvnSwitch" rel="nofollow">https://git.wiki.kernel.org/index.php/GitSvnSwitch</a></p>
<p>I just tested it on a test repo and it seems to work.</p>
|
How do I consolidate entries from multiple employee blogs into a single RSS feed <p>Our current SharePoint environment has Mysites setup as separate site collections where users create their blogs. It is a real challenge to know these blogs indivdually and I usually grab the RSS feed the first time I visit and then susbcribe from within Outlook. To help out non-techies, we'd like to be able to consolidate the entries from some top (regular) bloggers on our portal into a single feed that can then be used to subscribe from Outlook or display on a page on the portal.</p>
<p>Any ideas on how to go about this would be much appreciated. Thank you for your time and have a great day.</p>
| <p>I would consolidate these top feeds into an <a href="http://en.wikipedia.org/wiki/OPML" rel="nofollow">OPML</a> file. Here's a <a href="http://www.scripting.com/feeds/top100.opml" rel="nofollow">great example</a>. <a href="http://office.microsoft.com/en-us/outlook/HA012299401033.aspx" rel="nofollow">Outlook</a> 2007 can parse this and add it as a a collection of feeds. </p>
<p>You could also write a quick web part to parse the OPML file and download the top <em>n</em> posts from each feed. Sahil Malik has already done this hard work and you could use his <a href="http://blah.winsmarts.com/2006-7-Sharepoint%5FWebparts%5FAS%5F-%5FWriting%5Fthe%5FWebParts%5F-%5FThe%5FOPMLEditor%5FWebPart.aspx" rel="nofollow">examples</a> as a jump off.</p>
|
call a number using skype in a webpage <p>I am trying to add a link or button to the webpage so that the user can call a number directly if the skype is installed. it seems the link is like </p>
<p>skyp:....?call....</p>
<p>but cannot find any sample or documents. thanks for your help.</p>
| <p>This is the format for the link:</p>
<pre><code><a href="skype:echo123?call">Click</a> (make a call to echo123)
</code></pre>
<p>It will work provided the visitor have Skype installed.</p>
<p>You can find all the options and an alternative javascript to redirect the user to download skype is he/she does not have Skype installed.</p>
<p><a href="http://dev.skype.com/skype-uri">http://dev.skype.com/skype-uri</a></p>
|
Mystery HAVING clause <p>Can anyone please explain the following HAVING clause from an Access database? How can Format with all '0' ever return a string of spaces?</p>
<pre><code>HAVING Format([PerNr],'0000000') <> ' '
</code></pre>
| <p>Possible if field value is set to spaces...</p>
<p>VBA:</p>
<pre><code>Dim x As String
x = " "
MsgBox "x = " & Format(x, "0000000") & " : Len(x) = " & Len(Format(x, "0000000"))
</code></pre>
|
Boolean logic failure <p>I am having a strange problem with boolean logic. I must be doing something daft, but I can't figure it out.
In the below code firstMeasure.isInvisibleArea is true and measureBuffer1 is nil.
Even though test1 is evaluating to NO for some reason it is still dropping into my if statement.
It works ok if I use the commented out line.
Any idea why this happens?</p>
<pre><code>BOOL firstVisible = firstMeasure.isInVisibleArea;
BOOL notFirstVisible = !(firstMeasure.isInVisibleArea);
BOOL measureBufferNil = measureBuffer1 == nil;
BOOL test1 = measureBuffer1 == nil && !firstMeasure.isInVisibleArea;
BOOL test2 = measureBufferNil && !firstVisible;
if (measureBuffer1 == nil && !firstMeasure.isInVisibleArea)
//if (measureBufferNil && !firstVisible)
{
//do some action
}
</code></pre>
<p><hr /></p>
<p>Update 1:</p>
<p>I isolated the problem to !firstMeasure.isInVisibleArea as I've entirely taken on the measureBuffer bit.
Inside isInVisible area is a small calculation (it doesn't modify anything though), but the calculation is using self.view.frame. I am going take this out of the equation as well and see what happens. My hunch is that self.view.frame is changing between the two calls to isInVisibleArea.</p>
<p><hr /></p>
<p>Update 2:
This is indeed the problem. I have added the answer in more detail below</p>
| <p>When in doubt, you should fully parenthesize. Without looking up the precedence rules, what I think what is happening is that = is getting higher precedence than == or &&. So try:</p>
<pre><code>BOOL test1 = ((measureBuffer1 == nil) && !firstMeasure.isInVisibleArea);
</code></pre>
|
Best practice for removing Database calls from MVC Controller classes <p>I have an Action method in an ASP.NET MVC Controller class that handles form posts from a fairly basic "create/edit a user" page. I'm new to MVC so I've been following code samples from various Microsoft tutorials, this is how the method looks currently:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post)]
public ViewResult Save([Bind(Prefix = "ServiceUser")]ServiceUser SUser)
{
if (SUser.ServiceUserId == 0) //new service user
ServiceUserHelper.AddServiceUser(SUser);
else //update to existing service user
{
using (ProjectDataContext db = DatabaseHelper.CreateContext())
{
this.UpdateModel(db.ServiceUsers.Single(su => su.ServiceUserId == SUser.ServiceUserId), "ServiceUser");
db.SubmitChanges();
}
}
//return a confirmation view
}
</code></pre>
<p>This works fine; however my instincts tell me that the 'ProjectDataContext...' code doesn't belong in the controller. If I were to move the Update functionality to an other class (in the way I have done with the Insert method), I'd lose the convenience of the Controller's UpdateModel() method, and probably end up having to do something quite verbose to read the existing entity, update its properties, and submit the changes.</p>
<p>So my question is, what is the best way to achieve this? Is there a method similar to UpdateModel() somewhere in LINQ that can merge two entities of the same type together before submitting?</p>
<p>Thanks.</p>
| <p>Most people will suggest using the "Repository Pattern" to move that data access code out of the controller (and to enable unit testing with mock objects instead of the real database).</p>
<p>Here are some places to read more:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/125453/implementation-example-for-repository-pattern-with-linq-to-sql-and-c">Implementation example for Repository pattern with Linq to Sql and C#</a></li>
<li><a href="http://aspnetmvcbook.s3.amazonaws.com/aspnetmvc-nerdinner_v1.pdf" rel="nofollow">Chapter 1 of Professional ASP.NET MVC</a> (Page 32)</li>
</ul>
<p><strong>Edit:</strong> </p>
<p>I highly recommend reading the entire Scott Guthrie chapter linked above. It has a wealth of good advice in it. That said, here are some relevant examples (excepted from the chapter)...</p>
<p>First, I generally like to have different actions for "Update" vs. "Add". Even if they are the same View to render the form, it generally feels cleaner to have different URLs for POSTing an edit vs POSTing a new record. So, here is what the repository pattern in use looks like in a controller's update action:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues)
{
//get the current object from the database using the repository class
Dinner dinner = dinnerRepository.GetDinner(id);
try
{
//update the object with the values submitted
UpdateModel(dinner);
//save the changes
dinnerRepository.Save();
//redirect the user back to the read-only action for what they just edited
return RedirectToAction("Details", new { id = dinner.DinnerID });
}
catch
{
//exception occurred, probably from UpdateModel, so handle the validation errors
// (read the full chapter to learn what this extention method is)
ModelState.AddRuleViolations(dinner.GetRuleViolations());
//render a view that re-shows the form with the validation rules shown
return View(dinner);
}
}
</code></pre>
<p>Here is the "Add" example:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create()
{
//create a new empty object
Dinner dinner = new Dinner();
try
{
//populate it with the values submitted
UpdateModel(dinner);
//add it to the database
dinnerRepository.Add(dinner);
//save the changes
dinnerRepository.Save();
//redirect the user back to the read-only action for what they just added
return RedirectToAction("Details", new { id = dinner.DinnerID });
}
catch
{
//exception occurred, probably from UpdateModel, so handle the validation errors
// (read the full chapter to learn what this extention method is)
ModelState.AddRuleViolations(dinner.GetRuleViolations());
//render a view that re-shows the form with the validation rules shown
return View(dinner);
}
}
</code></pre>
<p>For both examples above, the DinnerRepository looks like this:</p>
<pre><code>public class DinnerRepository
{
private NerdDinnerDataContext db = new NerdDinnerDataContext();
//
// Query Methods
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
public IQueryable<Dinner> FindUpcomingDinners()
{
return from dinner in db.Dinners
where dinner.EventDate > DateTime.Now
orderby dinner.EventDate
select dinner;
}
public Dinner GetDinner(int id)
{
return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
}
//
// Insert/Delete Methods
public void Add(Dinner dinner)
{
db.Dinners.InsertOnSubmit(dinner);
}
public void Delete(Dinner dinner)
{
db.RSVPs.DeleteAllOnSubmit(dinner.RSVPs);
db.Dinners.DeleteOnSubmit(dinner);
}
//
// Persistence
public void Save()
{
db.SubmitChanges();
}
}
</code></pre>
|
How to check if a database exists in SQL Server? <p>What is the ideal way to check if a database exists on a SQL Server using TSQL? It seems multiple approaches to implement this.</p>
| <p>Actually it's best to use:</p>
<pre><code>if db_id('dms') is not null
--code mine :)
print 'db exists'
</code></pre>
<p>See <a href="https://msdn.microsoft.com/en-us/library/ms186274.aspx">https://msdn.microsoft.com/en-us/library/ms186274.aspx</a> </p>
|
How to Return Generic Dictionary in a WebService <p>I want a Web Service in C# that returns a Dictionary, according to a search:</p>
<pre><code>Dictionary<int, string> GetValues(string search) {}
</code></pre>
<p>The Web Service compiles fine, however, when i try to reference it, i get the following error:
"is not supported because it implements IDictionary."</p>
<p>¿What can I do in order to get this working?, any ideas not involving return a DataTable?</p>
| <p>There's no "default" way to take a Dictionary and turn it into XML. You have to pick a way, and your web service's clients will have to be aware of that same way when they are using your service. If both client and server are .NET, then you can simply use the same code to serialize and deserialize Dictionaries to XML on both ends.</p>
<p>There's code to do this <a href="http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx">in this blog post</a>. This code uses the default serialization for the keys and values of the Dictionary, which is useful when you have non-string types for either. The code uses inheritance to do its thing (you have to use that subclass to store your values). You could also use a wrapper-type approach as done in the last item in <a href="http://msdn.microsoft.com/en-us/magazine/cc164135.aspx">this article</a>, but note that the code in that article just uses ToString, so you should combine it with the first article.</p>
<p>Because I agree with Joel about StackOverflow being the canonical source for everything, below is a copy of the code from the first link. If you notice any bugs, edit this answer!</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
}
</code></pre>
|
Verifying a user in "Email Submission" use case <p>I'm building a system that allows people to submit text and photos via email in addition to standard access on the website. I'm trying to weight the security advantages of two strategies in particular for verifying submissions from a user. Here they are as follows:</p>
<ul>
<li>To based auth: Create a secret email address per user and present this to the user for submission. This strategy has the advantage that people can send from multiple devices that might be setup with different mail accounts</li>
<li>From based auth: Only accept emails from addresses that are registered in the user database. The idea being that it is impractical/difficult to impersonate registered users based on the sending address.</li>
</ul>
<p>Can you think of other possible solutions? Which strategy of the ones proposed makes the most sense to you?</p>
| <p>I would suggest that you not use From based authentication, at least not without some additional credentials (a passphrase, etc) </p>
<p><a href="http://www.google.com/search?q=send%20fake%20email" rel="nofollow"><strong>It's way too easy to forge</strong></a>, and certainly not difficult if you know someone's email address.</p>
<p>If you echo the email back to the user for confirmation, you can make things a little more difficult, but realize that your service can end up being used as a sort of spamming relay. (I could send 100 upload requests to you, with a forged FROM address, and you'd go ahead and spam the real person with 100 confirmation requests)</p>
|
ImageButton event does not fire if ImageButton does not have Image? <p>Is it normal behavior for an ImageButton event to not fire if it can't find the image for it. For example, assume I have the following piece of code:</p>
<pre><code>imageLink = new ImageButton();
imageLink.ImageUrl = "~/images/arrow.png";
</code></pre>
<p>If the page finds arrow.png, the image click works, but if it doesn't find it, it does not work.</p>
<p>These images are created dynamically and a CommandName, CommandArgument and Click Handler are assigned.</p>
<pre><code>void imageLink_Click(object sender, ImageClickEventArgs e)
{
ImageButton button = (ImageButton)sender;
Detail oDetail = new Detail();
switch(button.CommandName)
{
case "Band":
oDetail.Band = button.CommandArgument;
break;
case "State":
oDetail.State = button.CommandArgument;
break;
}
Session["Page2"] = oDetail;
Response.Redirect("~/Page2.aspx");
}
</code></pre>
| <p>No, that is not normal. I just tested and even if you never set <code>ImageUrl</code> the button will still post back. Are you certain that the issue is not related to event handling?</p>
|
Best practice for Parent / Child UI design in ASP.Net? <p>Coming from a desktop client background, with no real data-driven web design experience, I am studying ASP.NET UI design to determine the best UI pattern for Parent/Children data.</p>
<p>I always tend to experiment with Parent/Child presentation when learning a new UI platform, so that is where I have started here. Thinking I should use ASP.NET 2.0, I am studying the various ways of architecting a UI form which contains a master list of Parent records, and then showing the related children records in a second grid on the page when you click on a parent. Eventually, even the child records are parents to other children, so I'll need to deal with that also.</p>
<p>Think: Customers with Open Orders / Open Orders for Selected Customer / Line Items on Selected Open Order... like this screen where I built the same thing in WPF: <a href="http://www.twitpic.com/26w26" rel="nofollow">http://www.twitpic.com/26w26</a></p>
<p>Some of techniques I've seen simply creates a plain old-shcool table of href links for the parents, with some method call to query the children based on the selected parent, while some techniques I've seen use the ASP.NET 2.0 data controls to work all this out. Are the ASP.NET 2.0 data controls cheating? Do real developers use these out-of-the box controls, or do they output their own HTML so they can have more control?</p>
<p>Also, it seems like ASP.NET MVC is all the rage right now, so I though I should consider that. When I looked at a few intro's about it, it seems to take a step back in time as it looks like you have to manually create much the HTML to present lists and datagrids, rather than being able to use the ASP.NET 2.0 controls.</p>
<p>I'm kinda lost as to where to spend my energy.</p>
| <p>I won't comment on the Parent/Child portion of what you're asking, but rather on the WebForms vs ASP.NET MVC you asked about at the end.</p>
<p>I found developing using WebForms <strong><em>highly</em></strong> annoying. Every time I wanted to do something out of the "norm" I had to fight with the framework to get it to work the way I wanted.</p>
<p>ASP.NET MVC relieves you of these burdens greatly. However, it does so at the expense of having all kinds of cool components you can use out of the box. So yes, there is more hand-coding of the HTML, but ultimately that's what's going to make developing your pages a lot more pleasant.</p>
|
Dynamic search result when typing <p>I'm using asp.net and want to filter a search result everytime the user enter letters in a textbox. For exmaple this website do exactly what I want: <a href="http://www.prisjakt.nu/" rel="nofollow">http://www.prisjakt.nu/</a> (try searching in the right top corner). I have tried just putting my textbox and the gridview with the search result in an updatepanel, it's working but it's really slow, can I make it faster and how? Is there any articles or something about this?</p>
| <p>If you're open to using jQuery, take a look at <a href="http://www.pengoworks.com/workshop/jquery/autocomplete.htm" rel="nofollow">jQuery Autocomplete</a>.</p>
|
DataContractSerializer documentation <p>I'm looking for a good in depth documentation/how-to for DataContractSerializer. Google turns up a number of related articles but nothing jumped out at me. (I'm not looking for the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx" rel="nofollow">MSDN link</a>)</p>
<p>A little clarification: I have never use serialization in .NET but have a working app that does that I need to update/modify. I have a fairly good Idea how <em>I</em> would do what I need to do if <em>I had designed the serialization system</em> but I'd rather not hunt trough a pile of MSDN class documentation looking for how they expect me to do it. The MSDN stuff works well for figuring out how something works (as does Google because at that point you have a specific term to Google) What I would like is a well done "here is how it works and this is all the details" document targeted at showing me how to fit the pieces together rather than figuring out how they work. I'm afraid what I'm looking for is a bit of an "I'll know it when I see it" thing, and I have never had good luck Googeling for that sort of thing.</p>
<p>I'm particularly interested in specific pages that people have used and personally found very useful. <em>If you are thinking of something particular right now (before going to Google) that is what I'm looking for. If not...</em> </p>
| <p>Try this MSDN link instead, <a href="http://msdn.microsoft.com/en-us/library/ms733127.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms733127.aspx</a></p>
<blockquote>
<p>but I'd rather not hunt trough a pile
of MSDN class documentation looking
for how they expect me to do it.</p>
</blockquote>
<p>It's Microsoft, what do you expect??? You ARE expected to use it the way they want it. :)</p>
|
How can I use a dynamically sized texture array with glTexImage2D? <p>Currently, I'm able to load in a static sized texture which I have created. In this case it's 512 x 512.</p>
<p>This code is from the header:</p>
<pre><code>#define TEXTURE_WIDTH 512
#define TEXTURE_HEIGHT 512
GLubyte textureArray[TEXTURE_HEIGHT][TEXTURE_WIDTH][4];
</code></pre>
<p>Here's the usage of glTexImage2D:</p>
<pre><code>glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA,
TEXTURE_WIDTH, TEXTURE_HEIGHT,
0, GL_RGBA, GL_UNSIGNED_BYTE, textureArray);
</code></pre>
<p>And here's how I'm populating the array (rough example, not exact copy from my code):</p>
<pre><code>for (int i = 0; i < getTexturePixelCount(); i++)
{
textureArray[column][row][0] = (GLubyte)pixelValue1;
textureArray[column][row][1] = (GLubyte)pixelValue2;
textureArray[column][row][2] = (GLubyte)pixelValue3;
textureArray[column][row][3] = (GLubyte)pixelValue4;
}
</code></pre>
<p>How do I change that so that there's no need for TEXTURE_WIDTH and TEXTURE_HEIGHT? Perhaps I could use a pointer style array and dynamically allocate the memory...</p>
<h3>Edit:</h3>
<p>I think I see the problem, in C++ it can't really be done. The work around as pointed out by Budric is to use a single dimensional array but use all 3 dimensions multiplied to represent what would be the indexes:</p>
<pre><code>GLbyte *array = new GLbyte[xMax * yMax * zMax];
</code></pre>
<p>And to access, for example x/y/z of 1/2/3, you'd need to do:</p>
<pre><code>GLbyte byte = array[1 * 2 * 3];
</code></pre>
<p>However, the problem is, I don't think the <code>glTexImage2D</code> function supports this. Can anyone think of a workaround that would work with this OpenGL function?</p>
<h3>Edit 2:</h3>
<p>Attention OpenGL developers, this can be overcome by using a single dimensional array of pixels...</p>
<blockquote>
<p>[0]: column 0 > [1]: row 0 > [2]: channel 0 ... n > [n]: row 1 ... n > [n]: column 1 .. n</p>
</blockquote>
<p>... no need to use a 3 dimensional array. In this case I've had to use this work around as 3 dimensional arrays are apparently not strictly possible in C++.</p>
| <p>Ok since this took me ages to figure this out, here it is:</p>
<p>My task was to implement the example from the OpenGL Red Book (9-1, p373, 5th Ed.) with a dynamic texture array.</p>
<p>The example uses:</p>
<pre><code>static GLubyte checkImage[checkImageHeight][checkImageWidth][4];
</code></pre>
<p>Trying to allocate a 3-dimensional array, as you would guess, won't do the job. Someth. like this does <strong><em>NOT</em></strong> work:</p>
<pre><code>GLubyte***checkImage;
checkImage = new GLubyte**[HEIGHT];
for (int i = 0; i < HEIGHT; ++i)
{
checkImage[i] = new GLubyte*[WIDTH];
for (int j = 0; j < WIDTH; ++j)
checkImage[i][j] = new GLubyte[DEPTH];
}
</code></pre>
<p>You have to use a <strong><em>one dimensional array</em></strong>:</p>
<pre><code>unsigned int depth = 4;
GLubyte *checkImage = new GLubyte[height * width * depth];
</code></pre>
<p>You can access the elements using this loops:</p>
<pre><code>for(unsigned int ix = 0; ix < height; ++ix)
{
for(unsigned int iy = 0; iy < width; ++iy)
{
int c = (((ix&0x8) == 0) ^ ((iy&0x8)) == 0) * 255;
checkImage[ix * width * depth + iy * depth + 0] = c; //red
checkImage[ix * width * depth + iy * depth + 1] = c; //green
checkImage[ix * width * depth + iy * depth + 2] = c; //blue
checkImage[ix * width * depth + iy * depth + 3] = 255; //alpha
}
}
</code></pre>
<p>Don't forget to delete it properly:</p>
<pre><code>delete [] checkImage;
</code></pre>
<p>Hope this helps...</p>
|
Is it more secure to store using a database or a file? <p>This question is from a decomposition of <a href="http://stackoverflow.com/questions/678471/what-are-good-programming-practices-to-prevent-malware-in-standalone-applications">http://stackoverflow.com/questions/678471/what-are-good-programming-practices-to-prevent-malware-in-standalone-applications</a></p>
<p>The question has to do with malware dynamically getting into a program by infecting data files which the program reads/writes. </p>
<p>Is it safer to require data be stored in a database and only use service calls, no direct file operations when accessing data for a program? Let's say your program loads many images, numeric data tables, or text information as it runs. Assume this is after the program is loaded and initialized to where it can make service calls.</p>
<p>Is it easier to infect a file or a database? </p>
| <p>It is easier to infect user-space API than kernel space API.</p>
<p>In other words, the point is moot if you can't trust the services you're using to read the data.</p>
|
DXGetErrorString newbie question <p>I'm new to C++ and Direct X, and I was wondering what is the proper use of DXGetErrorString and DXGetErrorDescription?</p>
<p>According to <a href="http://msdn.microsoft.com/en-us/library/bb173057(VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb173057(VS.85).aspx</a> and <a href="http://msdn.microsoft.com/en-us/library/bb173056(VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb173056(VS.85).aspx</a>, these functions return a pointer to a string. However, in all the examples I've seen on the web, they directly use the return value without freeing it afterward.</p>
<p>For example:</p>
<pre><code>char buf[2048];
sprintf(buf, "Error: %s error description: %s\n",DXGetErrorString(hr),DXGetErrorDescription(hr));
</code></pre>
<p>Does that mean there is a memory leak because the memory allocated for the error string and the error description is never released ? If not, how is it released ?</p>
<p>Thank you for the help !</p>
| <p>Most likely, the functions return a static string, so it doesn't need to be free'd.</p>
<p>It'd be similar to writing code like this, where you would not worry about freeing the return value:</p>
<pre><code>PCWSTR GetErrorCode(int error)
{
switch (error)
{
case 1:
return L"File not found";
...
default:
return "Unknown error";
}
}
</code></pre>
|
How do I build a PXE-bootable boot loader from Workbench? <p>I'm trying to build a VxWorks boot loader that is PXE-bootable from Workbench, but not having any success. Here is a run-down of my environment:</p>
<ul>
<li>VxWorks 6.6 + latest patches</li>
<li>Workbench 3.0 + latest patches</li>
<li>Montevina BSP release 2.0/1</li>
</ul>
<p>The target is a Dell Precision M4400 laptop. Here's what I've been doing, without success:</p>
<ol>
<li>Create a new <code>VxWorks Image Project</code> in Workbench based on the Montevina BSP using the <code>PROFILE_BOOTAPP</code> profile.</li>
<li>Add the following components to the kernel configuration (the build fails otherwise):<br>- <code>INCLUDE_TIMER_SYS</code><br>- <code>INCLUDE_PCI_BUS</code><br>- <code>INCLUDE_PCI_OLD_CONFIG_ROUTINES</code><br>- <code>INCLUDE_PENTIUM_PCI</code></li>
<li>Add the <code>INCLUDE_PC_CONSOLE</code> component to the kernel configuration for console display (there aren't any serial ports on the target)</li>
<li>Set the build spec to <code>default_romCompress</code> and add a new build target named <code>vxWorks_romCompress.bin</code></li>
<li>Build the <code>vxWorks_romCompress.bin</code> target, which creates the corresponding file.</li>
<li>Add the PXE padding to the file:<br><code>cat $WIND_BASE/vxworks-6.6/target/config/montevina/pxeBoot.bin vxWorks_romCompress.bin > vxWorks_romCompress.pxe</code></li>
<li>Copy <code>vxWorks_romCompress.pxe</code> to the appropriate location for my TFTP server, and do a PXE boot from my target.</li>
</ol>
<p>At this point the target successfully downloads the file from the TFTP server, but stalls there with no output. There is nothing displayed on the console.</p>
<p>The <code>RAM_HIGH_ADRS</code> and <code>RAM_LOW_ADRS</code> do appear to be set correctly in the Workbench project (they match the settings of the legacy config.h file at <code>0x00108000</code> and <code>0x003080000</code>, respectively). </p>
<p>(Note that the Montevina BSP does ship with a pre-built <code>bootrom.pxe</code> boot loader, which I <strong>have</strong> been able to PXE-boot successfully. I'm needing to add several components to the boot loader, though, and would really prefer to do this via the Workbench environment, rather than the legacy config.h method.)</p>
<p>I've also tried mirroring the components included in the Workbench project's kernel configuration to match the legacy config.h settings as closely as possibly, without success. These are the components that were added (in addition to any dependencies of these):</p>
<ul>
<li><code>INCLUDE_PLB_BUS</code></li>
<li><code>DRV_NVRAM_FILE</code></li>
<li><code>INCLUDE_GENERICPHY</code></li>
<li><code>DRV_INTCTLR_IOAPIC</code></li>
<li><code>INCLUDE_GEI825XX_VXB_END</code></li>
<li><code>DRV_TIMER_IA_TIMESTAMP</code></li>
<li><code>INCLUDE_MII_BUS</code></li>
<li><code>DRV_INTCTLR_MPAPIC</code></li>
<li><code>DRV_SIO_NS16550</code></li>
<li><code>INCLUDE_FEI8255X_VXB_END</code></li>
<li><code>DRV_TIMER_LOAPIC</code></li>
<li><code>INCLUDE_SIO_UTILS</code></li>
<li><code>VXBUS_TABLE_CONFIG</code></li>
<li><code>INCLUDE_INTCTLR_LIB</code></li>
<li><code>INCLUDE_DMA_SYS</code></li>
<li><code>INCLUDE_PARAM_SYS</code></li>
<li><code>INCLUDE_SW_FPP</code></li>
</ul>
<p>So, that's where I am right now. I'm guessing the problem is in steps 4-6 above, but I don't see anything in the docs as to the proper way from within Workbench to make the boot loader PXE-bootable.</p>
| <p>Wind River got in touch with me and said this is not supported at present.</p>
|
Scala API design; a service which returns a Set<I> where I is some interface (abstract/trait) <p>I have asked quite a few questions about the Scala collection types and how they might actually be used. Consider how I might write some service API/implementation in Java:</p>
<pre><code>public interface JavaProductAPI {
public Set<IProduct> getProducts(String isin);
}
</code></pre>
<p>And now the impl:</p>
<pre><code>public class JavaProductAPIImpl implements JavaProductAPI {
private Map<String, Set<ProductImpl>> productsByIsin;
public Set<IProduct> getProducts() {
Set<ProductImpl> s = productsByIsin.get(isin);
return s == null
? Collections.<IProduct>emptySet()
: Collections.<IProduct>unmodifiableSet(s);
}
}
</code></pre>
<p>Lets say that there's a really good reason why I need to have access within the service implementation to the set of products as being of <code>ProductImpl</code>s, not <code>IProduct</code>s.</p>
<p>It seems that in Scala, there's no real way to achieve this whilst at the same time exlicitly returning an <code>scala.collection.immutable.Set</code> from the API access method. <em>Unless I don't mind returning a copy of the set</em>. </p>
<p>I'm going to assume that returning an actual copy of the data is bad practice (feel free to argue this point!):</p>
<pre><code>val productsByIsin: Map[String, scala.collection.Set[ProductImpl]] = ...
def getProducts(isin: String): scala.collection.immutable.Set[IProduct] = {
productsByIsin.get(isin) match {
case Some(s) => scala.collection.immutable.Set(s toSeq :_*)
case None => scala.collection.immutable.Set.empty
}
}
</code></pre>
<p>So that therefore my only real design choice is to have the API return a <code>scala.collection.Set</code> and use a read-only view:</p>
<pre><code>val productsByIsin: Map[String, scala.collection.mutable.Set[ProductImpl]] = ...
def getProducts(isin: String): scala.collection.Set[IProduct] = {
productsByIsin.get(isin) match {
case Some(s) => s readOnly
case None => scala.collection.Set.empty
}
}
</code></pre>
| <p>Your last block of code more closely mimics the Java code you're emulating: returning a read-only view of a mutable Set.</p>
<p>That said, in this situation, if your backing implementation is an immutable.Set[ProductImpl] and you want to return an immutable.Set[IProduct], it's safe to cast.</p>
<pre><code>import scala.collection._
trait IProduct
class ProductImpl extends IProduct
val productsByIsin: immutable.Map[String, immutable.Set[ProductImpl]] =
immutable.Map.empty
def getProducts(isin: String): immutable.Set[IProduct] =
productsByIsin.getOrElse(isin, immutable.Set.empty).asInstanceOf[immutable.Set[IProduct]]
</code></pre>
|
Advice on a better way to extend C++ STL container with user-defined methods <p>I inherited from C++ STL container and add my own methods to it. The rationale was such that to the clients, it will look act a regular list, yet has application-specific methods they can readily be called. </p>
<p>This works fine, but I have read numerous posts about not inheriting from STL. Can someone provide a concrete advice of how I might write the code below in a better way? </p>
<pre><code>class Item
{
int a;
int b;
int c;
int SpecialB()
{
return a * b + c;
}
};
class ItemList : public std::vector<Item>
{
int MaxA()
{
if( this->empty() )
throw;
int maxA = (*this)[0].a;
for( int idx = 1; idx < this->size(); idx++ )
{
if( (*this)[idx].a > maxA )
{
maxA = (*this)[idx].a;
}
}
return maxA;
}
int SpecialB()
{
if( this->empty() )
throw;
int specialB = (*this)[0].SpecialB();
for( int idx = 1; idx < this->size(); idx++ )
{
if( (*this)[idx].SpecialB() < specialB )
{
specialB -= (*this)[idx].c;
}
}
return specialB;
}
int AvgC()
{
if( this->empty() )
throw;
int cSum = 0;
for( int idx = 0; idx < this->size(); idx++ )
{
cSum += (*this)[idx].c;
}
return cSum / this->size(); // average
}
};
</code></pre>
<p><strong>EDIT</strong>: Thanks for a bunch of thoughtful answers. I will create helper functions instead and from now on will never inherit from STL containers.</p>
| <p>This is a <strong>bad</strong> idea.</p>
<p>There are a lot of reasons you shouldn't derive from STL classes, foremost of which is that they're not designed for it. Vector doesn't have a virtual destructor, so if you extend it, the superclass's destructor may not be called properly and you'll get memory leaks.</p>
<p>For more on this, see this answer on why <em>not</em> to derive from <code>std::string</code>. Many of the same points apply:</p>
<p><a href="http://stackoverflow.com/questions/555612/constructor-doesnt-work-for-class-inherited-from-stdstring/555633#555633">Constructor doesnât work for class inherited from std::string</a></p>
<ul>
<li>No virtual destructor</li>
<li>No protected functions (so you gain nothing by inheriting)</li>
<li>Polymorphism won't work, and you'll get object slicing. <code>std::vector</code> is assignable, but if you add your own fields they won't get copied on assignment if you assign from a vector pointer or vector reference. This is because <code>vector</code>'s <code>operator=</code> does not know about your fields.</li>
</ul>
<p>For all of these reasons, you're better off making utility functions than extending when it comes to STL.</p>
|
Automatic selection of <p></p>-text rendered in browser <p>who would know of a possibility to automatically select Paragaph text as it gets rendered in a browser, preferably using JavaScript?</p>
<p>In my case I have an amount of text in <code><p></p></code> tags and would like the page to appear with the text fully selected, just as if someone had done it manually with the mouse.</p>
<p>Many thanks for your suggestions!</p>
| <p>Insert this near the very end of your page:</p>
<pre><code><script type='text/javascript'>
ptags = window.document.getElementsByTagName("p");
current_selection = window.getSelection();
for (i=0; i< ptags.length; i++)
{
var r1 = document.createRange();
r1.setStartBefore(ptags[i]);
r1.setEndAfter(ptags[i]) ;
current_selection.addRange(r1);
}
</script>
</code></pre>
<p>Tested in Firefox 3.07 --> not really sure about cross-browser compatibility, although I think IE should be all right.</p>
|
Why are Doctype declarations split on two lines? <p>I know there's more important questions to discuss probably, but at the cost of appearing a fool, I'd like an answer ;-)</p>
<p>Take this for instance:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
</code></pre>
<p>Is it to comply to the 80 column standard? Also, i normally use single quotes in my HTML as they're easier on the eye, does it make any difference to browsers? Will it send IE6 in quirks mode putting it on one line and single-quoting attributes?</p>
<p>Thanks</p>
| <p>It's just line-wrapping.</p>
<p>Also, XML will take either quote mark, but convention is the double quote.</p>
|
How do I define a generic std::list of a custom type? <p>I'm getting the following error trying to define a list of "Lines":</p>
<blockquote>
<p>line-clip.cpp:44: error: expected
initializer before '<' token</p>
</blockquote>
<pre><code>#include <list>
using namespace std;
class Line {
public:
Point p1;
Point p2;
Line(Point P1, Point P2)
{
p1 = P1;
p2 = P2;
}
}
// Line List
list <Line> lineList;
</code></pre>
<p>How do you define a generic List of type "Line"?</p>
| <p>You need a semicolon after your class declaration :-).</p>
<pre><code>class Line {
...
}; // put a semicolon here.
</code></pre>
|
Best way to profile/optimize a website on google's appengine <p>I'm currently trying to optimize my website, which run on the google's appengine. It's not an easy task, because I'm not using any powerful tool.</p>
<p>Does anyone have experience in optimizing python code for this purpose?
Have you find a good python profiler?</p>
| <p>I have found <a href="http://code.google.com/p/jrfonseca/wiki/Gprof2Dot" rel="nofollow">Gprof2Dot</a> extremely useful. The output of the profiling modules I've tried as pretty unintuitive to interpret.</p>
<p>Gprof2Dot turns the cProfile output into a pretty looking graph, with the slowest chain(?) highlighted, and a bit of information on each function (function name, percentage of time spend on this function, and number of calls).</p>
<p><a href="http://jrfonseca.googlecode.com/svn/wiki/gprof2dot.png" rel="nofollow">An example graph (1429x1896px)</a></p>
<p>I've not done much with the App Engine, but when profiling non-webapp scripts, I tend to profile the script that runs all the unittests, which may not be very accurate to real-world situations</p>
<p>One (better?) method would be to have a script that does a fake WSGI request, then profile that.</p>
<p>WSGI is really simple protocol, it's basically a function that takes two arguments, one with request info and the second with a callback function (which is used for setting headers, among other things). Perhaps something like the following (which is possible-working pseudo code)...</p>
<pre><code>class IndexHandler(webapp.RequestHandler):
"""Your site"""
def get(self):
self.response.out.write("hi")
if __name__ == '__main__':
application = webapp.WSGIApplication([
('.*', IndexHandler),
], debug=True)
# Start fake-request/profiling bit
urls = [
"/",
"/blog/view/hello",
"/admin/post/edit/hello",
"/makeanerror404",
"/makeanerror500"
]
def fake_wsgi_callback(response, headers):
"""Prints heads to stdout"""
print("\n".join(["%s: %s" % (n, v) for n, v in headers]))
print("\n")
for request_url in urls:
html = application({
'REQUEST_METHOD': 'GET',
'PATH_INFO': request_url},
fake_wsgi_callback
)
print html
</code></pre>
<p>Actually, the App Engine documentation explains a better way of profiling your application:</p>
<p>From <a href="http://code.google.com/appengine/kb/commontasks.html#profiling" rel="nofollow">http://code.google.com/appengine/kb/commontasks.html#profiling</a>:</p>
<blockquote>
<p>To profile your application's performance, first rename your application's <code>main()</code> function to <code>real_main()</code>. Then, add a new main function to your application, named <code>profile_main()</code> such as the one below:</p>
<pre><code>def profile_main():
# This is the main function for profiling
# We've renamed our original main() above to real_main()
import cProfile, pstats
prof = cProfile.Profile()
prof = prof.runctx("real_main()", globals(), locals())
print "<pre>"
stats = pstats.Stats(prof)
stats.sort_stats("time") # Or cumulative
stats.print_stats(80) # 80 = how many to print
# The rest is optional.
# stats.print_callees()
# stats.print_callers()
print "</pre>"
</code></pre>
<p>[...]</p>
<p>To enable the profiling with your application, set <code>main = profile_main</code>. To run your application as normal, simply set <code>main = real_main</code>.</p>
</blockquote>
|
Is it possible to create a page from a string in ASP.Net? <p>I can create a page from a file with:</p>
<pre><code>Page page = BuildManager.CreateInstanceFromVirtualPath(
virtualPath, typeof(Page)) as Page;
</code></pre>
<p>How can I instantiate a page from a stream or a string?</p>
<p>Thank you.</p>
| <p>You can create your own <a href="http://msdn.microsoft.com/en-us/library/system.web.hosting.virtualpathprovider.aspx" rel="nofollow">VirtualPathProvider</a>, which sits between the ASP.NET parser and the file system. The default provider in ASP.NET reads ASPX markup from disk, but you can create your own to read it from anywhere (SQL, a stream, a string, etc).</p>
<p>Essentially how it works is that the custom VirtualPathProvider class takes over the handling of virtual paths like "~/MyPage.aspx" (which you must pass in to the BuildManager). It provides custom logic for deciding what to do with "~/MyPage.aspx", which could include returning data stored in a string or stream in memory.</p>
<p>Here's some reading to get you started:</p>
<ul>
<li><a href="http://support.microsoft.com/kb/910441" rel="nofollow">How to use virtual path providers to dynamically load and compile content from virtual paths in ASP.NET 2.0</a></li>
<li><a href="http://blogs.msdn.com/davidebb/archive/2005/11/27/497339.aspx" rel="nofollow">Overriding ASP.NET combine behavior using a VirtualPathProvider</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/aa479502.aspx" rel="nofollow">Virtualizing Access to Content: Serving Your Web Site from a ZIP File</a> (a good example using the same concept to do something different and fairly interesting)</li>
</ul>
|
Fastest way to format a phone number in C#? <p>What is the fastest way to format a string using the US phone format [(XXX) XXX-XXXX] using c#?</p>
<p>My source format is a string. </p>
| <pre><code>String.Format("{0:(###) ###-#### x ###}", double.Parse("1234567890123"))
Will result in (123) 456-7890 x 123
</code></pre>
|
Sort a DataGrid by clicking on column headers in the Compact Framework? <p>Is this even possible in the .Net Compact Framework? There's all sorts of stuff it leaves out when comparing with the Desktop Framework. </p>
<p>I'm wondering if the Compact Framework's got the upper hand on me with this feature request in our mobile app.</p>
| <p>Because that website is no longer available, here are the contents:</p>
<pre><code> public static void SortDataGrid(object sender, MouseEventArgs e)
{
DataGrid.HitTestInfo hitTest;
DataTable dataTable;
DataView dataView;
string columnName;
DataGrid dataGrid;
// Use only left mouse button clicks
if (e.Button == MouseButtons.Left)
{
// Set dataGrid equal to the object that called this event handler
dataGrid = (DataGrid)sender;
// Perform a hit test to determine where the mousedown event occurred
hitTest = dataGrid.HitTest(e.X, e.Y);
// If the MouseDown event occurred on a column header,
// then perform the sorting operation.
if (hitTest.Type == DataGrid.HitTestType.ColumnHeader)
{
// Get the DataTable associated with this DataGrid.
dataTable = (DataTable)dataGrid.DataSource;
// Get the DataView associated with the DataTable.
dataView = dataTable.DefaultView;
// Get the name of the column that was clicked.
if (dataGrid.TableStyles.Count != 0)
columnName = dataGrid.TableStyles[0].GridColumnStyles[hitTest.Column].MappingName;
else
columnName = dataTable.Columns[hitTest.Column].ColumnName;
// If the sort property of the DataView is already the current
// column name, sort that column in descending order.
// Otherwise, sort on the column name.
if (dataView.Sort == columnName)
dataView.Sort = columnName + " DESC";
else
dataView.Sort = columnName;
}
}
}
</code></pre>
|
LINQ to SQL - Is it true that SubmitChanges() automatically starts a transaction? <p>I need to use transactions with LINQ to SQL and I was reading around to get familiar with it.</p>
<p>Is it true that SubmitChanges is already transactioned?</p>
| <p>When you call SubmitChanges, LINQ to SQL examines the set of known objects to determine whether new instances have been attached to them. If they have, these new instances are added to the set of tracked objects. </p>
<p>Immediately before any actual changes are transmitted, <strong>LINQ to SQL starts a transaction to encapsulate the series of individual commands.</strong> </p>
<p>The changes to the objects are translated one by one to SQL commands and sent to the server. </p>
<p>At this point, any errors detected by the database cause the submission process to stop, and an exception is raised. <strong>All changes to the database are rolled back as if no submissions ever occurred</strong>. </p>
<p>For more info on this view the <a href="http://msdn.microsoft.com/en-us/library/bb399378.aspx">MSDN article</a>.</p>
<p>Hope this helps!</p>
|
How can I use the DRY principle to in ASP.NET MVC to refactor this code? <p>I have several methods in one of my controllers that does this: </p>
<pre><code>ViewData["Customers"] = LoadCustomers();
ViewData["Employees"] = LoadEmployees();
ViewData["Statuses"] = LoadStatuses();
etc......
</code></pre>
<p>Here is LoadCustomers(), but LoadEmployees, LoadStatuses and all the others are virtually the exact same logic: </p>
<pre><code>private static SelectList LoadCustomers()
{
IList<Customer> customers;
try
{
IServiceCallService scService = new ServiceCallService();
customers = scService.GetCustomers();
Customer c = new Customer
{
ID = "",
Name = "-- Select a Facility --"
};
customers.Insert(0, c);
}
catch
{
customers = new List<Customer>();
Customer c = new Customer
{
ID = "",
Name = "-- No Facilities on File --"
};
customers.Insert(0, c);
}
return new SelectList(customers, "ID", "Name");
}
</code></pre>
<p>How can I write this code better so I don't need a new method everytime I add a new select list?</p>
| <p>This looks like it might be a good candidate for generics:</p>
<pre><code>private static SelectList LoadItems<T>() where T : new, ...
{ // Add any additional interfaces
// that need to be supported by T
// for your Load method to work,
// as appropriate.
IList<T> items;
try
{
IServiceCallService scService = new ServiceCallService();
results = scService.Get<T>(); // You'll need to replace GetCustomers() with
// a generic Get<T> method.
// ...
}
catch // Really needed? What are you trying to catch here? (This catches
{ // everything silently. I suspect this is overkill.)
// ...
}
return new SelectList(items, "ID", "Name");
}
</code></pre>
|
Drupal - Apache's Mod_Deflate breaks CSS <p>We have enabled Apache's mod_deflate on our drupal site.
From that point onwards, we are noticing that CSS files aren't getting loaded properly. It doesn't happen every time. Kinda random.</p>
<p>Did anyone else notice this issue? If so, any suggested solutions?</p>
| <p>You might have better luck with the <a href="http://drupal.org/project/css%5Fgzip" rel="nofollow">CSS Gzip module</a> than doing it with Apache directly.</p>
|
How to locate the theme folder in Asp.net? <p>I'm binding some image controls dynamically but don't set image URL. When I use a skin file and then set the SkinId, I get the following error:</p>
<pre><code>The 'SkinId' property can only be set in or before the Page_PreInit event for static controls. For dynamic controls, set the property before adding it to the Controls collection.
</code></pre>
<p>How do I get a virtual theme's location?</p>
| <p>Set the SkinId on the markup</p>
<pre><code><asp:Image runat="server" id="LogoImage" SkinId="LogoImage" />
</code></pre>
<p>To set it programatically you need to set it up on the PreInit event</p>
<pre><code>public void Page_PreInit(object sender, EventArgs e)
{
LogoImage.SkinID = "LogoImage";
}
</code></pre>
<p>And here is a blog post for setting the SkinId Programatically
<a href="http://blogs.conchango.com/simonevans/archive/2005/06/09/How-to-programmatically-assign-a-SkinID-to-a-control-while-using-a-master-page-in-ASP.net-2.0.aspx" rel="nofollow">http://blogs.conchango.com/simonevans/archive/2005/06/09/How-to-programmatically-assign-a-SkinID-to-a-control-while-using-a-master-page-in-ASP.net-2.0.aspx</a></p>
<p>Finally, if you are just looking for the folder, it depends on whether you are using a <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.theme.aspx" rel="nofollow">Theme</a> or a <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.stylesheettheme.aspx" rel="nofollow">StylesheetTheme</a>.</p>
<pre><code>var path = "~/App_Themes/" + Page.Theme + "/images";
var path = "~/App_Themes/" + Page.StylesheetTheme + "/images";
</code></pre>
<h2>Update</h2>
<p>If you doing this in a Grid use a custom binding method</p>
<pre><code><asp:Image runat="server" id="myImage" ImageUrl='<%# GetThemedImage(((Product)Container.DataItem).Image)%>' />
</code></pre>
<p>then in the code-behind</p>
<pre><code>public string GetThemedImage(string image)
{
return "~/App_Themes/" + Page.Theme + "/images/" + image;
}
</code></pre>
|
Where to stop/destroy threads in Android Service class? <p>I have created a threaded service the following way:</p>
<pre><code>public class TCPClientService extends Service{
...
@Override
public void onCreate() {
...
Measurements = new LinkedList<String>();
enableDataSending();
}
@Override
public IBinder onBind(Intent intent) {
//TODO: Replace with service binding implementation
return null;
}
@Override
public void onLowMemory() {
Measurements.clear();
super.onLowMemory();
}
@Override
public void onDestroy() {
Measurements.clear();
super.onDestroy();
try {
SendDataThread.stop();
} catch(Exception e){
...
}
}
private Runnable backgrounSendData = new Runnable() {
public void run() {
doSendData();
}
};
private void enableDataSending() {
SendDataThread = new Thread(null, backgrounSendData, "send_data");
SendDataThread.start();
}
private void addMeasurementToQueue() {
if(Measurements.size() <= 100) {
String measurement = packData();
Measurements.add(measurement);
}
}
private void doSendData() {
while(true) {
try {
if(Measurements.isEmpty()) {
Thread.sleep(1000);
continue;
}
//Log.d("TCP", "C: Connecting...");
Socket socket = new Socket();
socket.setTcpNoDelay(true);
socket.connect(new InetSocketAddress(serverAddress, portNumber), 3000);
//socket.connect(new InetSocketAddress(serverAddress, portNumber));
if(!socket.isConnected()) {
throw new Exception("Server Unavailable!");
}
try {
//Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
String message = Measurements.remove();
out.println(message);
Thread.sleep(200);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
connectionAvailable = true;
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
connectionAvailable = false;
} finally {
socket.close();
announceNetworkAvailability(connectionAvailable);
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
connectionAvailable = false;
announceNetworkAvailability(connectionAvailable);
}
}
}
...
}
</code></pre>
<p>After I close the application the phone works really slow and I guess it is due to thread termination failure.</p>
<p>Does anyone know what is the best way to terminate all threads before terminating the application?</p>
| <p><strong>Addendum</strong>: The Android framework provides many helpers for one-off work, background work, etc, which may be preferable over trying to roll your own thread in many instances. As mentioned in a below post, AsyncTask is a good starting point to look into. I encourage readers to look into the framework provisions first before even beginning to think about doing their own threading.</p>
<p>There are several problems in the code sample you posted I will address in order:</p>
<p>1) Thread.stop() has been deprecated for quite some time now, as it can leave dependent variables in inconsistent states in some circumstances. See <a href="http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html" rel="nofollow">this Sun answer page</a> for more details (Edit: that link is now dead, see <a href="https://www.securecoding.cert.org/confluence/display/java/THI05-J.+Do+not+use+Thread.stop()+to+terminate+threads" rel="nofollow">this page for why not to use Thread.stop()</a>). A preferred method of stopping and starting a thread is as follows (assuming your thread will run somewhat indefinitely):</p>
<pre><code>private volatile Thread runner;
public synchronized void startThread(){
if(runner == null){
runner = new Thread(this);
runner.start();
}
}
public synchronized void stopThread(){
if(runner != null){
Thread moribund = runner;
runner = null;
moribund.interrupt();
}
}
public void run(){
while(Thread.currentThread() == runner){
//do stuff which can be interrupted if necessary
}
}
</code></pre>
<p>This is just one example of how to stop a thread, but the takeaway is that you are responsible for exiting a thread just as you would any other method. Maintain a method of cross thread communcation (in this case a volatile variable, could also be through a mutex, etc) and within your thread logic, use that method of communication to check if you should early exit, cleanup, etc.</p>
<p>2) Your measurements list is accessed by multiple threads (the event thread and your user thread) at the same time without any synchronization. It looks like you don't have to roll your own synchronization, you can use a <a href="http://developer.android.com/reference/java/util/concurrent/BlockingQueue.html" rel="nofollow">BlockingQueue</a>.</p>
<p>3) You are creating a new Socket every iteration of your sending Thread. This is a rather heavyweight operation, and only really make sense if you expect measurements to be extremely infrequent (say one an hour or less). Either you want a persistent socket that is not recreated every loop of the thread, or you want a one shot runnable you can 'fire and forget' which creates a socket, sends all relevant data, and finishes. (A quick note about using a persistent Socket, socket methods which block, such as reading, cannot be interrupted by Thread.interrupt(), and so when you want to stop the thread, you must close the socket as well as calling interrupt)</p>
<p>4) There is little point in throwing your own exceptions from within a Thread unless you expect to catch it somewhere else. A better solution is to log the error and if it is irrecoverable, stop the thread. A thread can stop itself with code like (in the same context as above):</p>
<pre><code>public void run(){
while(Thread.currentThread() == runner){
//do stuff which can be interrupted if necessary
if(/*fatal error*/){
stopThread();
return; //optional in this case since the loop will exit anyways
}
}
}
</code></pre>
<p>Finally, if you want to be sure a thread exits with the rest of your application, no matter what, a good technique is to call Thread.setDaemon(true) after creation and before you start the thread. This flags the thread as a daemon thread, meaning the VM will ensure that it is automatically destroyed if there are no non-daemon threads running (such as if your app quits).</p>
<p>Obeying best practices with regards to Threads should ensure that your app doesn't hang or slow down the phone, though they can be quite complex :)</p>
|
Application log aggregation, management and notifications <p>I'm wondering what everyone is using for logging, log management and log aggregation on their systems.</p>
<p>I am working in a company which uses .NET for all it's applications and all systems are Windows based. Currently each application looks after its own logging and notifications of failures (e.g. if app A fails it will send out its own 'call for help' to an admin).</p>
<p>While this current practice works its a bit hacky and hard to manage. I've been trying to find some options for making this work better and I've come up with the following:</p>
<ul>
<li>log4net & Chainsaw (ah, if it works).</li>
<li>Logging via log4net or another framework into a central database & rolling our own management tool.</li>
<li>Logging to the Windows event log and using MOM or System Center Operations Manager to aggregate and manage each of these servers & their apps.</li>
<li>A hand-rolled solution to suck all the log files into one point and work some magic across them.</li>
</ul>
<p>Essentially what we are after is something which can pull log entries all together and allow for some analytics to be run across them, plus use a kind of event based system to, for example, send out a warning email when there have been 30+ warning level logs for an application in the last <code>x</code> minutes.</p>
<p>So is there anything I've missed, or something someone else can suggest?</p>
| <p>If you can, I'd recommend writing to the EventLog and creating rules in SCOM to monitor. We use this extensively and it works well, even to a point of putting together pieces of code which monitor certain elements of our apps and writing values to the event log, where SCOM parses for the errors, and graphs those, plus informational errors, into reports showing stats over a given time.</p>
<p>I am however quite keen on rewriting some that into WMI, and having SCOM poll the WMI service for those same counters, as writing queue lengths to event log every 15 minutes seems a little wasteful ;)</p>
|
How to create sub domain from asp.net code <p>I need to create sub domain from code. For example my web site register new user named battulga. After automatically create battulga.mydomain.com.
How to do this?</p>
| <p>Here is a <a href="http://forums.asp.net/p/1267157/2384859.aspx" rel="nofollow">thread</a> about this in ASP.net forum.</p>
|
Operator overloading with memory allocation? <p>The sentence below is from, <strong><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=252441" rel="nofollow">The Positive Legacy of C++ and Java</a></strong> by Bruce Eckel, about operator overloading in C++:</p>
<blockquote>
<p>C++ has both stack allocation and heap
allocation and you must overload your
operators to handle all situations and
not cause memory leaks. Difficult
indeed.</p>
</blockquote>
<p>I do not understand how operator overloading has anything to do with memory allocation. Can anyone please explain how they are correlated?</p>
| <p>I can imagine a couple possible interpretations:</p>
<p>First, in C++ <code>new</code> and <code>delete</code> are both actually operators; if you choose to provide custom allocation behavior for an object by overloading these operators, you must be very careful in doing so to ensure you don't introduce leaks.</p>
<p>Second, some types of objects require that you overload <code>operator=</code> to avoid memory management bugs. For example, if you have a reference counting smart pointer object (like the Boost shared_ptr), you must implement <code>operator=</code>, and you must be sure to do so correctly. Consider this broken example:</p>
<pre><code>template <class T>
class RefCountedPtr {
public:
RefCountedPtr(T *data) : mData(data) { mData->incrRefCount(); }
~RefCountedPtr() { mData->decrRefCount(); }
RefCountedPtr<T>& operator=(const RefCountedPtr<T>& other) {
mData = other.mData;
return *this;
}
...
protected:
T *mData;
};
</code></pre>
<p>The <code>operator=</code> implementation here is broken because it doesn't manage the reference counts on <code>mData </code> and <code>other.mData</code>: it does not decrement the reference count on <code>mData</code>, leading to a leak; and it does not increment the reference count on <code>other.mData</code>, leading to a possible memory fault down the road because the object being pointed to could be deleted before all the actual references are gone.</p>
<p>Note that if you do not explicitly declare your own <code>operator=</code> for your classes, the compiler will provide a default implementation which has behavior identical to the implementation shown here -- that is, completely broken for this particular case.</p>
<p>So as the article says -- in some cases you must overload operators, and you must be careful to handle all situations correctly.</p>
<p><b>EDIT</b>: Sorry, I didn't realize that the reference was an online article, rather than a book. Even after reading the full article it's not clear what was intended, but I think Eckel was probably referring to situations like the second one I described above.</p>
|
Django ORM: caching and manipulating ForeignKey objects <p>Consider the following skeleton of a models.py for a space conquest game:</p>
<pre><code>class Fleet(models.Model):
game = models.ForeignKey(Game, related_name='planet_set')
owner = models.ForeignKey(User, related_name='planet_set', null=True, blank=True)
home = models.ForeignKey(Planet, related_name='departing_fleet_set')
dest = models.ForeignKey(Planet, related_name='arriving_fleet_set')
ships = models.IntegerField()
class Planet(models.Model):
game = models.ForeignKey(Game, related_name='planet_set')
owner = models.ForeignKey(User, related_name='planet_set', null=True, blank=True)
name = models.CharField(max_length=250)
ships = models.IntegerField()
</code></pre>
<p>I have many such data models for a project I'm working on, and I change the state of the game based on somewhat complicated interactions between various data objects. I want to avoid lots of unnecessary calls to the database, so once per turn, I do something like</p>
<ol><li>Query all the fleets, planets, and other objects from the database and cache them as python objects</li>
<li>Process the game objects, resolving the state of the game</li>
<li>Save them back in the database</li>
</ol>
<p>This model seems to totally break down when using ForeignKey objects. For example, when a new fleet departs a planet, I have a line that looks something like this:</p>
<pre><code>fleet.home.ships -= fleet.ships
</code></pre>
<p>After this line runs, I have other code that alters the number of ships at each of the planets, including the planet fleet.home. Unfortunately, the changes made in the above line are not reflected in the QuerySet of planets that I obtained earlier, so that when I save all the planets at the end of the turn, the changes to fleet.home's ships get overwritten.</p>
<p>Is there some better way of handling this situation? Or is this just how all ORMs are?</p>
| <p>Django's ORM does not implement an <a href="http://en.wikipedia.org/wiki/Identity%5Fmap">identity map</a> (it's in the <a href="http://code.djangoproject.com/ticket/17">ticket tracker</a>, but it isn't clear if or when it will be implemented; at least one core Django committer has <a href="http://spreadsheets.google.com/ccc?key=pSqnCvef6OXmGWQ9qbEVMeA">expressed opposition to it</a>). This means that if you arrive at the same database object through two different query paths, you are working with different Python objects in memory.</p>
<p>This means that your design (load everything into memory at once, modify a lot of things, then save it all back at the end) is unworkable using the Django ORM. First because it will often waste lots of memory loading in duplicate copies of the same object, and second because of "overwriting" issues like the one you're running into.</p>
<p>You either need to rework your design to avoid these issues (either be careful to work with only one QuerySet at a time, saving anything modified before you make another query; or if you load several queries, look up all relations manually, don't ever traverse ForeignKeys using the convenient attributes for them), or use an alternative Python ORM that implements identity map. <a href="http://www.sqlalchemy.org/">SQLAlchemy</a> is one option.</p>
<p>Note that this doesn't mean Django's ORM is "bad." It's optimized for the case of web applications, where these kinds of issues are rare (I've done web development with Django for years and never once had this problem on a real project). If your use case is different, you may want to choose a different ORM.</p>
|
Error in C Program <p><code>while(((long)(1000*ratio*((long)clock()-(long)t0))%100)/1000)<Data_Read_Rate);</code></p>
<p>The above line is generating the following error:
"Syntax Error before < token".</p>
<p>Why is this error coming up?</p>
<p>I use MINGW32 for development(GCC compiler).</p>
<p>Thanks...</p>
| <p>One paren is missing on the left. This will parse:</p>
<pre><code>while ((((long)(1000*ratio*((long)clock()-(long)t0))%100)/1000)<Data_Read_Rate);
</code></pre>
<p>Aside from the parse issue:</p>
<ul>
<li>Use an editor that highlights matching parentheses :)</li>
<li>Why not calculate the time remaining until the data read rate has dropped sufficiently, and call sleep()? That's nicer on the processor.</li>
</ul>
<p>Also, considering your use of the % operator, you may want to have the extra paren placed like so (I'm assuming <em>ratio</em> is not an integer), because the % operator requires integer operands:</p>
<pre><code>while (((long)(1000*ratio*(((long)clock()-(long)t0))%100)/1000)<Data_Read_Rate);
</code></pre>
<p>(But does that make sense on a semantic level? Chop it up!)</p>
|
Function Point Analysis in SAS <p>Would some be able to help me with some links on how FPA is done for SAS related projects.If someone of yuo have already done I guess it would be even more usefull if yuo could share some tips on how it could be done</p>
| <p>I think the question is a bit too broad. FPA is a big subject area and has some general guidelines around how it is conducted. ( See a good article here: <a href="http://www.qpmg.com/fp-intro.htm" rel="nofollow">clicky</a> ) I don't know of any specific examples where SAS was incorporated. However this type of analysis lends itself more to the processes and software functions and therefore is fairly language agnostic. </p>
<p>Maybe we could discuss this in more detail if we talked about a specific SAS program, macro or operation.</p>
|
order by case and alias <p>How can I use</p>
<pre><code>ORDER BY
CASE @AccountOperator
WHEN '>' THEN AccountTrxValue
END ASC,
CASE @AccountOperator
WHEN '<' THEN AccountTrxValue
END DESC
</code></pre>
<p>when AccountTrxValue is an alias and a result of the following in the "select"?</p>
<pre><code>CASE WHEN PAA.RedeemValue>0 THEN
PAA.RedeemValue * -1
ELSE PAA.EarnValue END
AS AccountTrxValue ,
</code></pre>
<p>It dosesn't accept the alias because of the case</p>
<p>(without using sub query) </p>
<h2>EDIT:</h2>
<p>so someone answered me and I did it that way:</p>
<pre><code>ORDER BY
CASE
WHEN @AccountOperator IS NULL OR @AccountOperator IN ('>','=') THEN
CASE WHEN PAA.RedeemValue>0 THEN
PAA.RedeemValue * -1
ELSE PAA.EarnValue END
END DESC,
CASE
WHEN @AccountOperator = '<'THEN
CASE WHEN PAA.RedeemValue>0 THEN
PAA.RedeemValue * -1
ELSE PAA.EarnValue END
END
</code></pre>
<p>How can I write it in a shorter way?
*I couldn't include the null in the "in"
* I had to do 2 cases because it seems that "desc" should be written after the "end"</p>
| <pre><code>ORDER BY
CASE @AccountOperator
WHEN '>' THEN AccountTrxValue
WHEN '<' THEN -AccountTrxValue
END
</code></pre>
<p>You should be allowed to use column aliases in the ORDER BY clause, assuming SQL Server</p>
<p>Otherwise:</p>
<pre><code>ORDER BY
CASE @AccountOperator
WHEN '>' THEN
CASE WHEN PAA.RedeemValue>0 THEN
PAA.RedeemValue * -1
ELSE PAA.EarnValue END
WHEN '<' THEN
-CASE WHEN PAA.RedeemValue>0 THEN
PAA.RedeemValue * -1
ELSE PAA.EarnValue END
END
</code></pre>
<p>Edit:</p>
<p>The -AccountTrxValue or -CASE WHEN PAA.RedeemValue>0... simply negates the value. This means the default ASC works like a DESC...</p>
<p>Edit2:
General case for non-numerics</p>
<pre><code>DECLARE @Switch char(1);
SELECT @Switch = '<';
SELECT
*,
ROW_NUMBER() OVER (ORDER BY SortCol ASC) AS SortASC,
ROW_NUMBER() OVER (ORDER BY SortCol DESC) AS SortDESC
FROM
dbo.tablename
ORDER BY
CASE @Switch
WHEN '<' THEN ROW_NUMBER() OVER (ORDER BY SortCol ASC)
WHEN '>' THEN ROW_NUMBER() OVER (ORDER BY SortCol DESC)
ELSE 0
END;
</code></pre>
|
Explicit nulling <p>In what situations in java is explicit nulling useful. Does it in any way assist the garbage collector by making objects unreachable or something? Is it considered to be a good practice?</p>
| <p>In Java it <em>can</em> help if you've got a very long-running method, and the only reference to the an object is via a local variable. Setting that local variable to null when you don't need it any more (but when the method is going to continue to run for a long time) <em>can</em> help the GC. (In C# this is very rarely useful as the GC takes "last possible use" into account. That optimization may make it to Java some time - I don't know.)</p>
<p>Likewise if you've got a member field referring to an object and you no longer need it, you could potentially aid GC by setting the field to null.</p>
<p>In my experience, however, it's rarely <em>actually</em> useful to do either of these things, and it makes the code messier. Very few methods <em>really</em> run for a long time, and setting a variable to null really has nothing to do with what you want the method to achieve. It's not good practice to do it when you don't need to, and if you <em>do</em> need to you should see whether refactoring could improve your design in the first place. (It's possible that your method or type is doing too much.) </p>
<p>Note that setting the variable to null is entirely passive - it doesn't inform the garbage collector that the object can be collected, it just avoids the garbage collector seeing that reference as a reason to keep the object alive next time it (the GC) runs.</p>
|
2 Mutually exclusive RadioButton "Lists" <p>I think this has to be THE most frustrating thing I've ever done in web forms. Yet one would think it would be the easiest of all things in the world to do. That is this:</p>
<p>I need 2 separate lists of radiobuttons on my .aspx page. One set allows a customer to select an option. The other set does also but for a different purpose. But only one set can have a selected radiobutton.</p>
<p>Ok I've tried this using 2 asp.net Radiobuttonlists controls on the same page. Got around the nasty bug with GroupName (asp.net assigns the control's uniqueID which prevents the groupname from ever working because now, 2 radiobuttonlists can't have the same groupname for all their radiobuttons because each radiobuttonlist has a different uniqueID thus the bug assigns the unique ID as the name attribute when the buttons are rendered. since the name sets are different, they are not mutually exclusive). Anyway, so I created that custom RadioButtonListcontrol and fixed that groupname problem.</p>
<p>But when ended up happening is when I went to put 2 instances of my new custom radiobuttonlist control on my .aspx page, all was swell until I noticed that every time I checked for radiobuttonlist1.SelectedValue or radiobuttonlist2.SelectedValue (did not matter which I was checking) the value always spit back string.empty and i was not able to figure out why (see <a href="http://forums.asp.net/t/1401117.aspx" rel="nofollow">http://forums.asp.net/t/1401117.aspx</a>).</p>
<p>Ok onto the third try tonight and into the break of dawn (no sleep). I tried to instead just scrap trying to use 2 custom radiobuttonlists altogether because of that string.empty issue and try to spit out 2 sets of radiobuttonlists via using 2 asp.net repeaters and a standard input HTML tag inside. Got that working. Ok but the 2 lists still are not mutually exclusive. I can select a value in the first set of radiobuttons from repeater1 and same goes for repeater2. I cannot for the life of me get the "sets" to be mutually exclusive sets of radiobuttons.</p>
| <p>As you have two groups of radio buttons that you want to function as one group of radio buttons, the solution is simple: Make it one group of radio buttons.</p>
<p>The only problem you have then is that the value that you get has the same name from both lists, but that can be solved by adding a prefix to the values so that you easily identify from which list the option comes.</p>
|
where can I find a good delphi library? <p>I'm using delphi6, and it lacks the following abilities:</p>
<ul>
<li>a library object,</li>
<li>a list object(looks like TList,TStringList is good enough?)</li>
<li>a algorithm library(like sort,) </li>
<li>template library like STL</li>
<li>dynamic language feature or GC.</li>
<li>and so on.</li>
</ul>
<p>how can I find this things?</p>
| <p>Try <a href="http://sourceforge.net/projects/jcl/" rel="nofollow">Jedi Code Library</a>. There are good replacements for container classes and sorting algorithms. I don't think there is GC or STL-like library for Delphi 6. </p>
<p>Delphi 6 is behind the times, check <a href="http://www.codegear.com/products/delphi/win32" rel="nofollow">Delphi 2009</a> or at least <a href="http://www.turboexplorer.com/delphi" rel="nofollow">Turbo Delphi</a></p>
|
Django Imagefield not working properly via ModelForm <p>I'm certain I'm doing something really obviously stupid, but I've been trying to figure it out for a few hours now and nothing is jumping out at me.</p>
<p>I'm using a ModelForm so I can expose a few fields from a model for editing. 2x ImageField, 1x TextField. The Form is processed and the TextField works. The two ImageFields do not work and they're why I'm here today.</p>
<p>I'm using Django 1.0.2</p>
<p>Here's the relevant code (ask if you need more -- and I'm not including the HTML because that part appears to work fine):</p>
<p>Model:</p>
<pre><code>class Company(models.Model):
#...
logo = models.ImageField(upload_to='logos', blank=True)
intro_pic = models.ImageField(upload_to='intropics', blank=True)
intro_text = models.TextField(blank=True)
</code></pre>
<p>View and form:</p>
<pre><code>def admin_edit(request, company_slug):
company = get_object_or_404(Company, slug = company_slug)
f = AdminEditForm(instance = company)
if request.method == 'POST':
f = AdminEditForm(request.POST, instance = company)
if f.is_valid():
print "Processing form"
print f.cleaned_data['intro_pic']
f.save()
return render_to_response('uadmin/edit.html', {'company':company, 'f':f}, RequestContext(request))
class AdminEditForm(ModelForm):
class Meta:
model = Company
fields = ['logo', 'intro_pic', 'intro_text']
</code></pre>
| <p>Well I feel like an idiot. In order for Django to be able to process uploaded files, you need to pass the request.FILES variable to the form (makes sense, right?!) </p>
<p>In my case the following line goes from:</p>
<pre><code>f = AdminEditForm(request.POST, instance = company)
</code></pre>
<p>To:</p>
<pre><code>f = AdminEditForm(request.POST, request.FILES, instance = company)
</code></pre>
<p>Another thing to check (if you run into something like this in the future) is that your form is multipart. Your <code><form></code> tag should look something like this:</p>
<pre><code><form enctype="multipart/form-data" method="post" action="">
</code></pre>
|
MSBuild, properties and imported files <p>Is it possible to run an msbuild task that populates a property or Item from an imported file "A" and then use these values in another file which imports file "A"?</p>
<p>EDIT: FileX imports FileA and FileY imports FileA. One of FileA's property is changed in FileX. Can this changed value be accessed in FileY</p>
| <p>Sorry its a bit confusing: </p>
<p>Are you saying FileX imports FileA and FileY imports FileA. FileX sets property P in FileX but FileY reads it? If there is no relationship between X & Y then the only way to do it would be use the fact that properties in MSBUILD overlap with evironment vars. So possbly calling </p>
<pre><code><exec ... setx.exe Propertyname SomeValue.... /> in fileA and the $(Propertyname) in FileB
</code></pre>
|
Different format for whole numbers and decimal <p>is there a way of formatting a string to show whole numbers of a decimal number if it follows 00.</p>
<p>example show 10 if number is 10.00.
but show 10.2 if number is 10.2</p>
<p>this is for c#, asp.net</p>
| <p>In .NET:</p>
<pre><code>if (Math.Floor(d) == d)
return d.ToString("0");
else
return d.ToString();
</code></pre>
|
Listen to events from preloader in flex <p>I have a preloader in my flex application:</p>
<pre><code>public class Preloader extends DownloadProgressBar
{
private var _preloader:PreloaderAnimation;
public function Preloader()
{
super();
_preloader = new PreloaderAnimation;
addChild(_preloader);
}
public override function set preloader(preloader:Sprite):void
{
preloader.addEventListener(ProgressEvent.PROGRESS , onSWFDownloadProgress );
preloader.addEventListener(Event.COMPLETE , onSWFDownloadComplete );
preloader.addEventListener(FlexEvent.INIT_PROGRESS , onFlexInitProgress );
preloader.addEventListener(FlexEvent.INIT_COMPLETE , onFlexInitComplete );
}
.........
private function onFlexInitComplete( event:FlexEvent ):void
{
dispatchEvent(new Event(Event.COMPLETE));
}
}
</code></pre>
<p>When the Flex Initialize is complete the preloader dispatches an Event.COMPLETE. But I want to be able to listen to the event in my flex app and do stuff when it dispatches. When it dispatches the preloader removes itself that's why its crucial. Any idea on how I could listen from my flex app?</p>
<p>Regards Adlertz</p>
| <p>The Preloader's INIT_COMPLETE event is fired after the preloader receives the Application's CREATION_COMPLETE event.</p>
<p>The order of initialisation is this:</p>
<ul>
<li>Preloader starts loading your app;</li>
<li>Application downloaded, starts initialising;</li>
<li>Application is initialised, dispatches CREATION_COMPLETE;</li>
<li>Preloader receives Application.CREATION_COMPLETE, dispatches INIT_COMPLETE;</li>
<li>Your preloader class receives the Preloader's INIT_COMPLETE;</li>
<li>Your preloader dispatches the COMPLETE event;</li>
<li>The Preloader removes your preloader class and dispatches the (private) PRELOADER_DONE event;</li>
<li>Your application is displayed.</li>
</ul>
<p>What this means in this case is that the Application.CREATION_COMPLETE is equivalent to the Preloader.INIT_COMPLETE - if you want to know when the preloader dispatches INIT_COMPLETE then listen for CREATION_COMPLETE.</p>
<p>You can confirm all of this by looking through the source code for the Preloader class.</p>
|
Object Validation <p>I have an object which i need to validate. This object has properties which cannot be null, strings which cannot exceed a given size and date strings which i need to check for format correctness.</p>
<p>How would you perform this validation. I don't want to go over the whole object, I'm looking for something more dynamic</p>
<p>EDIT:</p>
<p>This object will be used in webservices input so any setter validation will be useless also i dont know how the system will behave with the added dependency of any annotation based system</p>
<p>Im looking for a custom solution (yes i know reinventing the wheel)</p>
| <p>Without the exact scenario, I can recommend you use the object's setter methods (you <em>did</em> make the fields private, right?) to validate every change to the values. the String setters can call the length-validating code, the Date setters can call the format-validating code, etc.</p>
<p>Hope this helps,</p>
<p>Yuval =8-)</p>
|
Access events added with attachEvent() / addEventListener() in JavaScript <p>How can I access events added with <code>attachEvent()</code> / <code>addEventListener()</code> in JavaScript?</p>
<p>Use case: debug events using FireBug's console.</p>
| <p>There is no way to access them. </p>
<p>Depending on what you're trying to achieve, better way to debug the events might be to output the <a href="http://www.quirksmode.org/js/events%5Fproperties.html">event properties</a> you're interested in from the event handler function...</p>
|
How to use 2 C libs that export the same function names <p><strong>Duplicate of the following question: <a href="http://stackoverflow.com/questions/678254/c-function-conflict">C function conflict</a></strong></p>
<p><hr /></p>
<p>Hi,
in my current project I have to use some kind of interface lib. The function names are given by this interface, what this functions do is developers choice. As far as I can tell a project shall use this functions and when it comes to compiling you choose the lib and with it the functionality. What I try to do is to use an existing lib and my lib at the same time by wrapping the other and call it in mein functions:</p>
<p>otherlib:</p>
<pre><code>int function1 (int a) {
// do something
}
</code></pre>
<p>mylib:</p>
<pre><code>int function1 (int a) {
//my code here
otherlib::function1(a);
}
</code></pre>
<p>Problem is I don't have access to the other lib and the other lib doesn't have any namespaces. I already tried</p>
<pre><code>namespace old {
#include "otherlib.h"
}
</code></pre>
<p>and then call the old function by old::function1 in my function. This works as long as it's only header file. The lib exports it's symbol back into global space. Also something like</p>
<pre><code>namespace new {
function1 (int a) {
::function1(a);
}
}
</code></pre>
<p>didn't work. Last but not least I tried ifdefs and defines suggested <a href="http://stackoverflow.com/questions/189921/how-to-handle-a-class-name-conflict-when-porting-old-code">here</a></p>
<p>but I wasn't successful.</p>
<p>Any ideas how to solve this? Thanks in advance.</p>
<p>EDIT: I neither have access to the old lib nor the project both libs shall be used in.</p>
<p>EDIT2: at least the old lib is a static one</p>
| <p>Namespaces in C solved using library names prefixes like:</p>
<p>libfoo --> foo_function1<br />
libbar --> bar_function1</p>
<p>These prefixes are actual namespaces. so if you write libbar</p>
<pre><code>int bar_function1(int a) {
function1(a);
}
</code></pre>
<p>This is the way to solve problems.</p>
<p>C has namespaces --- they just called prefixes ;)</p>
<p>Another option is to do various dirty tricks with dynamic loading of libraries like:</p>
<pre><code>h1=dlopen("libfoo.so")
foo_function1=dlsym(h1,"function1")
h2=dlopen("libbar.so")
bar_function1=dlsym(h2,"function1")
</code></pre>
|
Game map from Code <p>It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;)</p>
<p>I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things. Currently the map is created using a background image with CSS positioning of team icons on top of that to represent cities. You can see how it looks here: <a href="http://woarl.com/map/turn%5F32%5Fnormal.html" rel="nofollow">WoA Map</a></p>
<p>The background image for the map is located here: <a href="http://woarl.com/map/images/theMap.jpg" rel="nofollow">Map background</a> and created in <a href="http://www.omnigroup.com/applications/omnigraffle/" rel="nofollow">Omnigraffle</a>. It's not designed to draw maps but I'm hopelessly incompetent with photoshop and this works for my purposes just fine.</p>
<p>The problem comes that I want to perform such fun things as pathfinding and for that I need to have the map somehow stored in code. I have tried using <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>, I have looked at incorporating it with <a href="http://www.blender.org/" rel="nofollow">Blender</a>, I tried going "old school" and creating tiles as from many older games and finally I tried to use SVG. I say this so you can see clearly that it's not through lack of trying that I have this problem ;)</p>
<p>I want to be able to store the map layout in code and both create an image from it and use it for things such as pathfinding. I'm using Python but I suspect that most answers will be generic. The cities other such things are stored already and easily drawn on, I want to store the layout of the landmass and features on the landmass.</p>
<p>As for pathfinding, each type of terrain has a movement cost and when the map is stored as just an image I can't access the terrain of a given area. In addition to pathfinding I wish to be able to know the terrain for various things related to the game, cities in mountains produce stone for example.</p>
<p>Is there a good way to do this and what terms should I have used in Google because the terms I tried all came up with unrelated stuff (mapping being something completely different most of the time).</p>
<p>Edit 2:
Armies can be placed anywhere on the map as can cities, well, anywhere but in the water where they'd sink, drown and probably complain (in that order).</p>
<p>After chatting to somebody on MSN who made me go over the really minute details and who has a better understanding of the game (owing to the fact that he's played it) it's occurring to me that tiles are the way to go but not the way I had initially thought. I put the bitmap down as it is now but also have a data layer of tiles, each tile has a given terrain type and thus pathfinding and suchlike can be done on it yet at the same time I still render using Omnigraffle which works pretty well.</p>
<p>I will be making an editor for this as suggested by <a href="http://stackoverflow.com/users/66634/adam-smith">Adam Smith</a>. I don't know that graphs will be relevant <a href="http://stackoverflow.com/users/62014/xynth">Xynth</a> but I've not had a chance to look into them fully yet.</p>
<p>I really appreciate all those that answered my question, thanks.</p>
| <p>I'd store a game map in code as a <a href="http://en.wikipedia.org/wiki/Graph%5F%28mathematics%29" rel="nofollow">graph</a>. </p>
<p>Each node would represent a country/city and each edge would represent adjacency. Once you have a map like that, I'm sure you can find many resources on AI (pathfinding, strategy, etc.) online.</p>
<p>If you want to be able to build an image of the map programattically, consider adding an (x, y) coordinate and an image for each node. That way you can display all of the images at the given coordinates to build up a map view.</p>
|
Constructor chaining with "this" <p>Why does the first constructor in ClassA cause the compiler error 'cannot use "this" in member intializer'?</p>
<p>... or how can i get this to work?</p>
<p>Thanks</p>
<pre><code>public sealed class ClassA : IMethodA
{
private readonly IMethodA _methodA;
public ClassA():this(this)
{}
public ClassA(IMethodA methodA)
{
_methodA = methodA;
}
public void Run(int i)
{
_methodA.MethodA(i);
}
public void MethodA(int i)
{
Console.WriteLine(i.ToString());
}
}
public interface IMethodA
{
void MethodA(int i);
}
</code></pre>
| <p>You are allowed to use the <code>this(...)</code> syntax to invoke another constructor at the same level - however, you cannot use <code>this</code> (the current instance) in this context.</p>
<p>The easiest option here is to duplicate the assignment code (<code>_methodA = methodA</code>).</p>
<p>Another option might be null-coalescing:</p>
<pre><code>public ClassA():this(null)
{}
public ClassA(IMethodA methodA)
{ // defaults to "this" if null
_methodA = methodA ?? this;
}
</code></pre>
|
Why is Internet Explorer 6 still a corporate favorite in some organizations? <p>... or</p>
<p>How can I convince my organization to ditch Internet Explorer 6?</p>
<p>Having to maintain Internet Explorer 6 compatibility when developing web applications is a nightmare - but until my client decides to ditch it as the official browser, I am stuck with it. I am trying to convince our system administrators to change. I've seen a long list of arguments against using Internet Explorer 6 in any environment, and I am trying to anticipate their arguments rebuttals.
So far, the only perceived advantages I can see in Internet Explorer 6 are:</p>
<ol>
<li>Central management through group policies</li>
<li>Legacy application compatibility</li>
</ol>
<p>Both of these are addressed by Internet Explorer 7 or later (AFAIK).</p>
<p>Are there any advantages that Internet Explorer 6 has that are not already addressed by Internet Explorer 7 or later?</p>
| <p>Internet Explorer 6 has been around for ages, and the vast majority of websites and web applications work correctly with it.</p>
<p>In order to change to a different browser (which, BTW, will probably be Internet Explorer 7), you need to, first of all, do a cost benefit analysis to justify this decision to everyone's bosses.</p>
<p>A really high level summary:</p>
<p>Cost:</p>
<ul>
<li>Test all web applications.</li>
<li>Check all third-party websites actually work in the new browser.</li>
<li>Check all other software, to see if there are any underlying issues with moving to a new browser.</li>
</ul>
<p>Benefits:</p>
<ul>
<li>Multi tabs?</li>
</ul>
<p>Honestly, I can't see this happening, unless a corporation is doing a desktop refresh which happens periodically.</p>
|
Where are the asp.net Dynamic Data limits? <p>What are the limitations of asp.net dynamic data?<br />
What is not possible to do in dynamic data, so that you have to use web forms?</p>
| <p>Not sure what you mean DD just sits on top standard ASP.Net site so you can switch in an out of DD, the really great flexibility is that you can just use the bits of DD you need in your ASP.Net project (you don't need to scaffold the site) you can just make use of the business rules and FieldTemplate to speed developement of you site. For instance in a DetailsView when editing a table getting a dropdown list to select from a related table is always a pain in ASp.Net but is mix in a little DD you get that for free. :D
see my blog here <a href="http://csharpbits.notaclue.net/2008/07/part-3-standard-aspnet-page-with.html" rel="nofollow">Custom Pages Part 3 - Standard ASP.Net Page with Dynamic Data features added to take advantage of the FieldTemplates.</a></p>
|
C# to format (indent, align) C# properly <p>We have a code generator that <a href="http://www.codegeneration.net/tiki-index.php?page=CodeMungerModel" rel="nofollow">munges</a> the schema of a given database to automate our inhouse n-tier architecture. The output is various C# partial classes, one per file. </p>
<p>In the code to munge all the strings, we try and keep on top of the indenting and formatting as much as possible, but invariably when you come to open the file in Visual Studio the formatting is awry. A quick ctrl-k, ctrl-d fixes it, but obviously this reformatting is lost the next time the class is generated.</p>
<p>What I'd like to know, is if there's a way I can somehow automatically format the contents of the textfile in the same way Visual Studio does? </p>
<p>Pseudocode</p>
<pre><code>Create "code" object, passing text file to constructor
Invoke "format" method
Re-save text file
</code></pre>
<p>Any help greatly appreciated.</p>
<p><strong>EDIT:</strong>
I should clarify - I want to be able to invoke the formatting from my C# code that creates the textfile containing my generated C#. The format of the code can be standardised (doesn't have to be per-developer), and I don't want to have to install any 3rd-party apps.</p>
<p>I seem to remember there's a namespace containing loads of classes for creating C# in C#: <a href="http://msdn.microsoft.com/en-us/library/system.codedom" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.codedom</a>(VS.80).aspx, but I'm not sure if it contains any classes that could help.</p>
<p><strong>FURTHER EDIT:</strong>
My code generator is a winforms app deployed via a click-once install. It's used by many developers in-house. I need a solution that doesn't require each developer to have a tool installed on their machine.</p>
| <p>Take a look at <a href="http://www.narrange.net/" rel="nofollow">Narrange</a>.You'll probably need to automate these things as part of the build.<br />
Not sure if it meets all your requirements though.<br />
<em>To quote:</em></p>
<blockquote>
<p>NArrange is a .NET code beautifier
that automatically organizes code
members and elements within .NET
classes.</p>
</blockquote>
|
Safe JavasScript that calls PHP script that calls external web service <p>I have a PHP page that needs to make a call to a external web service. This Web service call takes a bunch of sensitive data from a html form on the PHP page, e.g. SSN, and returns info related to that person.</p>
<p>The problem is that the web service call should be made as soon as the customer fills in the SSN field and the field loses focus, so the page cannot be reloaded in any way. I was thinking about using jQuery to make a call to the web service, but AJAX unfortunately requires that you are on the same domain as the requested resource. So I'm thinking about creating an local PHP page that makes the call to the web service and then use JQuery to call this new page.</p>
<p>Questions:</p>
<ol>
<li><p>How do I use JQuery to call the local PHP script that makes the call to the web service?</p></li>
<li><p>Because the JQuery code will take sensitive data from a html form and send it to the PHP script, how can I encrypt the data?</p></li>
</ol>
| <p>1) $.get("myscript.php", function(response) { alert(response) });</p>
<p>2) I wouldn't encrypt using jQuery, it would be slow and easy to decrypt. Enabling SSL on the server would be a better solution.</p>
|
Use C++ CLI template class in C# <p>I have the following class in C++/CLI and an explicit template instantiation for the int primitive..</p>
<pre><code>template<typename T>
public ref class Number
{
T _value;
public:
static property T MinValue
{
T get()
{
return T::MinValue;
}
}
static property T MaxValue
{
T get()
{
return T::MaxValue;
}
}
property T Value
{
T get()
{
return _value;
}
void set(T value)
{
if( value<MinValue || value > MaxValue)
throw gcnew System::ArgumentException("Value out of range");
_value = value;
}
}
};
template ref class Number<int>;
</code></pre>
<p>On compiling this and inspecting the generated assembly using reflector I am able to see a class called <code>Number<int></code> but while trying to instantiate this same class in C# the compiler complains about some <code>System::Number</code> class not taking a template argument. What am I doing wrong? Can this be done at all?</p>
| <p>Reflector is <em>lying</em> a little bit here. The name of the class is not actually Number<int>. It is actually 'Number<int>'. Notice the single quotes. These are only visible when you view the type name with ildasm. </p>
<p>I <strong>believe</strong> this is done to make the type unbindable in most languages as they have no way of understanding how a C++ template actually works. This makes it effectively only visible to the C++ compiler which is appropriate since it's the only MS compiler that actually supports templates (templates != generics). </p>
|
TFS Branch/Merge meets History View <p>We have a setup with a development "trunk" in our recently-migrated-to-from-VSS TFS system and developers have been doing work in branches off the trunk, which are merged back in.</p>
<p>We've been diligently commenting our changesets at check in time, something we never did in the VSS days. However when I right-click on a trunk file in the Source Control Explorer and choose History, I only see monolithic changesets labeled "merge from dev branch" (or whatever the developer scribbled in there when they merged.) A history entry doesn't even seem to contain info on <em>which</em> branch was merged in at that time, let alone any info about the changesets that make it up, or the comments that go with them.</p>
<p>How have other TFS users dealt with this issue? </p>
<p>Is there another way to view the history that I'm missing here? </p>
| <p>Looking at the history of a change prior to the merge has been a bit of a pain point with TFS. So much so that Microsoft have done a lot of work to address this in the next version of TFS (TFS 2010). In TFS 2010 (when it comes out), when you get to a merge in the history view it is actually a little twistie that you can expand and go see the history for the thing that was merged which is much nicer.</p>
<p>In the meantime, when I see I big monolithic merge (or branch) comment I tend to let out a audible sigh and then go find the file in the branch it was merged from in Source Control Explorer and do a view history there.</p>
|
Interface naming convention <p>This is a subjective thing of course, but I don't see anything positive in prefixing interface names with an 'I'. To me, <code>Thing</code> is practically always more readable than <code>IThing</code>.</p>
<p>My question is, why does this convention exist then? Sure, it makes it easier to tell interfaces from other types. But wouldn't that argument extend to retaining the Hungarian notation, which is now widely censured?</p>
<p>What's your argument for that awkward 'I'? Or, more importantly, what could be Microsoft's?</p>
| <p>Conventions (and criticism against them) all have a reason behind them, so let's run down some reasons behind conventions</p>
<ul>
<li><p><strong>Interfaces are prefixed as I to differentiate interface types from implementations</strong> - e.g., as mentioned above there needs to be an easy way to distinguish between <code>Thing</code> and its interface <code>IThing</code> so the convention serves to this end.</p></li>
<li><p><strong>Interfaces are prefixed I to differentiate it from abstract classes</strong> - There is ambiguity when you see the following code:</p>
<p><code>public class Apple: Fruit</code></p>
<p>Without the convention one wouldn't know if <code>Apple</code> was <em>inheriting</em> from another class named <code>Fruit</code>, or if it were an <em>implementation</em> of an interface named <code>Fruit</code>, whereas <code>IFruit</code> will make this obvious:</p>
<p><code>public class Apple: IFruit</code></p>
<p>Principle of least surprise applies.</p></li>
<li><p><strong>Not all uses of hungarian notation are censured</strong> - Early uses of Hungarian notation signified a prefix which indicated the type of the object and then followed by the variable name or sometimes an underscore before the variable name. This was, for certain programming environments (think Visual Basic 4 - 6) useful but as true object-oriented programming grew in popularity it became impractical and redundant to specify the type. This became especially issue when it came to intellisense.</p>
<p>Today hungarian notation is acceptable to distinguish UI elements from actual data and similarly associated UI elements, e.g., <code>txtObject</code> for a textbox, <code>lblObject</code> for the label that is associated with that textbox, while the data for the textbox is simply <code>Object</code>.</p>
<p>I also have to point out that the original use of Hungarian notation wasn't for specifying data types (called System Hungarian Notation) but rather, specifying the semantic use of a variable name (called Apps Hungarian Notation). Read more on it on the <a href="http://en.wikipedia.org/wiki/Hungarian%5Fnotation">wikipedia entry on Hungarian Notation</a>.</p></li>
</ul>
|
How can one implement a Compact Directed Acyclic Word Graph (CDAWG) in C? <p>How would one implement <a href="http://www.i.kyushu-u.ac.jp/~takeda/papers/PSC01.pdf" rel="nofollow">this data structure</a> in C? It is a structure similar to but twice as space-efficient as the DAWG, that is more efficient than the trie which only compresses prefixes.</p>
| <p>From what I can see from this <a href="http://www.i.kyushu-u.ac.jp/~takeda/papers/PSC01.pdf">paper</a></p>
<p>It's a trie with suffix compression to reduce the final state changes for a match, since I'd worked on something similar that, I had also considered doing that to save space. This was the solution I had thought of for the data structure, I'm interested to see if there are other approaches:</p>
<pre><code>struct cdawg
{
int issuffix:1;
int length:31;
char *s; // suffix if issuffix == 1, else array of valid transition chars
struct cdawg *trans; // array of next states based on the index of trans char in s, null if suffix
};
</code></pre>
|
How to programmatically get SVN revision description and author in c#? <p>How do I programmatically get the revision description and author from the SVN server in c#?</p>
| <p>Using <a href="http://sharpsvn.net/" rel="nofollow">SharpSvn</a>:</p>
<pre><code>using(SvnClient client = new SvnClient())
{
Collection<SvnLogEventArgs> list;
// When not using cached credentials
// c.Authentication.DefaultCredentials = new NetworkCredential("user", "pass")l
SvnLogArgs la = new SvnLogArgs { Start = 128, End = 132 };
client.GetLog(new Uri("http://my/repository"), la, out list);
foreach(SvnLogEventArgs a in list)
{
Console.WriteLine("=== r{0} : {1} ====", a.Revision, a.Author);
Console.WriteLine(a.LogMessage);
}
}
</code></pre>
|
Binding DropDownList to an Enumeration <p>How do i bind a regular asp.net dropdownlist to an enum?</p>
| <p>This page explains it well:</p>
<p><a href="http://geekswithblogs.net/jawad/archive/2005/06/24/EnumDropDown.aspx" rel="nofollow">http://geekswithblogs.net/jawad/archive/2005/06/24/EnumDropDown.aspx</a></p>
|
Reader Writer Problem <p>Sorry if I am asking same question again but want to verify!</p>
<p>I have two processes P1 and P2.</p>
<p>P1 is a writer (Producer).<br />
P2 is a reader (Consumer).</p>
<p>There is some shared memory or a file that P1 writes to and as soon as P1 writes, P2 should be notified for reading.</p>
<p>Now as per my understanding pseudocode for P1 should be</p>
<pre>
Open shared file
Create a named event("Writedone") to signal write for P2 process
Do some processing on file
Mutex.Lock()
Write to File
Mutex.Unlock()
Signal named Event.
CloseHandle on file
</pre>
<p>Now in P2</p>
<pre>
Open handle to Shared file
Open handle to named event
WaitForSingleEvent on named event("Writedone")
Read from file
CloseHandle on file
</pre>
<p>Questions:</p>
<ol>
<li>Is it required to have locks in the reader? The reader will just read the file and not change it. So I guess no locks are required in the reader. Thoughts? Can it go wrong in some case without locks?</li>
<li>I am opening and closing handles to the file every time during reading and writing. I think that is not required. I can open the file handle in the constructor and close it in the destructor of reader and writer. But can I read from the file when it is being used in writing? </li>
</ol>
<p>EDIT: Everytime writer is writing 10 bytes at the end of File and reader is supposed to read the latest 10 bytes written by writer.</p>
| <p>The answer is: locking is necessary if (and only if) both threads can use the same shared resources at the same time. There isn't enough information about your specific implementation, but I have few remarks:</p>
<ol>
<li>Locking only during writing makes no sense. It only adds some overhead, but not prevent from any concurrent access until the reader is also correctly locked.</li>
<li>Locking would be necessary if file operations which modify structures connected with the file's descriptors are not synchronized in any way. It may happen that P1 could start writing to the file when P2 is still reading. If reading and writing operations modify the same system structures without any underlying synchronization you will end up with corrupted data. It's hard to say if this is the case here because you didn't mention which particular function (libraries) you used. File operations are synchronized on most systems, so it shouldn't be a problem.</li>
<li>From what you wrote about "10 bytes portions of information", the explicit locking seems to be not necessary (unless #2 doesn't impose it). P1 produces quantum of data. When the data is ready to be read P1 notifies P2 about that (by the event; event passing should be internally synchronized, anyhow). P2 knows that it could read quantum of data and then needs to wait for subsequent notification. It may happen that subsequent notification would be sent before previous one is handled. So, the events needs to be queued somehow. You can also use semaphore instead of events notification.</li>
</ol>
|
How many RewriteRules can you have in .htaccess without trouble? <p>Simple question. Is there a limit as to how many RewriteRules I can have in my .htaccess or can I put a zillion of them in there without Apache going all funky on me?</p>
<p>Is there a relative limit where the server simply dives because there are to many rules to iterate through?</p>
<p>Thanks!</p>
| <p>You have to know that the <a href="http://httpd.apache.org/docs/2.2/howto/htaccess.html#when">.htaccess configuration files are being processed on every request</a>.</p>
<p>So if you have a .htaccess file with 1000 rules, the worst case is that every 1000 rules are tested every time a request hits this directory.</p>
<p>Therefore you should use a structure where a rule matches a request as early as possible. Rules that handle more frequent requests should appear before those that are less frequent and determine the processing (see <a href="http://httpd.apache.org/docs/2.2/mod/mod%5Frewrite.html#rewriteflags"><code>L</code> flag</a>). Read about the <a href="http://httpd.apache.org/docs/2.2/rewrite/rewrite%5Ftech.html#InternalRuleset">ruleset processing</a> to know how the rules are being processed (see also <a href="http://httpd.apache.org/docs/2.2/mod/mod%5Frewrite.html#rewriteloglevel"><code>RewriteLogLevel</code> direcitve</a>).</p>
<p>Another factor are the regular expressions: Better use âsimpleâ and efficient regular expressions than ambiguous or complex ones. You should look into the how regular expressions are interpreted and processed to avoid costly ones and get the most out of them.</p>
|
WPF label counterpart for HTML "for" attribute <p>Is there some attribute in WPF that I can add to element, so when I click it the target control get focus? The closest thing I have found is 'Target', but it works only with access keys and clicking it has no effect.</p>
| <p>No, but an <a href="http://blogs.msdn.com/johngossman/archive/2008/05/07/the-attached-behavior-pattern.aspx" rel="nofollow">attached behavior</a> could be made to work for this.</p>
|
TDD in Visual Studio 2008 add-ins <p>I am trying to create an addin for Excel using Visual Studio 2008 and I would like to use Test Driven Development (TDD).</p>
<p>Pure TDD would start from an empty solution.<br />
The following methods are autogenerated when creating a shared addin project: </p>
<pre><code>public class Connect
{
public Connect(){ }
public void OnAddInsUpdate(ref System.Array custom){ }
public void OnBeginShutdown(ref System.Array custom){ }
public void OnConnection(
object application
, Extensibility.ext_ConnectMode
, connectMode
, object addInInst
, ref System.Array custom)
{
applicationObject = application;
addInInstance = addInInst;
}
public void OnDisconnection(
Extensibility.ext_DisconnectMode disconnectMode
, ref System.Array custom){ }
public void OnStartupComplete(ref System.Array custom){ }
}
</code></pre>
<p>How do I test these methods before actual writing any of my code for the addin?<br />
The addin will have a class WorkSheet.cs </p>
<p>Freddy: I was thinking of instantiating the classes within the generated code, write a test against the creation of the object, and continue from there.</p>
| <p>The code is generated by a framework and as such does not require testing. I would propose to exclude this code from code coverage (if you use that).</p>
|
How to link multiple visual studio solutions together? <p>I have 3 solutions and solution A requires built versions of the dlls from solution B and C in order to compile. it is not possible to merge it to one solution...</p>
<p>So far it seems that Visual Studio doesnt support solution references and msbuild is clever enough to know that you are building one solution from another etc if I try that way. The overall goal is to try to make the multiple solutions seem almost like there is only one - just solution A.</p>
<p>I believe this is a common problem, but how do you link it up nicely? </p>
| <p>This question has popped up in <a href="http://stackoverflow.com/questions/200954/">different</a>, but <a href="http://stackoverflow.com/questions/284856/">related</a>, forms. There is actually an <a href="http://msdn.microsoft.com/en-us/library/ee817674.aspx">MSDN page that covers this</a>.</p>
<p>What you're looking for is a multi-solution approach akin to the <strong>Partitioned Single Solution Model for Larger Systems</strong>. Have one "everything" solution that builds everything and maintains your inter-component dependencies. This is what you build when you need to build solution A. You then have separate solutions that only include components B or C. Essentially, you'll still have 3 solutions, but you'll add the projects from solutions B and C into solution A.</p>
|
How can I change the view of an MS Access subform at runtime in VBA code? <p>This seems like it would be a simple affair, and I am sure I have done this before, but it has been a while since I have done any UI programming in Access. What I need to do is put a button on a form to toggle between datasheet and form view for a subform.</p>
<p>I have found a defaultview property, but nothing that looks like it would toggle the view of the form after it is already open.</p>
<p>Essentially I need the property I can fill in the following code..</p>
<pre><code>sfEmployeeBatchEntry.Form.??? = acFormDS
</code></pre>
| <p>I found it on my own. I was missing it because it used the silly and clunky RunCommand syntax instead of a simple property or method on the control or form classes.</p>
<p>It ain't pretty, but for posterity, here is the answer.</p>
<pre><code>'You have to set focus to the subform control or the change view call will'
'fail (UGH!)'
MyForm.mySubFormControl.SetFocus
'Change to datasheet view...'
DoCmd.RunCommand acCmdSubformDatasheet
'Change to Form View...'
DoCmd.RunCommand acCmdSubformFormView
</code></pre>
|
Does a typed dataset use reflection at runtime? <p>Does a typed dataset use reflection on runtime?</p>
| <p>No. It is just a code generated wrapper that completely compiled and does no reflection in runtime.</p>
|
OnLive: How does it work? <p><a href="http://www.onlive.com/" rel="nofollow">OnLive</a> is a cloud computing solution for gaming. It offers streaming of high-end games to any pc, regardless of its hardware. I wonder how it works: sending raw HD res image and audio data seems unlikely. Would relatively simple compression, like jpeg and mp3/ogg, do the trick?</p>
| <p>Have you read <a href="http://pc.ign.com/articles/965/965535p1.html" rel="nofollow">this</a> article? Excerpts thereof:</p>
<blockquote>
<p>It's essentially the gaming version of cloud computing - everything is computed, rendered and housed online. In its simplest description, your controller inputs are uploaded, a high-end server takes your inputs and plays the game, and then a video stream of the output is sent back to your computer. Think of it as something like Youtube or Hulu for games.</p>
<p>The service works with pretty much any Windows or Mac machine as a small browser plug-in. Optionally, you will also be able to purchase a small device, called the OnLive MicroConsole, that you can hook directly into your TV via HDMI, though if your computer supports video output to your TV, you can just do it that way instead. Of course, you can also just play on your computer's display if you don't want to pipe it out to your living room set. </p>
<p>[...]</p>
<p>OnLive has worked diligently to overcome lag issues. The first step in this was creating a video compression algorithm that was as quick as possible.</p>
</blockquote>
|
Returning JSON from PHP to JavaScript? <p>I have a PHP script that's being called through jQuery AJAX. I want the PHP script to return the data in JSON format to the javascript. Here's the pseudo code in the PHP script:</p>
<pre><code>$json = "{";
foreach($result as $addr)
{
foreach($addr as $line)
{
$json .= $line . "\n";
}
$json .= "\n\n";
}
$json .= "}";
</code></pre>
<p>Basically, I need the results of the two for loops to be inserted in $json.</p>
| <p>Php has an inbuilt JSON Serialising function.</p>
<pre><code>json_encode
</code></pre>
<p><a href="http://nz.php.net/json%5Fencode">json_encode</a></p>
<p><strong>Please</strong> use that if you can and don't suffer Not Invented Here syndrome.</p>
|
Java inheritance - added methods <p>I want to have a base class, <code>BaseConnect</code>, which contains an <code>OutputStream</code> and children classes <code>ObjectStreamConnect</code> and <code>DataStreamConnect</code>. In my <code>BaseConnect</code> class I have <code>OutputStream os;</code> And in my Two children classes I have the constructors that do "<code>os = ObjectOutputStream(...)</code>" or "<code>os = DataOutputStream(...)</code>", respectively. </p>
<p>Since <code>ObjectOutputStream</code>s have a <code>writeObject(Object o)</code> method and <code>DataOutputStreams</code> do not, it seems that I cannot have my <code>ObjectStreamConnect</code> class do a "<code>os.writeObject(object)</code>" since the parent class, <code>OutputStream</code>, does not have <code>writeObject(Object o)</code>. </p>
<p>I'm sure this is code-smelly, and I'm wondering how to handle it.</p>
<p>My thoughts:</p>
<p>I thought of making the method that contains <code>os.writeObject</code> abstract, so that <code>ObjectStreamConnect</code> could implement it differently, but then I realized that <code>DataStreamConnect</code> would also have to implement it, which it does not need to. </p>
<p>I also do not want to just get rid of the parent and have the two classes implement everything separately, because they do have a lot of the same methods with the same implementations.</p>
<p>Please help. For some reason, the answer to this problem is not coming to me.</p>
<p>jbu</p>
<p>edit: I can't paste entire code but it goes something like this:</p>
<pre><code>public class BaseConnect {
OutputStream os;
...
}
public class ObjectStreamConnect extends BaseConnect {
public ObjectStreamConnect () {
...
os = new ObjectOutputStream(socket.getOutputStream);
}
public void writeObject(Object o) {
os.writeObject(o);
}
}
public class DataStreamConnect extends BaseConnect {
public DataStreamConnect () {
...
os = new DataOutputStream(socket.getOutputStream);
}
}
</code></pre>
| <p>What you seem to be saying is "my two objects use some shared methods, and I'm sharing them through inheritance of a superclass".</p>
<p>Then you get stuck because inheritance actually says "this <em>is</em> one of these, and so has this API" when it isn't - as your difficult-to-implement method suggests.</p>
<p>If you put the shared methods in some sort of helper class, and supply both <code>DataStreamConnect</code> and <code>OutputStreamConnect</code> with an instance of the helper, you can share the support code without having to share the same API.</p>
|
Getting Local Windows User login session timestamp in C# <p>I've been trying to look around the various .NET class library's for some where I can get the logged in user of the local machine, either connected to a domain or not.
So far </p>
<pre><code>System.Security.Principal.WindowsPrincipal LoggedUser = System.Threading.Thread.CurrentPrincipal as
System.Security.Principal.WindowsPrincipal;
// This returns the username
LoggedUser.Identity.Name
</code></pre>
<p>This will return the user's name, however is there any way of getting the session details, something that you would see in AD or user logged in, session duration, etc.. the context of the user, actions such as Workstation locked, the presence of the user basiclly. </p>
<p>If you have any idea, it would be much appreciated.
Thanks in advance.</p>
| <p>You can query Active Directory for much of the data that you need through LDAP queries using the <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.aspx" rel="nofollow">System.DirectoryServices</a> namespace. For example, the sample below shows the user's last logon time.</p>
<p>Of course, this only works for domain users.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
namespace ADMadness
{
class Program
{
static void Main(string[] args)
{
DirectorySearcher search = new DirectorySearcher("LDAP://DC=my,DC=domain,DC=com");
search.Filter = "(SAMAccountName=MyAccount)";
search.PropertiesToLoad.Add("lastLogonTimeStamp");
SearchResult searchResult = search.FindOne();
long lastLogonTimeStamp = long.Parse(searchResult.Properties["lastLogonTimeStamp"][0].ToString());
DateTime lastLogon = DateTime.FromFileTime(lastLogonTimeStamp);
Console.WriteLine("The user last logged on at {0}.", lastLogon);
Console.ReadLine();
}
}
}
</code></pre>
|
SQL create a temporary 'mapping' table in a select statement <p>I'm building up results by joining tables</p>
<pre><code>select t1.*, t2.col2 from t1, t2 where t1.col1=t2.col1
</code></pre>
<p>Is there a way to create a temporary 'mapping' table 'inline' in a select statement for instances where the t2 table doesn't exist?</p>
<p>So something like </p>
<pre><code>select t1.*, tempt2.col2 from t1, (<create temp table>) tempt2 where ...
</code></pre>
<p>I'm using Oracle</p>
| <p>Table with <code>1</code> row:</p>
<pre><code>SELECT t1.*, t2.col2
FROM t1,
(
SELECT 1 AS col2
FROM dual
) t2
</code></pre>
<p>Table with <code>0</code> rows:</p>
<pre><code>SELECT t1.*, t2.col2
FROM t1,
(
SELECT 1 AS col2
FROM dual
WHERE 1 = 0
) t2
</code></pre>
<p>Table with <code>N</code> rows:</p>
<pre><code>SELECT t1.*, t2.col2
FROM t1,
(
SELECT 1 AS col2
FROM dual
CONNECT BY
level <= :N
) t2
</code></pre>
|
Adding OCX Control to a Resource Dialog (how Do I control it) <pre><code>I'm adding an OCX to a resource dialog that I've created in my C++ project.
</code></pre>
<p>The ocx adds properly; but my question is how do I access the ocx programatically?<br />
I don't see a member variable (or even a class) attached to it. </p>
<p>This is my .rc contents</p>
<p>/////////////////////////////////////////////////////////////////////////////
//
// Dialog Info
//</p>
<p>IDD_LENELDECODER DLGINIT
BEGIN
IDC_MATRIXCONTROL1, 0x376, 26, 0
0x0000, 0x0000, 0x0900, 0x0000, 0x4c7b, 0x0000, 0x3643, 0x0000, 0x0013,
0x0065, 0x0000, 0x000b, 0xffff,
0
END</p>
<p>Where IDC_MATRIXCONTROL1 is the ID associated with the ocx. My question is, how do I access this ocx's member variables from a class; and how do I make it resize when the dialog resizes?</p>
<p>I've tried both MFC ActiveX and ATL Project -> ATL Control (composite). I though that since the ATL composite control has a Go To Dialog attached to it that I would be able to access it, but I don't know how to do it.</p>
<p>Any help is greatly appreciated! Thank you,</p>
<p>Joey</p>
| <p>When using MFC:</p>
<ol>
<li>In resource editor Right click in the OCX control,</li>
<li>Select "Add Variable...",</li>
<li>Put a name like m_object, then press finish to terminate.</li>
</ol>
<p>Now you can access your OCX control with m_object.</p>
<p>If you want to resize your object you have to trap WM_WINDOWSPOSCHANGING message.</p>
|
ASP.Net MVC have An Action render another Action <p>I have two pages I need, and want to show for the url /index and /review. The only difference between the two pages is on the review I will have a review comment section to show and Submit button. Otherwise the two pages are identical. I thought I could create a user control for the main content.</p>
<p>However, if I could say under the Review action, flag to show review stuff and them return the rest of the index action.</p>
<p>How would you (generic you) do this?</p>
| <p><strong>Model example</strong></p>
<pre><code>public class MyModel
{
public bool ShowCommentsSection { get; set; }
}
</code></pre>
<p><strong>Controller actions</strong></p>
<pre><code>public ActionResult Index()
{
var myModel = new MyModel();
//Note: ShowCommentsSection (and the bool type) is false by default.
return View(myModel);
}
public ActionResult Review()
{
var myModel = new MyModel
{
ShowCommentsSection = true
};
//Note that we are telling the view engine to return the Index view
return View("Index", myModel);
}
</code></pre>
<p><strong>View (somewhere inside your index.aspx probably)</strong></p>
<pre><code><% if(Model.ShowCommentsSection) { %>
<% Html.RenderPartial("Reviews/ReviewPartial", Model); %>
<% } %>
</code></pre>
<p>Or, if Razor is your cup of tea:</p>
<pre><code>@if(Model.ShowCommentsSection) {
Html.RenderPartial("Reviews/ReviewPartial", Model);
}
</code></pre>
|
java.net.SocketException: Broken pipe <p>I am getting this for all the database connections from my app server..<br />
This exception occured for couple of hours, then got fixed by itself.<br />
Something to do with network connection from the appserver?</p>
<pre>
java.net.SocketException: Broken pipe
com.inet.tds.SQLException: java.net.SocketException: Broken pipe
java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at com.inet.tds.a.a(Unknown Source)
at com.inet.tds.a.a(Unknown Source)
at com.inet.tds.a.commit(Unknown Source)
at com.inet.pool.a.commit(Unknown Source)</pre>
| <p>For MySQL, "By default, the server closes the connection after eight hours if nothing has happened." And, MySQL has a reconnect feature that supports auto-reconnect after the closed connection is detected on the client side.</p>
<p>Eight hours? With the use of connection pooling or a long-running background job, that is possible.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/gone-away.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.0/en/gone-away.html</a></p>
|
Does F# provide you automatic parallelism? <p>By this I meant: when you design your app side effects free, etc, will F# code be automatically distributed across all cores?</p>
| <p>No, I'm afraid not. Given that F# isn't a <em>pure</em> functional language (in the strictest sense), it would be rather difficult to do so I believe. The primary way to make good use of parallelism in F# is to use <strong>Async Workflows</strong> (mainly via the Async module I believe). The TPL (Task Parallel Library), which is being introduced with .NET 4.0, is going to fulfil a similar role in F# (though notably it can be used in all .NET languages equally well), though I can't say I'm sure exactly how it's going to integrate with the existing async framework. Perhaps Microsoft will simply advise the use of the TPL for everything, or maybe they will leave both as an option and one will eventually become the de facto standard...</p>
<p>Anyway, here are a few articles on asynchronous programming/workflows in F# to get you started.</p>
<ul>
<li><a href="http://blogs.msdn.com/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx">http://blogs.msdn.com/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx</a></li>
<li><a href="http://strangelights.com/blog/archive/2007/09/29/1597.aspx">http://strangelights.com/blog/archive/2007/09/29/1597.aspx</a></li>
<li><a href="http://www.infoq.com/articles/pickering-fsharp-async">http://www.infoq.com/articles/pickering-fsharp-async</a></li>
</ul>
|
Returning a host object in Rhino <p>What is the best way to return an host object to JavaScript in Rhino? I have two classes like this:</p>
<pre><code>public class Hosted extends org.mozilla.javascript.ScriptableObject {
private static final long serialVersionUID = 1;
public Hosted() {}
public void jsConstructor() {}
public String getClassName() {
return "Hosted";
}
public Member jsGet_member() {
Member m = new Member();
m.defineFunctionProperties(new String[] { "toString" }, m.getClass(), DONTENUM);
return m;
}
}
public class Member extends org.mozilla.javascript.ScriptableObject {
private static final long serialVersionUID = 2;
public Member() {}
public void jsConstructor() {}
public String getClassName() {
return "Member";
}
public String toString() {
return "called toString()";
}
}
</code></pre>
<p>It works, in the sense that I can call the toString method, but the member object doesn't behave as I would expect:</p>
<pre><code>js> defineClass("Hosted");
js> defineClass("Member");
js> var h = new Hosted();
js> h.toString();
[object Hosted]
js> h instanceof Hosted;
true
js> h.__proto__;
[object Hosted]
js>
js> var m = h.member;
js> m.toString();
called toString()
js> m instanceof Member; // Should be true
false
js> m.__proto__; // Should be [object Member]
null
</code></pre>
<p>If I call <code>Object.prototype.toString</code> though, it does say it's a Member object:</p>
<pre><code>js> Object.prototype.toString.call(m);
[object Member]
</code></pre>
<p>I've tried calling <code>m.setPrototype</code> and <code>Context.javaToJS</code>.</p>
| <pre><code> public Scriptable jsGet_member() {
Scriptable scope = ScriptableObject.getTopLevelScope(this);
Member m = new Member();
m.setParentScope(scope);
// defineClass("Member") must have previously been called.
m.setPrototype(ScriptableObject.getClassPrototype(scope, "Member"));
m.defineFunctionProperties(new String[] { "toString" },
m.getClass(), DONTENUM);
return m;
}
</code></pre>
<p><hr /></p>
<pre><code>js> defineClass("Member")
js> defineClass("Hosted")
js> var h = new Hosted();
js> var m = h.member;
js> m.toString();
called toString()
js> m instanceof Member;
true
js> m.__proto__;
[object Member]
</code></pre>
<p><hr /></p>
<p><strong>Edit</strong>: The method can also be written:</p>
<pre><code> public Scriptable jsGet_member() {
Scriptable scope = ScriptableObject.getTopLevelScope(this);
Context cx = Context.getCurrentContext();
Member m = (Member)cx.newObject(scope, "Member");
m.defineFunctionProperties(new String[] { "toString" },
m.getClass(), DONTENUM);
return m;
}
</code></pre>
<p>which will call Member.jsConstructor; there may be other differences as well.</p>
|
Rotation and Scaling -- How to do both and get the right result? <p>I've got a set of Java2D calls that draw vectors on a graphics context. I'd like for the image to be doubled in size and then rotated 90 degrees.</p>
<p>I'm using the following code to do this:</p>
<pre><code>Graphics2D g2 = // ... get graphics 2d somehow ...
AffineTransform oldTransform = g2.getTransform();
AffineTransform newTransform = (AffineTransform)oldTransform.clone();
newTransform.concatenate(AffineTransform.getTranslateInstance(x1, x2));
newTransform.concatenate(AffineTransform.getScaleInstance((double)newW/(double)iconW, (double)newH/(double)iconH));
newTransform.concatenate(AffineTransform.getRotateInstance(Math.toRadians(rotationAngle), (double)iconW/2.0d, (double)iconH/2.0d));
// ... do my drawing ...
</code></pre>
<p>This rotates and scales, however, the scale isn't applied the way I would like. It is as if it is rotated before scaling, thus making the image wider on the wrong axis.</p>
<p>Is there a better way to do this?</p>
| <p>I believe those transforms are implemented like a stack - so the last transform is performed first. Try reversing the order of the rotate and scale transformations and you should get what you are looking for.</p>
<pre><code>newTransform.concatenate(AffineTransform.getTranslateInstance(x1, x2));
newTransform.concatenate(AffineTransform.getRotateInstance(Math.toRadians(rotationAngle), (double)iconW/2.0d, (double)iconH/2.0d));
newTransform.concatenate(AffineTransform.getScaleInstance((double)newW/(double)iconW, (double)newH/(double)iconH));
</code></pre>
|
Unix - substitution <p>i have problem with substitution. I have a file with 1 line of random characters with brackets "{}" around 1 character. I want to move with these brackets on the previous character or on the next one. (I know how to do it if the line of character is still, non-changing.) But I wonder how to do it when I don't know these chars and I don't know where these brackets are.</p>
<p>For Example: " ABC123{X}CBA321 " ==> " ABC12{3}XCBA321 " or " ABC123X{C}BA321 "</p>
<p>I would like to use awk or sed, some regex, maybe...</p>
| <p>Move backward one character:</p>
<pre><code>sed -e 's/\(.\){\(.\)}/{\1}\2/g' file
</code></pre>
<p>Move forward one character:</p>
<pre><code>sed -e 's/{\(.\)}\(.\)/\1{\2}/g' file
</code></pre>
<p>To modify the file in-place, use the <code>-i</code> flag:</p>
<pre><code>sed -i -e 's/\(.\){\(.\)}/{\1}\2/g' file
sed -i -e 's/{\(.\)}\(.\)/\1{\2}/g' file
</code></pre>
<p>The first example works by matching any character followed by a character surrounded by <code>{}</code>. Without grouping, this is: <code>.{.}</code> We add grouping so we can put the two characters in the output. Instead of surrounding the second character with <code>{}</code> with surround the first character. This is <code>{\1}\2</code>.</p>
<p>The second example works similarly, but matches <code>{.}.</code> first then outputs <code>\1{\2}</code>.</p>
|
ASP.NET MVC on Mono <p>what steps should I perform in order to run asp.net mvc 1.0 web application on mono?</p>
| <p>It requires the same steps as for 3.0.<br />
minus</p>
<pre><code>System.Web.Razor.dll
System.Web.WebPages.Razor.dll
</code></pre>
<p>But why do you even want to run a 1.0 application, when 4.0 works already ?</p>
<p>Here: <br />
<a href="http://stackoverflow.com/questions/4239645/does-the-razor-view-engine-work-for-mono/6317712#6317712">Does the Razor View Engine work for Mono?</a></p>
|
Why does my Perl script complain about 'Global symbol "$connection" requires explicit package name'? <pre><code>my $now = &GetDate;
my $myHeader = &ReadMessage;
my $mySoftwareVersions = param('mySoftwareVersions');
my $q = new CGI;print $q->header();
use CGI::Carp(fatalsToBrowser);
getAllSoftwareVersions();
sub getAllSoftwareVersions
{
my $user = "zxxx";
my $passwd = "xxxx";
# my $tableName = "config_table";
# my $connection = DBI->connect("DBI:mysql:MESCI:hamysql02.stl.mo.boeing.com:18080", $user, $passwd, { AutoCommit => 0, RaiseError => 1}) or die "Couldn't connect to Database: " . DBI->errstr;
print "Must be connected\n\n";
print "\n\n";
# Error here.
my @Rows = &getConfigTableRows($connection, $config_table, $mySoftwareVersions );
my $total = @Rows;
print "total is ";
print $total;
</code></pre>
<p>The Above code dies with:</p>
<pre>Global symbol "$connection" requires explicit package name</pre>
<p><strong>Edit</strong>
This question is related to :</p>
<ul>
<li><a href="http://stackoverflow.com/questions/682695/how-do-i-resolve">http://stackoverflow.com/questions/682695/how-do-i-resolve</a> </li>
<li><a href="http://stackoverflow.com/questions/681557/xml-cannot-be-displayed-error-from-perl-cgi-script-using-mysql">http://stackoverflow.com/questions/681557/xml-cannot-be-displayed-error-from-perl-cgi-script-using-mysql</a></li>
</ul>
<p>Hopefully the original poster will be able to clean this up so it makes more sense, but here's what we've got so far so we can attempt to help.</p>
| <p>Although Kent's answer is thinking ahead, the error is simply telling you that you did not <em>declare</em> <code>$connection</code> as a lexical ( "my" ) variable. So therefore, perl interprets it as that you must be referring to a package global. </p>
<p>Raw Perl does not complain when you use an undefined variable, it considers it a package global. You appear to have <a href="http://search.cpan.org/perldoc?strict" rel="nofollow"><code>strict</code></a> on somewhere (a standard and recommended practice), which wants you to declare your variables before using them. If you didn't declare the variable in the current package (or "namespace"), it assumes you're referring to a variable declared in another package, so it asks you to append the package name, just to keep everything clear and aboveboard. </p>
<p>Perl uses <a href="http://search.cpan.org/perldoc?perlfunc.pod#my" rel="nofollow"><code>my</code></a> to declare scoped variables, and <a href="http://search.cpan.org/perldoc?perlfunc.pod#our" rel="nofollow"><code>our</code></a> to declare package globals. </p>
<pre><code>my $connection = "Rainbow";
</code></pre>
<p>OR</p>
<pre><code>our $connection = 'French';
</code></pre>
<p><hr/>
Just in case you got the wrong idea, the error message would go away if you turned strict off, your problem wouldn't. And they might go underground. </p>
<pre><code>{ no strict;
my @rows = getConfigTableRows( $nothing, @other_stuff );
}
</code></pre>
<p>Perl just won't <em>complain</em> that <code>$nothing</code> is nothing. And this easy-to-fix error could cause subtler errors in other places. Plus think if you had assigned <code>$connection</code> successfully, only to type:</p>
<pre><code>{ no strict;
my @rows = getConfigTableRows( $connecion, $config_table, $mySoftwareVersions );
}
</code></pre>
<p>Perl gives you a message about <code>'$connecion'</code> and hopefully, you can tell that it was a typo, and forgo at least 30 minutes not seeing it and wondering if your query is wrong, or whatever. </p>
|
DeleteOnSubmit LINQ exception "Cannot add an entity with a key that is already in use" <p>edit: in case anyone is wondering, the actionhandler invokes code that creates and disposes the same kind of datacontext, in case that might have anything to do with this behaviour. the code doesn't touch the MatchUpdateQueue table, but i figure i should mention it just in case.</p>
<p>double edit: everyone who answered was correct! i gave the answer to the respondent who suffered most of my questioning. fixing the problem allowed another problem (hidden within the handler) to pop up, which happened to throw exactly the same exception. whoops!</p>
<p>I'm having some issues with deleting items in LINQ. The DeleteOnSubmit call in the code below causes a LINQ Exception with the message "Cannot add an entity with a key that is already in use." I'm not sure what I'm doing wrong here, it is starting to drive me up the wall. The primary key is just an integer autoincrement column and I have no other problems until I try to remove an item from the database queue. Hopefully I'm doing something painfully retarded here that is easy to spot for anyone who isn't me!</p>
<pre><code>static void Pacman()
{
Queue<MatchUpdateQueue> waiting = new Queue<MatchUpdateQueue>();
events.WriteEntry("matchqueue worker thread started");
while (!stop)
{
if (waiting.Count == 0)
{
/* grab any new items available */
aDataContext db = new aDataContext();
List<MatchUpdateQueue> freshitems = db.MatchUpdateQueues.OrderBy(item => item.id).ToList();
foreach (MatchUpdateQueue item in freshitems)
waiting.Enqueue(item);
db.Dispose();
}
else
{
/* grab & dispatch waiting item */
MatchUpdateQueue item = waiting.Peek();
try
{
int result = ActionHandler.Handle(item);
if (result == -1)
events.WriteEntry("unknown command consumed : " + item.actiontype.ToString(), EventLogEntryType.Error);
/* remove item from queue */
waiting.Dequeue();
/* remove item from database */
aDataContext db = new aDataContext();
db.MatchUpdateQueues.DeleteOnSubmit(db.MatchUpdateQueues.Single(i => i == item));
db.SubmitChanges();
db.Dispose();
}
catch (Exception ex)
{
events.WriteEntry("exception while handling item : " + ex.Message, EventLogEntryType.Error);
stop = true;
}
}
/* to avoid hammering database when there's nothing to do */
if (waiting.Count == 0)
Thread.Sleep(TimeSpan.FromSeconds(10));
}
events.WriteEntry("matchqueue worker thread halted");
}
</code></pre>
| <p>You could do something to the effect of </p>
<pre><code>db.MatchUpdateQueues.DeleteOnSubmit(db.MatchUpdateQueues.Single(theItem => theItem == item));
</code></pre>
<p>Just a note as other answers hinted towards Attach.. you will not be able to use attach on a context other then the original context the item was received on unless the entity has been serialized.</p>
|
Persisting the state column on transition using rubyist-aasm (acts as state machine) <p>What is the best way to persist the object's state to the database on a transition using aasm? I had thought that this would happen automatically but this doesn't seem to be the case.</p>
<p>(Edit: when I manually save the object, the state column does get updated. But a save isn't done on transitions.)</p>
<p>I can't find much useful documentation for this plugin, so if you have a suggestion for an alternative finite state machine implementation with better documentation, that might help as well.</p>
| <p>If you call the <em>bang!</em> form of the transition event method, the state will persist. For example, say you have an object with the following event:</p>
<pre><code>class Book < ActiveRecord::Base
# ...
aasm_event :close do
transitions :to => :closed, :from => [:opened]
end
# ...
end
</code></pre>
<p>Calling <code>book.close</code> will set the state to <code>closed</code>, but will not automatically save. Calling <code>book.close!</code> will set the state *and* automatically save the AR object.</p>
|
Using acts_as_list and in_place_editing at the same time <p>I have a rails project where the the view displays a list of items. I use acts_as_list to make the list DnD orderable and in_place_editing on each item to, well, edit it.</p>
<p>My problem is that when I DnD the items around, the item I drag automagically becomes editable when I drop it. Any tips on how I can avoid that behavior. </p>
<p>Ideally, I'd like to make it editable by clicking a small icon next to the item, but I don't know how to make that work with this plugin.</p>
<p>Thanks in advance.</p>
| <p>This happens because the element you are dragging has a listener on mouseup that begins the edit. You can specify an :external_control in the options hash if you want a different element to trigger the edit.</p>
<pre><code><div id="<%= dom_id(@obj) -%>">
<span><%= @obj.to_s -%></span>
<img id="<%= dom_id(@obj, :edit) -%>" src="edit_handle.png"/>
</div>
<%= in_place_editor(dom_id(@obj), :external_control => dom_id(@obj, :edit)) %>
<%= draggable_element(dom_id(@obj)) %>
</code></pre>
|
Why does CreateDIBSection() fail when the window is offscreen? <p>I'm building a Delphi component to embed an <a href="http://www.libsdl.org" rel="nofollow">SDL</a> rendering surface on a VCL form. It works just fine as long as the form is on-screen at the moment that the SDL surface is created. Otherwise, it's not able to create any rendering textures.</p>
<p>I traced into the SDL code and ended up with the following function call, which fails (returns NULL):</p>
<pre><code>data->hbm = CreateDIBSection(renderdata->memory_hdc, bmi, DIB_RGB_COLORS, &data->pixels, NULL, 0);
</code></pre>
<p>The HDC is a valid handle to the drawing context owned by a control that has its own HWND window handle, that's been set up properly. But when the control is created offscreen, which commonly happens in Delphi, (all forms, with their controls, are created in a hidden state until it's time to display them,) the CreateDIBSection call will fail until the control is actually visible.</p>
<p>Also, if it's created onscreen, then hidden and re-shown (if it's on a tab sheet and I switch tabs, for example,) any textures I create get blanked during this process.</p>
<p>This is driving me nuts. Anyone know what's going on and how I can work around it?</p>
| <p>Just an idea.... Have you watched the window Handle? Isn't it butchered and recreated?</p>
|
Load old XML data into new version of InfoPath form <p>We have an ASP.NET application with an InfoPath forms component, delivering InfoPath forms to the browser using InfoPath Forms Server. Rather than save the forms in SharePoint, we submit the XML form data to a ASP.NET web service, which saves the data as an XML data type in SQL Server 2005. This is working fine, and we have no issues loading the XML data back into the InfoPath form.</p>
<p>Our issue comes when we try to load old data ( from Version 1 of the form) into a new version of the form (Version 2). This new version of the form (V2) has a new textbox field, for example. Because the V2 field does not exist in the V1 XML, they are visible on the V2 form, but are disabled and cannot be filled.</p>
<p>Our question is how do we load V1 XML data into V2 forms, and have the user be able to complete those fields which are now present in V2 of the form. </p>
<p>This behaviour is possible using InfoPath Forms Server and forms stored in a Form Library. if you update the Form Template, you can open old forms in the new template, see the new fields, and can save data in the new fields. We need to know how to do it programmatically when the Form XML data is stored in SQL Server, rather than a Form Library.</p>
| <p>It's been a while since I did anything InfoPath, so apologies for this being a little vague:</p>
<p>Part of the InfoPath template, which is pretty much just a ZIP archive with a different extension, is a file called "upgrade.xsl". This file contains one or more XSL transformations that "upgrade" documents targeting earlier schema versions.</p>
<p>The question is: Why does the correct transformation get applied in one scenario (SharePoint/Form Library) and not in the other (web service)? Is the second process possibly losing the tag that InfoPath uses to know the version of the schema that the source document is targeting? I believe the tag I'm referring to is the "?mso-infoPathSolution" tag ("solutionVersion" attribute).</p>
<p>If this tag is indeed being stripped from the document (and you can't easily prevent it), you may need to apply the appropriate XSL transformation "manually". Of course, if there are multiple versions you are dealing with, it could be difficult to determine what transformation needs to be applied in any case.</p>
|
SQL language differences between MSSQL 2000 and 2005 <p>My company has an application developed for SQL Server 2005 (among others), and a potential client is attempting to install it on SQL Server 2000. Naturally, installation failed. Specifically, it failed with syntax errors in our CREATE TABLE statements.</p>
<p>Is there a summary of the language differences between these two databases?</p>
| <p>You can take a look at the list of breaking changes <a href="http://technet.microsoft.com/en-us/library/ms143532%28SQL.90%29.aspx" rel="nofollow">here</a> at technet.</p>
|
How do I make a field global to my site? <p>Okay, this is a bit abstract, but here goes:</p>
<p>I'm creating a website and I want to have a field, "foo", that I can access from any page on the site. I figured the best way to do this would be to create a subclass of Page called "bar", add the protected field "foo" to it, and then have all my webpages inheret from "bar". Ta-da. Every page now has foo.</p>
<p>But now I add controls to my pages, and I want them to have access to "foo".</p>
<p>Well, now foo can't be protected, so it's public. Fine. But how do the controls know about "foo"? I can access foo by doing something like this in my control:</p>
<pre><code>Foo foo = ((Bar)Page).foo;
</code></pre>
<p>This works, but strikes me as a bit ugly. I'd really like to just be able to use foo. I figure, hey, maybe I can do the same trick with my controls that I did for page. I create a new class, "blargh" that inherits from UserControl, and grab foo in there the ugly way. Then I have my controls inherit from blargh. Yay!</p>
<p>Except it doesn't work. When I start up the project it complains about the line trying to access ((Bar)Page).foo, because Page is null. Why? How could Page be null? When I look at the call stack I get no help.</p>
<p>Is there an easy, well understood way to do this? Am I barking up the wrong tree?</p>
| <p>If you need every user to have their own instance you can store it in the session. </p>
<pre><code> Session["foo"]=data;
</code></pre>
<p>Then on your other pages you can use:</p>
<pre><code> Control ctl = (Control) Session["foo"];
</code></pre>
<p>Keep in mind you will have to cast Session["foo"] to whatever type you want to work with. there is also a similar Application[] space which can be used if you only need one instance for every user of the website.</p>
|
Is this extern harmless? <p>main.h</p>
<pre><code>extern int array[100];
</code></pre>
<p>main.c</p>
<pre><code>#include "main.h"
int array[100] = {0};
int main(void)
{
/* do_stuff_with_array */
}
</code></pre>
<p>In the main.c module, the array is defined, and declared. Does the act of also having the extern statement included in the module, cause any problems?</p>
<p>I have always visualized the extern statement as a command to the linker to "look elsewhere for the actual named entity. It's not in here.</p>
<p>What am I missing?</p>
<p>Thanks.</p>
<p>Evil.</p>
| <p>The correct interpretation of <code>extern</code> is that you tell something to the <strong>compiler</strong>. You tell the compiler that, despite not being present right now, the variable declared will somehow be found by the linker (typically in another object (file)). The linker will then be the lucky guy to find everything and put it together, whether you had some extern declarations or not.</p>
<p>To avoid exposure of names (variables, functions, ..) outside of a specific object (file), you would have to use <code>static</code>.</p>
|
Getting the "diff" between two arrays in C#? <p>Let's say I have these two arrays:</p>
<pre><code>var array1 = new[] {"A", "B", "C"};
var array2 = new[] {"A", "C", "D"};
</code></pre>
<p>I would like to get the differences between the two. I know I could write this in just a few lines of code, but I want to make sure I'm not missing a built in language feature or a LINQ extension method.</p>
<p>Ideally, I would end up with the following three results:</p>
<ul>
<li>Items not in array1, but are in array2 ("D")</li>
<li>Items not in array2, but are in array1 ("B")</li>
<li>Items that are in both</li>
</ul>
<p>Thanks in advance!</p>
| <p>If you've got LINQ available to you, you can use <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except.aspx"><code>Except</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx"><code>Distinct</code></a>. The sets you asked for in the question are respectively:</p>
<pre><code>- array2.Except(array1)
- array1.Except(array2)
- array1.Intersect(array2)
</code></pre>
|
How to make a window always stay on top in .Net? <p>I have a C# winforms app that runs a macro in another program. The other program will continually pop up windows and generally make things look, for lack of a better word, crazy. I want to implement a cancel button that will stop the process from running, but I cannot seem to get the window to stay on top. How do I do this in C#? </p>
<p>Edit: I have tried TopMost=true; , but the other program keeps popping up its own windows over top. Is there a way to send my window to the top every n milliseconds?</p>
<p>Edit: The way I solved this was by adding a system tray icon that will cancel the process by double-clicking on it. The system tray icon does no get covered up. Thank you to all who responded. I read the article on why there is not a 'super-on-top' window... it logically does not work.</p>
| <p><code>Form.TopMost</code> will work unless the other program is creating topmost windows. </p>
<p>There is no way to create a window that is not covered by new topmost windows of another process. Raymond Chen <a href="http://blogs.msdn.com/oldnewthing/archive/2005/06/07/426294.aspx">explained</a> why. </p>
|
Assigning values to Instance variables in Objective C <p>The function I'm looking at:</p>
<pre><code>-(void)viewDidLoad {
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"statedictionary" ofType:@"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.statesZips = dictionary;
[dictionary release];
NSArray *components = [self.stateZips allKeys];
NSArray *sorted = [components sortedArrayUsingSelector:@selector(compare:)];
self.States = sorted;
NSString *selectedState = [self.states objectAtIndex:0];
NSArray *array = [stateZips objectForKey: selectedState];
self.zips = array;
}
</code></pre>
<p>Why is an NSDictionary allocated, then assigned to a pointer called *dictionary, and then assigned to the instance variable stateZips? Why not allocate it and assign it directly to the instance variable and save memory of creating and releasing another NSDictionary? The same methodology is always followed, including later in this function with the NSArray...</p>
<pre><code>NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.statesZips = dictionary;
[dictionary release];
</code></pre>
<p>Also, this sorting puts the keys from a hash table (dictionary) in alphabetical order. I'm not sure I understand this line:</p>
<pre><code>NSArray *sorted = [components sortedArrayUsingSelector:@selector(compare:)];
</code></pre>
| <p>No one seems to have addressed the fact that the line</p>
<pre><code>self.statesZips = dictionary;
</code></pre>
<p>is not directly an instance variable assignment. <code>stateZips</code> is a property, and so that line of code calls the <code>setStateZips:</code> method. That method retains or copies the dictionary, so unless the <code>viewDidLoad</code> method intends to use it again for some purpose, it's not needed any longer. That makes it OK to <code>release</code> it.</p>
<p>The previous line:</p>
<pre><code>[[NSDictionary alloc] initWithContentsOfFile:plistPath];
</code></pre>
<p>allocates an object. That makes it your responsibility to <code>release</code> it once you don't need it any more. After assigning it to the <code>statesZips</code> property, it's no longer needed, so it's released and you shouldn't use <code>dictionary</code> any more. You'll notice that later code only refers to <code>self.stateZips</code>, not <code>dictionary</code>.</p>
<p>In the case of the <code>NSArray</code> later in the method, <code>viewDidLoad</code> does not allocate the object, so that method is not responsible for calling <code>release</code> on it. The rule of thumb is that if you <code>alloc</code> it, you're responsible for making sure it gets released. Otherwise, it's not your problem.</p>
<p>Sorting the array uses the <code>sortedArrayUsingSelector:</code> method. A selector identifies a method in Objective-C. And the <code>@selector</code> is the literal syntax for selectors (kind of like how <code>@""</code> is the literal syntax for <code>NSString</code> objects). So, what that code says, is "give me an array where the objects in <code>components</code> are sorted, and use the <code>compare:</code> method to compare each object when you do the sort. When it sorts the array, it will call <code>compare:</code> on the objects in the array to determine how to put them in order.</p>
|
DRY LINQ statements for tables with common columns <p>Here's an interesting problem. Is there a way to write some code using LINQ to SQL which is capable of performing a table UPDATE knowing only that the table it is given contains columns x, y, z but not knowing at compile time which table it is dealing with?</p>
<p>I have several tables in my DB schema which share some columns and I need to apply a set based UPDATE operation which is identical in its logical procedure regardless of which one of the tables we're dealing with. </p>
<p>Here's a simple example: say you have 3 tables which implement an adjacency model hierarchy (ie each row contains a primary key ID and a self-referencing parent ID column). Each of the tables also has a 'Disabled' boolean flag. When I disable an instance of any of these entities, it should cascade through the child items, i.e.</p>
<p>UPDATE MyTable
SET Disabled = 1
WHERE ID = @ID or Parent_ID = @ID</p>
<p>I don't want to be writing these kind of LINQ statements for each entity, it violates DRY. It might seem trivial with this example, but as the example gets more complex you're duplicating increasing amounts of code. I'm sure it must be possible using an interface and perhaps generics, but I'm struggling to come up with an elegant solution.</p>
| <p>Simply create a base class for your entities and move the common properties to it as virtual properties. Override these properties in your entities and specify Column attributes on them. Here's a detailed <a href="http://blogs.msdn.com/dinesh.kulkarni/archive/2007/11/09/linq-to-sql-how-to-2-base-class-for-all-entities.aspx" rel="nofollow">example</a>.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.