qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
78,847 | <p>ASP.NET 1.1 - I have a DataGrid on an ASPX page that is databound and displays a value within a textbox. The user is able to change this value, then click on a button where the code behind basically iterates through each DataGridItem in the grid, does a FindControl for the ID of the textbox then assigns the .Text value to a variable which is then used to update the database. The DataGrid is rebound with the new values.</p>
<p>The issue I'm having is that when assigning the .Text value to the variable, the value being retrieved is the original databound value and not the newly entered user value. Any ideas as to what may be causing this behaviour?</p>
<p>Code sample:</p>
<pre><code>foreach(DataGridItem dgi in exGrid.Items)
{
TextBox Text1 = (TextBox)dgi.FindControl("TextID");
string exValue = Text1.Text; //This is retrieving the original bound value not the newly entered value
// do stuff with the new value
}
</code></pre>
| [
{
"answer_id": 79791,
"author": "Nathan Feger",
"author_id": 8563,
"author_profile": "https://Stackoverflow.com/users/8563",
"pm_score": 1,
"selected": false,
"text": "<p>Are you able to manage permissions on this database? Would adding a separate user who only has read access to a data... | 2008/09/17 | [
"https://Stackoverflow.com/questions/78847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/710/"
] | ASP.NET 1.1 - I have a DataGrid on an ASPX page that is databound and displays a value within a textbox. The user is able to change this value, then click on a button where the code behind basically iterates through each DataGridItem in the grid, does a FindControl for the ID of the textbox then assigns the .Text value to a variable which is then used to update the database. The DataGrid is rebound with the new values.
The issue I'm having is that when assigning the .Text value to the variable, the value being retrieved is the original databound value and not the newly entered user value. Any ideas as to what may be causing this behaviour?
Code sample:
```
foreach(DataGridItem dgi in exGrid.Items)
{
TextBox Text1 = (TextBox)dgi.FindControl("TextID");
string exValue = Text1.Text; //This is retrieving the original bound value not the newly entered value
// do stuff with the new value
}
``` | Are you able to manage permissions on this database? Would adding a separate user who only has read access to a database be sufficient for this type of scenario? This could be a read-only user on the main database, but is only effectively used on the snapshot db.
i.e. Add a new user, readerMan5000 who is only given select access, to the database in question. Then require users to authenticate through that new credential.
Note to future commenters, you may want to read:
<http://www.simple-talk.com/sql/database-administration/sql-server-2005-snapshots/>
or
<http://msdn.microsoft.com/en-us/library/ms187054(SQL.90).aspx>
before you open your big mouth like me. :) |
78,849 | <p>I have an image (mx) and i want to get the uint of the pixel that was clicked.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 79221,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 3,
"selected": false,
"text": "<p>A few minutes on the <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/BitmapData.html\"... | 2008/09/17 | [
"https://Stackoverflow.com/questions/78849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748529/"
] | I have an image (mx) and i want to get the uint of the pixel that was clicked.
Any ideas? | Here's an even simpler implementation. All you do is take a snapshot of the stage using the **draw()** method of bitmapData, then use **getPixel()** on the pixel under the mouse. The advantage of this is that you can sample anything that's been drawn to the stage, not just a given bitmap.
```
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.*;
stage.addEventListener(MouseEvent.CLICK, getColorSample);
function getColorSample(e:MouseEvent):void {
var bd:BitmapData = new BitmapData(stage.width, stage.height);
bd.draw(stage);
var b:Bitmap = new Bitmap(bd);
trace(b.bitmapData.getPixel(stage.mouseX,stage.mouseX));
}
```
Hope this is helpful!
---
**Edit**:
This edited version uses a single `BitmapData`, and removes the unnecessary step of creating a `Bitmap`. If you're sampling the color on `MOUSE_MOVE` then this is essential to avoid memory issues.
Note: if you're using a custom cursor sprite you'll have to use an object other than 'state' or else you'll be sampling the color of the custom sprite instead of what's under it.
```
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.*;
private var _stageBitmap:BitmapData;
stage.addEventListener(MouseEvent.CLICK, getColorSample);
function getColorSample(e:MouseEvent):void
{
if (_stageBitmap == null) {
_stageBitmap = new BitmapData(stage.width, stage.height);
}
_stageBitmap.draw(stage);
var rgb:uint = _stageBitmap.getPixel(stage.mouseX,stage.mouseY);
var red:int = (rgb >> 16 & 0xff);
var green:int = (rgb >> 8 & 0xff);
var blue:int = (rgb & 0xff);
trace(red + "," + green + "," + blue);
}
``` |
78,852 | <p>Mapping a collection of enums with NHibernate</p>
<p>Specifically, using Attributes for the mappings.</p>
<p>Currently I have this working mapping the collection as type Int32 and NH seems to take care of it, but it's not exactly ideal.</p>
<p>The error I receive is "Unable to determine type" when trying to map the collection as of the type of the enum I am trying to map.</p>
<p>I found a post that said to define a class as</p>
<pre><code>public class CEnumType : EnumStringType {
public CEnumType() : base(MyEnum) { }
}
</code></pre>
<p>and then map the enum as CEnumType, but this gives "CEnumType is not mapped" or something similar.</p>
<p>So has anyone got experience doing this?</p>
<p>So anyway, just a simple reference code snippet to give an example with</p>
<pre><code> [NHibernate.Mapping.Attributes.Class(Table = "OurClass")]
public class CClass : CBaseObject
{
public enum EAction
{
do_action,
do_other_action
};
private IList<EAction> m_class_actions = new List<EAction>();
[NHibernate.Mapping.Attributes.Bag(0, Table = "ClassActions", Cascade="all", Fetch = CollectionFetchMode.Select, Lazy = false)]
[NHibernate.Mapping.Attributes.Key(1, Column = "Class_ID")]
[NHibernate.Mapping.Attributes.Element(2, Column = "EAction", Type = "Int32")]
public virtual IList<EAction> Actions
{
get { return m_class_actions; }
set { m_class_actions = value;}
}
}
</code></pre>
<p>So, anyone got the correct attributes for me to map this collection of enums as actual enums? It would be really nice if they were stored in the db as strings instead of ints too but it's not completely necessary.</p>
| [
{
"answer_id": 80485,
"author": "alvin",
"author_id": 15121,
"author_profile": "https://Stackoverflow.com/users/15121",
"pm_score": 1,
"selected": false,
"text": "<p>This is the way i do it. There's probably an easier way but this works for me.</p>\n\n<p>Edit: sorry, i overlooked that yo... | 2008/09/17 | [
"https://Stackoverflow.com/questions/78852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/924607/"
] | Mapping a collection of enums with NHibernate
Specifically, using Attributes for the mappings.
Currently I have this working mapping the collection as type Int32 and NH seems to take care of it, but it's not exactly ideal.
The error I receive is "Unable to determine type" when trying to map the collection as of the type of the enum I am trying to map.
I found a post that said to define a class as
```
public class CEnumType : EnumStringType {
public CEnumType() : base(MyEnum) { }
}
```
and then map the enum as CEnumType, but this gives "CEnumType is not mapped" or something similar.
So has anyone got experience doing this?
So anyway, just a simple reference code snippet to give an example with
```
[NHibernate.Mapping.Attributes.Class(Table = "OurClass")]
public class CClass : CBaseObject
{
public enum EAction
{
do_action,
do_other_action
};
private IList<EAction> m_class_actions = new List<EAction>();
[NHibernate.Mapping.Attributes.Bag(0, Table = "ClassActions", Cascade="all", Fetch = CollectionFetchMode.Select, Lazy = false)]
[NHibernate.Mapping.Attributes.Key(1, Column = "Class_ID")]
[NHibernate.Mapping.Attributes.Element(2, Column = "EAction", Type = "Int32")]
public virtual IList<EAction> Actions
{
get { return m_class_actions; }
set { m_class_actions = value;}
}
}
```
So, anyone got the correct attributes for me to map this collection of enums as actual enums? It would be really nice if they were stored in the db as strings instead of ints too but it's not completely necessary. | You will need to map your CEnum type directly. In XML mappings this would mean creating a new class mapping element in your NHibernate XML mappings file.
```
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="YourAssembly"
auto-import="true" default-lazy="false">
...
<class name="YourAssemblyNamespace.CEnum" table="CEnumTable" mutable="false" >
<id name="Id" unsaved-value="0" column="id">
<generator class="native"/>
</id>
...
</class>
</hibernate-mapping>
```
To do it with attribute mappings, something like this on top of your CEnum class:
`[NHibernate.Mapping.Attributes.Class(Table = "CEnumTable")] //etc as you require` |
78,884 | <p>I have an xslt sheet with some text similar to below:</p>
<pre><code><xsl:text>I am some text, and I want to be bold</xsl:text>
</code></pre>
<p>I would like some text to be bold, but this doesn't work.</p>
<pre><code><xsl:text>I am some text, and I want to be <strong>bold<strong></xsl:text>
</code></pre>
<p>The deprecated b tag doesn't work either. How do I format text within an xsl:text tag?</p>
| [
{
"answer_id": 78904,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>Try this: </p>\n\n<pre><code><fo:inline font-weight=\"bold\"><xsl:text>Bold text</xsl:text></fo:inline&g... | 2008/09/17 | [
"https://Stackoverflow.com/questions/78884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5989/"
] | I have an xslt sheet with some text similar to below:
```
<xsl:text>I am some text, and I want to be bold</xsl:text>
```
I would like some text to be bold, but this doesn't work.
```
<xsl:text>I am some text, and I want to be <strong>bold<strong></xsl:text>
```
The deprecated b tag doesn't work either. How do I format text within an xsl:text tag? | You don't. `xsl:text` can only contain text nodes and `<strong>` is an element node, not a string that starts with less-than character; XSLT is about creating node trees, not markup. So, you have to do
```
<xsl:text>I am some text, and I want to be </xsl:text>
<strong>bold<strong>
<xsl:text> </xsl:text>
``` |
78,913 | <p>What is the single most effective practice to prevent <a href="http://en.wikipedia.org/wiki/Arithmetic_overflow" rel="nofollow noreferrer">arithmetic overflow</a> and <a href="http://en.wikipedia.org/wiki/Arithmetic_underflow" rel="nofollow noreferrer">underflow</a>?</p>
<p>Some examples that come to mind are:</p>
<ul>
<li>testing based on valid input ranges</li>
<li>validation using formal methods</li>
<li>use of invariants</li>
<li>detection at runtime using language features or libraries (this does not prevent it)</li>
</ul>
| [
{
"answer_id": 78936,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 3,
"selected": true,
"text": "<p>One possibility is to use a language that has arbitrarily sized integers that never overflow / underflow.</p>\n\n<p>Otherwi... | 2008/09/17 | [
"https://Stackoverflow.com/questions/78913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3836/"
] | What is the single most effective practice to prevent [arithmetic overflow](http://en.wikipedia.org/wiki/Arithmetic_overflow) and [underflow](http://en.wikipedia.org/wiki/Arithmetic_underflow)?
Some examples that come to mind are:
* testing based on valid input ranges
* validation using formal methods
* use of invariants
* detection at runtime using language features or libraries (this does not prevent it) | One possibility is to use a language that has arbitrarily sized integers that never overflow / underflow.
Otherwise, if this is something you're really concerned about, and if your language allows it, write a wrapper class that acts like an integer, but checks every operation for overflow. You could even have it do the check on debug builds, and leave things optimized for release builds. In a language like C++, you could do this, and it would behave almost exactly like an integer for release builds, but for debug builds you'd get full run-time checking.
```
class CheckedInt
{
private:
int Value;
public:
// Constructor
CheckedInt(int src) : Value(src) {}
// Conversions back to int
operator int&() { return Value; }
operator const int &() const { return Value; }
// Operators
CheckedInt operator+(CheckedInt rhs) const
{
if (rhs.Value < 0 && rhs.Value + Value > Value)
throw OverflowException();
if (rhs.Value > 0 && rhs.Value + Value < Value)
throw OverflowException();
return CheckedInt(rhs.Value + Value);
}
// Lots more operators...
};
```
Edit:
Turns out someone is [doing this already for C++](http://www.codeplex.com/SafeInt) - the current implementation is focused for Visual Studio, but it looks like they're getting support for gcc as well. |
78,924 | <p>I have written a message handler function in Outlook's Visual Basic (we're using Outlook 2003 and Exchange Server) to help me sort out incoming email. </p>
<p>It is working for me, except sometimes the rule fails and Outlook deactivates it. </p>
<p>Then I turn the rule back on and manually run it on my Inbox to catch up. The rule spontaneously fails and deactivates several times a day. </p>
<p>I would love to fix this once and for all.</p>
| [
{
"answer_id": 79000,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>have written a message handler function in Outlook's Visual Basic (we're using Outlook 2003 and Exchange Server) to help me ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/78924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have written a message handler function in Outlook's Visual Basic (we're using Outlook 2003 and Exchange Server) to help me sort out incoming email.
It is working for me, except sometimes the rule fails and Outlook deactivates it.
Then I turn the rule back on and manually run it on my Inbox to catch up. The rule spontaneously fails and deactivates several times a day.
I would love to fix this once and for all. | This code showed me the different TypeNames that were in my Inbox:
```
Public Sub GetTypeNamesInbox()
Dim myOlItems As Outlook.Items
Set myOlItems = application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
Dim msg As Object
For Each msg In myOlItems
Debug.Print TypeName(msg)
'emails are typename MailItem
'Meeting responses are typename MeetingItem
'Delivery receipts are typename ReportItem
Next msg
End Sub
```
HTH |
78,932 | <p>I have the following HTML <code><select></code> element:</p>
<pre><code><select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
</code></pre>
<p>Using a JavaScript function with the <code>leaveCode</code> number as a parameter, how do I select the appropriate option in the list?</p>
| [
{
"answer_id": 78945,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 11,
"selected": true,
"text": "<p>You can use this function:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"tr... | 2008/09/17 | [
"https://Stackoverflow.com/questions/78932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | I have the following HTML `<select>` element:
```
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
```
Using a JavaScript function with the `leaveCode` number as a parameter, how do I select the appropriate option in the list? | You can use this function:
```js
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
```
```html
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
```
Optionally if you want to trigger onchange event also, you can use :
```
element.dispatchEvent(new Event('change'))
``` |
78,974 | <p>I've written a control that inherits from the <code>System.Web.UI.WebControls.DropDownList</code> and so I don't have any code in front for this control, but I still want to set the OutputCache directive. I there any way to set this in the C# code, say with an attribute or something like that? </p>
<p>I'm particularly hoping to be able to replicate the <code>VaryByParam</code> property</p>
| [
{
"answer_id": 79012,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));\nResponse.Cache.SetCacheability(HttpCacheability.Se... | 2008/09/17 | [
"https://Stackoverflow.com/questions/78974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] | I've written a control that inherits from the `System.Web.UI.WebControls.DropDownList` and so I don't have any code in front for this control, but I still want to set the OutputCache directive. I there any way to set this in the C# code, say with an attribute or something like that?
I'm particularly hoping to be able to replicate the `VaryByParam` property | I realize this is an incredibly old question but it is still worthy of an answer.
What you are talking about isn't a User Control it is a Custom Control. What you want to do with the OutputCache can be done simply with the Context Cache.
In your code where you are getting the data and binding to your DropDownList do something like this:
```
List<Object> listOfObjects = null;
//assuming a List of Objects... it doesn't matter whatever type of data you use
if (Context.Cache["MyDataCacheKey"] == null)
{
// data not cached, load it from database
listOfObjects = GetDataFromDB();
//add your data to the context cache with a sliding expiration of 10 minutes.
Context.Cache.Add("MyDataCacheKey", listOfObjects, null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(10.0),
System.Web.Caching.CacheItemPriority.Normal, null);
}
else
listOfObjects = (List<Object>)Context.Cache["MyDataCacheKey"];
DropDownList1.DataSource = listOfObjects;
DropDownList1.DataBind();
``` |
78,978 | <p>I'm working on a regular expression in a <code>.NET</code> project to get a specific tag. I would like to match the entire DIV tag and its contents:</p>
<pre><code><html>
<head><title>Test</title></head>
<body>
<p>The first paragraph.</p>
<div id='super_special'>
<p>The Store paragraph</p>
</div>
</body>
</head>
</code></pre>
<p>Code:</p>
<pre><code> Regex re = new Regex("(<div id='super_special'>.*?</div>)", RegexOptions.Multiline);
if (re.IsMatch(test))
Console.WriteLine("it matches");
else
Console.WriteLine("no match");
</code></pre>
<p>I want to match this:</p>
<pre><code><div id="super_special">
<p>Anything could go in here...doesn't matter. Let's get it all</p>
</div>
</code></pre>
<p>I thought <code>.</code> was supposed to get all characters, but it seems to having trouble with the carriage returns. What is my regex missing?</p>
<p>Thanks.</p>
| [
{
"answer_id": 78985,
"author": "mopoke",
"author_id": 14054,
"author_profile": "https://Stackoverflow.com/users/14054",
"pm_score": 1,
"selected": false,
"text": "<p>Depends what language you're working in. \nFor example, in perl you'd use the regex modifier s:</p>\n\n<pre><code>m{<d... | 2008/09/17 | [
"https://Stackoverflow.com/questions/78978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27870/"
] | I'm working on a regular expression in a `.NET` project to get a specific tag. I would like to match the entire DIV tag and its contents:
```
<html>
<head><title>Test</title></head>
<body>
<p>The first paragraph.</p>
<div id='super_special'>
<p>The Store paragraph</p>
</div>
</body>
</head>
```
Code:
```
Regex re = new Regex("(<div id='super_special'>.*?</div>)", RegexOptions.Multiline);
if (re.IsMatch(test))
Console.WriteLine("it matches");
else
Console.WriteLine("no match");
```
I want to match this:
```
<div id="super_special">
<p>Anything could go in here...doesn't matter. Let's get it all</p>
</div>
```
I thought `.` was supposed to get all characters, but it seems to having trouble with the carriage returns. What is my regex missing?
Thanks. | Out-of-the-box, without special modifiers, most regex implementations don't go beyond the end-of-line to match text. You probably should look in the documentation of the regex engine you're using for such modifier.
I have one other advice: beware of greed! Traditionally, regex **are** greedy which means that your regex would probably match this:
```
<div id="super_special">
I'm the wanted div!
</div>
<div id="not_special">
I'm not wanted, but I've been caught too :(
</div>
```
You should check for a "not-greedy" modifier, so that your regex would stop matching text at the **first** occurence of `</div>`, not at the **last** one.
Also, as others have said, consider using an HTML parser instead of regexes. It will save you a lot of headache.
*Edit: even a non-greedy regex wouldn't work as expected either, if `<div>`s are nested! Another reason to consider using an HTML parser.* |
79,041 | <p>I have a web system which has a classical parent-children menu saved in a database, with fields id as the PK, and parent_id to pointing to the owning menu. (Yes, I know this doesn't scale very well, but that's another topic). </p>
<p>So for these records (id-parent_id pairs):</p>
<pre><code>0-7 0-4 4-9 4-14 4-16 9-6
</code></pre>
<p>I have this tree:</p>
<pre><code>0
├ 7
└ 4
├ 9
| └ 6
├ 14
└ 16
</code></pre>
<p>I'm needing to hide a top node, so I have to make a list of all the childrens of that certain node, i.e. for 4, they will be (9, 6, 14, 16). Order doesn't matters.</p>
<p>I'm confused... does this fits into the classical tree problems? or is it a graph one?</p>
<p>How can I compose this structure and solve this problem using php?</p>
| [
{
"answer_id": 79067,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 2,
"selected": true,
"text": "<p>This is the perfect chance to use recursion!</p>\n\n<p>Pseudo-code:</p>\n\n<pre><code>nodeList = {}\nenumerateNodes(rootNo... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861/"
] | I have a web system which has a classical parent-children menu saved in a database, with fields id as the PK, and parent\_id to pointing to the owning menu. (Yes, I know this doesn't scale very well, but that's another topic).
So for these records (id-parent\_id pairs):
```
0-7 0-4 4-9 4-14 4-16 9-6
```
I have this tree:
```
0
├ 7
└ 4
├ 9
| └ 6
├ 14
└ 16
```
I'm needing to hide a top node, so I have to make a list of all the childrens of that certain node, i.e. for 4, they will be (9, 6, 14, 16). Order doesn't matters.
I'm confused... does this fits into the classical tree problems? or is it a graph one?
How can I compose this structure and solve this problem using php? | This is the perfect chance to use recursion!
Pseudo-code:
```
nodeList = {}
enumerateNodes(rootNode, nodeList);
function enumerateNodes(node, nodeList) {
nodeList += node;
foreach ( childnode in node.children ) {
enumerateNodes(childnode, nodeList);
}
}
```
Edit: Didn't notice that your tree is in the adjacent list format. I would probably just build that into an actual tree datastructure before I started working with it. Just loop through all pairs (creating nodes the first time you see them) and linking them. I *think* it should be easy... |
79,121 | <p>So, im trying to write some code that utilizes Nvidia's CUDA architecture. I noticed that copying to and from the device was really hurting my overall performance, so now I am trying to move a large amount of data onto the device.</p>
<p>As this data is used in numerous functions, I would like it to be global. Yes, I can pass pointers around, but I would really like to know how to work with globals in this instance. </p>
<p>So, I have device functions that want to access a device allocated array.</p>
<p>Ideally, I could do something like:</p>
<pre><code>__device__ float* global_data;
main()
{
cudaMalloc(global_data);
kernel1<<<blah>>>(blah); //access global data
kernel2<<<blah>>>(blah); //access global data again
}
</code></pre>
<p>However, I havent figured out how to create a dynamic array. I figured out a work around by declaring the array as follows:</p>
<pre><code>__device__ float global_data[REALLY_LARGE_NUMBER];
</code></pre>
<p>And while that doesn't require a cudaMalloc call, I would prefer the dynamic allocation approach.</p>
| [
{
"answer_id": 79256,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Spend some time focusing on the copious documentation offered by NVIDIA.</p>\n\n<p>From the Programming Guide:</p>\n\n<pre><... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14621/"
] | So, im trying to write some code that utilizes Nvidia's CUDA architecture. I noticed that copying to and from the device was really hurting my overall performance, so now I am trying to move a large amount of data onto the device.
As this data is used in numerous functions, I would like it to be global. Yes, I can pass pointers around, but I would really like to know how to work with globals in this instance.
So, I have device functions that want to access a device allocated array.
Ideally, I could do something like:
```
__device__ float* global_data;
main()
{
cudaMalloc(global_data);
kernel1<<<blah>>>(blah); //access global data
kernel2<<<blah>>>(blah); //access global data again
}
```
However, I havent figured out how to create a dynamic array. I figured out a work around by declaring the array as follows:
```
__device__ float global_data[REALLY_LARGE_NUMBER];
```
And while that doesn't require a cudaMalloc call, I would prefer the dynamic allocation approach. | Something like this should probably work.
```
#include <algorithm>
#define NDEBUG
#define CUT_CHECK_ERROR(errorMessage) do { \
cudaThreadSynchronize(); \
cudaError_t err = cudaGetLastError(); \
if( cudaSuccess != err) { \
fprintf(stderr, "Cuda error: %s in file '%s' in line %i : %s.\n", \
errorMessage, __FILE__, __LINE__, cudaGetErrorString( err) );\
exit(EXIT_FAILURE); \
} } while (0)
__device__ float *devPtr;
__global__
void kernel1(float *some_neat_data)
{
devPtr = some_neat_data;
}
__global__
void kernel2(void)
{
devPtr[threadIdx.x] *= .3f;
}
int main(int argc, char *argv[])
{
float* otherDevPtr;
cudaMalloc((void**)&otherDevPtr, 256 * sizeof(*otherDevPtr));
cudaMemset(otherDevPtr, 0, 256 * sizeof(*otherDevPtr));
kernel1<<<1,128>>>(otherDevPtr);
CUT_CHECK_ERROR("kernel1");
kernel2<<<1,128>>>();
CUT_CHECK_ERROR("kernel2");
return 0;
}
```
Give it a whirl. |
79,126 | <p>I'm building a function to extend the <code>Enum.Parse</code> concept that</p>
<ul>
<li>Allows a default value to be parsed in case that an Enum value is not found</li>
<li>Is case insensitive</li>
</ul>
<p>So I wrote the following:</p>
<pre><code>public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
</code></pre>
<p>I am getting a Error Constraint cannot be special class <code>System.Enum</code>.</p>
<p>Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the <code>Parse</code> function and pass a type as an attribute, which forces the ugly boxing requirement to your code.</p>
<p><strong>EDIT</strong> All suggestions below have been greatly appreciated, thanks.</p>
<p>Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML)</p>
<pre><code>public static class EnumUtils
{
public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
}
</code></pre>
<p><strong>EDIT:</strong> (16th Feb 2015) Christopher Currens has posted <a href="https://stackoverflow.com/a/8086788">a compiler enforced type-safe generic solution in MSIL or F#</a> below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page.</p>
<p><strong>EDIT 2:</strong> (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)</p>
| [
{
"answer_id": 79148,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 3,
"selected": false,
"text": "<p>Hope this is helpful:</p>\n\n<pre><code>public static TValue ParseEnum<TValue>(string value, TValue defaultVa... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | I'm building a function to extend the `Enum.Parse` concept that
* Allows a default value to be parsed in case that an Enum value is not found
* Is case insensitive
So I wrote the following:
```
public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
```
I am getting a Error Constraint cannot be special class `System.Enum`.
Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the `Parse` function and pass a type as an attribute, which forces the ugly boxing requirement to your code.
**EDIT** All suggestions below have been greatly appreciated, thanks.
Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML)
```
public static class EnumUtils
{
public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
}
```
**EDIT:** (16th Feb 2015) Christopher Currens has posted [a compiler enforced type-safe generic solution in MSIL or F#](https://stackoverflow.com/a/8086788) below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page.
**EDIT 2:** (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :) | This feature is finally supported in C# 7.3!
--------------------------------------------
The following snippet (from [the dotnet samples](https://github.com/dotnet/samples/blob/3ee82879284e3f4755251fd33c3b3e533f7b3485/snippets/csharp/keywords/GenericWhereConstraints.cs#L180-L190)) demonstrates how:
```
public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum
{
var result = new Dictionary<int, string>();
var values = Enum.GetValues(typeof(T));
foreach (int item in values)
result.Add(item, Enum.GetName(typeof(T), item));
return result;
}
```
Be sure to set your language version in your C# project to version 7.3.
---
Original Answer below:
I'm late to the game, but I took it as a challenge to see how it could be done. It's not possible in C# (or VB.NET, but scroll down for F#), but *is possible* in MSIL. I wrote this little....thing
```
// license: http://www.apache.org/licenses/LICENSE-2.0.html
.assembly MyThing{}
.class public abstract sealed MyThing.Thing
extends [mscorlib]System.Object
{
.method public static !!T GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue,
!!T defaultValue) cil managed
{
.maxstack 2
.locals init ([0] !!T temp,
[1] !!T return_value,
[2] class [mscorlib]System.Collections.IEnumerator enumerator,
[3] class [mscorlib]System.IDisposable disposer)
// if(string.IsNullOrEmpty(strValue)) return defaultValue;
ldarg strValue
call bool [mscorlib]System.String::IsNullOrEmpty(string)
brfalse.s HASVALUE
br RETURNDEF // return default it empty
// foreach (T item in Enum.GetValues(typeof(T)))
HASVALUE:
// Enum.GetValues.GetEnumerator()
ldtoken !!T
call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)
callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator()
stloc enumerator
.try
{
CONDITION:
ldloc enumerator
callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
brfalse.s LEAVE
STATEMENTS:
// T item = (T)Enumerator.Current
ldloc enumerator
callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
unbox.any !!T
stloc temp
ldloca.s temp
constrained. !!T
// if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
callvirt instance string [mscorlib]System.Object::ToString()
callvirt instance string [mscorlib]System.String::ToLower()
ldarg strValue
callvirt instance string [mscorlib]System.String::Trim()
callvirt instance string [mscorlib]System.String::ToLower()
callvirt instance bool [mscorlib]System.String::Equals(string)
brfalse.s CONDITION
ldloc temp
stloc return_value
leave.s RETURNVAL
LEAVE:
leave.s RETURNDEF
}
finally
{
// ArrayList's Enumerator may or may not inherit from IDisposable
ldloc enumerator
isinst [mscorlib]System.IDisposable
stloc.s disposer
ldloc.s disposer
ldnull
ceq
brtrue.s LEAVEFINALLY
ldloc.s disposer
callvirt instance void [mscorlib]System.IDisposable::Dispose()
LEAVEFINALLY:
endfinally
}
RETURNDEF:
ldarg defaultValue
stloc return_value
RETURNVAL:
ldloc return_value
ret
}
}
```
Which generates a function that **would** look like this, if it were valid C#:
```
T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum
```
Then with the following C# code:
```
using MyThing;
// stuff...
private enum MyEnum { Yes, No, Okay }
static void Main(string[] args)
{
Thing.GetEnumFromString("No", MyEnum.Yes); // returns MyEnum.No
Thing.GetEnumFromString("Invalid", MyEnum.Okay); // returns MyEnum.Okay
Thing.GetEnumFromString("AnotherInvalid", 0); // compiler error, not an Enum
}
```
Unfortunately, this means having this part of your code written in MSIL instead of C#, with the only added benefit being that you're able to constrain this method by `System.Enum`. It's also kind of a bummer, because it gets compiled into a separate assembly. However, it doesn't mean you have to deploy it that way.
By removing the line `.assembly MyThing{}` and invoking ilasm as follows:
```
ilasm.exe /DLL /OUTPUT=MyThing.netmodule
```
you get a netmodule instead of an assembly.
Unfortunately, VS2010 (and earlier, obviously) does not support adding netmodule references, which means you'd have to leave it in 2 separate assemblies when you're debugging. The only way you can add them as part of your assembly would be to run csc.exe yourself using the `/addmodule:{files}` command line argument. It wouldn't be *too* painful in an MSBuild script. Of course, if you're brave or stupid, you can run csc yourself manually each time. And it certainly gets more complicated as multiple assemblies need access to it.
So, it CAN be done in .Net. Is it worth the extra effort? Um, well, I guess I'll let you decide on that one.
---
### F# Solution as alternative
Extra Credit: It turns out that a generic restriction on `enum` is possible in at least one other .NET language besides MSIL: F#.
```ml
type MyThing =
static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T =
/// protect for null (only required in interop with C#)
let str = if isNull str then String.Empty else str
Enum.GetValues(typedefof<'T>)
|> Seq.cast<_>
|> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0)
|> function Some x -> x | None -> defaultValue
```
This one is easier to maintain since it's a well-known language with full Visual Studio IDE support, but you still need a separate project in your solution for it. However, it naturally produces considerably different IL (the code *is* very different) and it relies on the `FSharp.Core` library, which, just like any other external library, needs to become part of your distribution.
Here's how you can use it (basically the same as the MSIL solution), and to show that it correctly fails on otherwise synonymous structs:
```
// works, result is inferred to have type StringComparison
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", StringComparison.Ordinal);
// type restriction is recognized by C#, this fails at compile time
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", 42);
``` |
79,129 | <p>For the life of me, I cannot get the SqlProfileProvider to work in an MVC project that I'm working on.</p>
<p>The first interesting thing that I realized is that Visual Studio does not automatically generate the ProfileCommon proxy class for you. That's not a big deal since it's simpy a matter of extending the ProfileBase class. After creating a ProfileCommon class, I wrote the following Action method for creating the user profile.</p>
<pre><code>[AcceptVerbs("POST")]
public ActionResult CreateProfile(string company, string phone, string fax, string city, string state, string zip)
{
MembershipUser user = Membership.GetUser();
ProfileCommon profile = ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon;
profile.Company = company;
profile.Phone = phone;
profile.Fax = fax;
profile.City = city;
profile.State = state;
profile.Zip = zip;
profile.Save();
return RedirectToAction("Index", "Account");
}</code></pre>
<p>The problem that I'm having is that the call to ProfileCommon.Create() cannot cast to type ProfileCommon, so I'm not able to get back my profile object, which obviously causes the next line to fail since profile is null.</p>
<p>Following is a snippet of my web.config:</p>
<p><pre><code><profile defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="false" enabled="true">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="FirstName" type="string" />
<add name="LastName" type="string" />
<add name="Company" type="string" />
<add name="Phone" type="string" />
<add name="Fax" type="string" />
<add name="City" type="string" />
<add name="State" type="string" />
<add name="Zip" type="string" />
<add name="Email" type="string" >
</properties>
</profile></pre></code></p>
<p>The MembershipProvider is working without a hitch, so I know that the connection string is good.</p>
<p>Just in case it's helpful, here is my ProfileCommon class:</p>
<pre><code>public class ProfileCommon : ProfileBase
{
public virtual string Company
{
get
{
return ((string)(this.GetPropertyValue("Company")));
}
set
{
this.SetPropertyValue("Company", value);
}
}
public virtual string Phone
{
get
{
return ((string)(this.GetPropertyValue("Phone")));
}
set
{
this.SetPropertyValue("Phone", value);
}
}
public virtual string Fax
{
get
{
return ((string)(this.GetPropertyValue("Fax")));
}
set
{
this.SetPropertyValue("Fax", value);
}
}
public virtual string City
{
get
{
return ((string)(this.GetPropertyValue("City")));
}
set
{
this.SetPropertyValue("City", value);
}
}
public virtual string State
{
get
{
return ((string)(this.GetPropertyValue("State")));
}
set
{
this.SetPropertyValue("State", value);
}
}
public virtual string Zip
{
get
{
return ((string)(this.GetPropertyValue("Zip")));
}
set
{
this.SetPropertyValue("Zip", value);
}
}
public virtual ProfileCommon GetProfile(string username)
{
return ((ProfileCommon)(ProfileBase.Create(username)));
}
}</code></pre>
<p>Any thoughts on what I might be doing wrong? Have any of the rest of you successfully integrated a ProfileProvider with your ASP.NET MVC projects?</p>
<p>Thank you in advance...</p>
| [
{
"answer_id": 80594,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure about the whole question, but one thing I noticed in your code:</p>\n\n<pre><code>ProfileCommon profi... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10792/"
] | For the life of me, I cannot get the SqlProfileProvider to work in an MVC project that I'm working on.
The first interesting thing that I realized is that Visual Studio does not automatically generate the ProfileCommon proxy class for you. That's not a big deal since it's simpy a matter of extending the ProfileBase class. After creating a ProfileCommon class, I wrote the following Action method for creating the user profile.
```
[AcceptVerbs("POST")]
public ActionResult CreateProfile(string company, string phone, string fax, string city, string state, string zip)
{
MembershipUser user = Membership.GetUser();
ProfileCommon profile = ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon;
profile.Company = company;
profile.Phone = phone;
profile.Fax = fax;
profile.City = city;
profile.State = state;
profile.Zip = zip;
profile.Save();
return RedirectToAction("Index", "Account");
}
```
The problem that I'm having is that the call to ProfileCommon.Create() cannot cast to type ProfileCommon, so I'm not able to get back my profile object, which obviously causes the next line to fail since profile is null.
Following is a snippet of my web.config:
```
<profile defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="false" enabled="true">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="FirstName" type="string" />
<add name="LastName" type="string" />
<add name="Company" type="string" />
<add name="Phone" type="string" />
<add name="Fax" type="string" />
<add name="City" type="string" />
<add name="State" type="string" />
<add name="Zip" type="string" />
<add name="Email" type="string" >
</properties>
</profile>
```
The MembershipProvider is working without a hitch, so I know that the connection string is good.
Just in case it's helpful, here is my ProfileCommon class:
```
public class ProfileCommon : ProfileBase
{
public virtual string Company
{
get
{
return ((string)(this.GetPropertyValue("Company")));
}
set
{
this.SetPropertyValue("Company", value);
}
}
public virtual string Phone
{
get
{
return ((string)(this.GetPropertyValue("Phone")));
}
set
{
this.SetPropertyValue("Phone", value);
}
}
public virtual string Fax
{
get
{
return ((string)(this.GetPropertyValue("Fax")));
}
set
{
this.SetPropertyValue("Fax", value);
}
}
public virtual string City
{
get
{
return ((string)(this.GetPropertyValue("City")));
}
set
{
this.SetPropertyValue("City", value);
}
}
public virtual string State
{
get
{
return ((string)(this.GetPropertyValue("State")));
}
set
{
this.SetPropertyValue("State", value);
}
}
public virtual string Zip
{
get
{
return ((string)(this.GetPropertyValue("Zip")));
}
set
{
this.SetPropertyValue("Zip", value);
}
}
public virtual ProfileCommon GetProfile(string username)
{
return ((ProfileCommon)(ProfileBase.Create(username)));
}
}
```
Any thoughts on what I might be doing wrong? Have any of the rest of you successfully integrated a ProfileProvider with your ASP.NET MVC projects?
Thank you in advance... | Here's what you need to do:
1) In Web.config's section, add "inherits" attribute in addition to your other attribute settings:
```
<profile inherits="MySite.Models.ProfileCommon" defaultProvider="....
```
2) Remove entire `<properties>` section from Web.config, since you have already defined them in your custom ProfileCommon class and also instructed to inherit from your custom class in previous step
3) Change the code of your ProfileCommon.GetProfile() method to
```
public virtual ProfileCommon GetProfile(string username)
{
return Create(username) as ProfileCommon;
}
```
Hope this helps. |
79,165 | <p>I read the Git manual, FAQ, Git - SVN crash course, etc. and they all explain this and that, but nowhere can you find a simple instruction like:</p>
<p>SVN repository in: <code>svn://myserver/path/to/svn/repos</code></p>
<p>Git repository in: <code>git://myserver/path/to/git/repos</code></p>
<pre><code>git-do-the-magic-svn-import-with-history \
svn://myserver/path/to/svn/repos \
git://myserver/path/to/git/repos
</code></pre>
<p>I don't expect it to be that simple, and I don't expect it to be a single command. But I do expect it not to try to explain anything - just to say what steps to take given this example.</p>
| [
{
"answer_id": 79178,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 10,
"selected": true,
"text": "<p>Magic:</p>\n\n<pre><code>$ git svn clone http://svn/repo/here/trunk\n</code></pre>\n\n<p>Git and SVN operate very different... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
] | I read the Git manual, FAQ, Git - SVN crash course, etc. and they all explain this and that, but nowhere can you find a simple instruction like:
SVN repository in: `svn://myserver/path/to/svn/repos`
Git repository in: `git://myserver/path/to/git/repos`
```
git-do-the-magic-svn-import-with-history \
svn://myserver/path/to/svn/repos \
git://myserver/path/to/git/repos
```
I don't expect it to be that simple, and I don't expect it to be a single command. But I do expect it not to try to explain anything - just to say what steps to take given this example. | Magic:
```
$ git svn clone http://svn/repo/here/trunk
```
Git and SVN operate very differently. You need to learn Git, and if you want to track changes from SVN upstream, you need to learn `git-svn`. The `git-svn` [main page has a good examples section](https://git-scm.com/docs/git-svn):
```
$ git svn --help
``` |
79,197 | <p>What's a simple way to combine <strong>feed</strong> and <strong>feed2</strong>? I want the items from <strong>feed2</strong> to be added to <strong>feed</strong>. Also I want to avoid duplicates as <strong>feed</strong> might already have items when a question is tagged with both WPF and Silverlight.</p>
<pre><code>Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight");
XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri);
SyndicationFeed feed = SyndicationFeed.Load(reader);
Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf");
XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri);
SyndicationFeed feed2 = SyndicationFeed.Load(reader2);
</code></pre>
| [
{
"answer_id": 79372,
"author": "David Thibault",
"author_id": 5903,
"author_profile": "https://Stackoverflow.com/users/5903",
"pm_score": 0,
"selected": false,
"text": "<p>If it's solely for stackoverflow, you can use this :<br>\n<a href=\"https://stackoverflow.com/feeds/tag/silverlight... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1133/"
] | What's a simple way to combine **feed** and **feed2**? I want the items from **feed2** to be added to **feed**. Also I want to avoid duplicates as **feed** might already have items when a question is tagged with both WPF and Silverlight.
```
Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight");
XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri);
SyndicationFeed feed = SyndicationFeed.Load(reader);
Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf");
XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri);
SyndicationFeed feed2 = SyndicationFeed.Load(reader2);
``` | You can use LINQ to simplify the code to join two lists (don't forget to put System.Linq in your usings and if necessary reference System.Core in your project) Here's a Main that does the union and prints them to console (with proper cleanup of the Reader).
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ServiceModel.Syndication;
namespace FeedUnion
{
class Program
{
static void Main(string[] args)
{
Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight");
SyndicationFeed feed;
SyndicationFeed feed2;
using(XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri))
{
feed= SyndicationFeed.Load(reader);
}
Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf");
using (XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri))
{
feed2 = SyndicationFeed.Load(reader2);
}
SyndicationFeed feed3 = new SyndicationFeed(feed.Items.Union(feed2.Items));
StringBuilder builder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(builder))
{
feed3.SaveAsRss20(writer);
System.Console.Write(builder.ToString());
System.Console.Read();
}
}
}
}
``` |
79,215 | <p>For example, if I have a page located in Views/Home/Index.aspx and a JavaScript file located in Views/Home/Index.js, how do you reference this on the aspx page?</p>
<p>The example below doesn't work even though the compiler says the path is correct</p>
<pre><code><script src="Index.js" type="text/javascript"></script>
</code></pre>
<p>The exact same issue has been posted here in more detail:
<a href="http://forums.asp.net/p/1319380/2619991.aspx" rel="nofollow noreferrer">http://forums.asp.net/p/1319380/2619991.aspx</a></p>
<p>If this is not currently possible, will it be in the future? If not, how is everyone managing their javascript resources for large Asp.net MVC projects? Do you just create a folder structure in the Content folder that mirrors your View folder structure? YUCK!</p>
| [
{
"answer_id": 79246,
"author": "Chris Pietschmann",
"author_id": 7831,
"author_profile": "https://Stackoverflow.com/users/7831",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the VirtualPathUtility.ToAbsolute method like below to convert the app relative url of the .js file ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10941/"
] | For example, if I have a page located in Views/Home/Index.aspx and a JavaScript file located in Views/Home/Index.js, how do you reference this on the aspx page?
The example below doesn't work even though the compiler says the path is correct
```
<script src="Index.js" type="text/javascript"></script>
```
The exact same issue has been posted here in more detail:
<http://forums.asp.net/p/1319380/2619991.aspx>
If this is not currently possible, will it be in the future? If not, how is everyone managing their javascript resources for large Asp.net MVC projects? Do you just create a folder structure in the Content folder that mirrors your View folder structure? YUCK! | For shared javascript resources using the Content folder makes sense. The issue was I was specifically trying to solve was aspx page specific javascript that would never be reused.
I think what I will just have to do is put the aspx page specific javascript right onto the page itself and keep the shared js resources in the Content folder. |
79,258 | <p>Is there a tool that will find for me all the css classes that I am referencing in my HTML that don't actually exist?</p>
<p>ie. if I have <ul class="topnav" /> in my HTML and the topnav class doesn't exist in any of the referenced CSS files.</p>
<p>This is similar to <a href="https://stackoverflow.com/questions/33242/how-can-i-find-unused-images-and-css-styles-in-a-website">SO#33242</a>, which asks how to find unused CSS styles. This isn't a duplicate, as that question asks which CSS classes are not used. This is the opposite problem.</p>
| [
{
"answer_id": 79306,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 1,
"selected": false,
"text": "<p>Error Console in Firefox. Although, it gives <strong>all</strong> CSS errors, so you have to read through it.</p>... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4640/"
] | Is there a tool that will find for me all the css classes that I am referencing in my HTML that don't actually exist?
ie. if I have <ul class="topnav" /> in my HTML and the topnav class doesn't exist in any of the referenced CSS files.
This is similar to [SO#33242](https://stackoverflow.com/questions/33242/how-can-i-find-unused-images-and-css-styles-in-a-website), which asks how to find unused CSS styles. This isn't a duplicate, as that question asks which CSS classes are not used. This is the opposite problem. | You can put this JavaScript in the page that can perform this task for you:
```
function forItems(a, f) {
for (var i = 0; i < a.length; i++) f(a.item(i))
}
function classExists(className) {
var pattern = new RegExp('\\.' + className + '\\b'), found = false
try {
forItems(document.styleSheets, function(ss) {
// decompose only screen stylesheets
if (!ss.media.length || /\b(all|screen)\b/.test(ss.media.mediaText))
forItems(ss.cssRules, function(r) {
// ignore rules other than style rules
if (r.type == CSSRule.STYLE_RULE && r.selectorText.match(pattern)) {
found = true
throw "found"
}
})
})
} catch(e) {}
return found
}
``` |
79,264 | <p>Is there a program or API I can code against to extract individual files from a Windows Vista Complete PC Backup image?</p>
<p>I like the idea of having a complete image to restore from, but hate the idea that I have to make two backups, one for restoring individual files, and one for restoring my computer in the event of a catastrophic failure.</p>
| [
{
"answer_id": 79306,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 1,
"selected": false,
"text": "<p>Error Console in Firefox. Although, it gives <strong>all</strong> CSS errors, so you have to read through it.</p>... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
] | Is there a program or API I can code against to extract individual files from a Windows Vista Complete PC Backup image?
I like the idea of having a complete image to restore from, but hate the idea that I have to make two backups, one for restoring individual files, and one for restoring my computer in the event of a catastrophic failure. | You can put this JavaScript in the page that can perform this task for you:
```
function forItems(a, f) {
for (var i = 0; i < a.length; i++) f(a.item(i))
}
function classExists(className) {
var pattern = new RegExp('\\.' + className + '\\b'), found = false
try {
forItems(document.styleSheets, function(ss) {
// decompose only screen stylesheets
if (!ss.media.length || /\b(all|screen)\b/.test(ss.media.mediaText))
forItems(ss.cssRules, function(r) {
// ignore rules other than style rules
if (r.type == CSSRule.STYLE_RULE && r.selectorText.match(pattern)) {
found = true
throw "found"
}
})
})
} catch(e) {}
return found
}
``` |
79,275 | <p>I have a form like this:</p>
<pre><code><form name="mine">
<input type=text name=one>
<input type=text name=two>
<input type=text name=three>
</form>
</code></pre>
<p>When user types a value in 'one', I sometimes want to skip the field 'two', depending on what he typed. For example, if user types '123' and uses Tab to move to next field, I want to skip it and go to field three.</p>
<p>I tried to use <code>OnBlur</code> and <code>OnEnter</code>, without success. </p>
<p><strong>Try 1:</strong></p>
<pre><code><form name="mine">
<input type=text name=one onBlur="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=two>
<input type=text name=three>
</form>
</code></pre>
<p><strong>Try 2:</strong></p>
<pre><code><form name="mine">
<input type=text name=one>
<input type=text name=two onEnter="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=three>
</form>
</code></pre>
<p>but none of these works. Looks like the browser doesn't allow you to mess with focus while the focus is changing. </p>
<p>BTW, all this tried with Firefox on Linux.</p>
| [
{
"answer_id": 79317,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 3,
"selected": true,
"text": "<p>Try to attach tabindex attribute to your elements and then programmaticaly (in javaScript change it):</p>\n\n<pre><c... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
] | I have a form like this:
```
<form name="mine">
<input type=text name=one>
<input type=text name=two>
<input type=text name=three>
</form>
```
When user types a value in 'one', I sometimes want to skip the field 'two', depending on what he typed. For example, if user types '123' and uses Tab to move to next field, I want to skip it and go to field three.
I tried to use `OnBlur` and `OnEnter`, without success.
**Try 1:**
```
<form name="mine">
<input type=text name=one onBlur="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=two>
<input type=text name=three>
</form>
```
**Try 2:**
```
<form name="mine">
<input type=text name=one>
<input type=text name=two onEnter="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=three>
</form>
```
but none of these works. Looks like the browser doesn't allow you to mess with focus while the focus is changing.
BTW, all this tried with Firefox on Linux. | Try to attach tabindex attribute to your elements and then programmaticaly (in javaScript change it):
```
<INPUT tabindex="3" type="submit" name="mySubmit">
``` |
79,292 | <p>Can databases (MySQL in particular, any SQL--MS, Oracle, Postgres--in general) do mass updates, and figure out on their own what the new value should be? Say for example I've got a database with information about a bunch of computers, and all of these computers have drives of various sizes--anywhere from 20 to 250 GB. Then one day we upgrade every single computer by adding a 120 GB hard drive. Is there a way to say something like</p>
<pre><code>update computers set total_disk_space = (whatever that row's current total_disk_space is plus 120)
</code></pre>
| [
{
"answer_id": 79305,
"author": "Tom Leys",
"author_id": 11440,
"author_profile": "https://Stackoverflow.com/users/11440",
"pm_score": 2,
"selected": false,
"text": "<p>Yeah:</p>\n\n<pre><code>update computers set total_disk_space = total_disk_space + 120;\n</code></pre>\n"
},
{
... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14701/"
] | Can databases (MySQL in particular, any SQL--MS, Oracle, Postgres--in general) do mass updates, and figure out on their own what the new value should be? Say for example I've got a database with information about a bunch of computers, and all of these computers have drives of various sizes--anywhere from 20 to 250 GB. Then one day we upgrade every single computer by adding a 120 GB hard drive. Is there a way to say something like
```
update computers set total_disk_space = (whatever that row's current total_disk_space is plus 120)
``` | For the entire Table then:
```
Update Computers
Set Total_Disk_Space = Total_Disk_Space + 120;
```
If, you only want to update certain ones, then you'd need filters, for example:
```
Update Computers
Set Total_Disk_Space = Total_Disk_Space + 120
Where PurchaseDate BETWEEN '1/1/2008' AND GETDATE();
``` |
79,352 | <p>I have a method that can return either a single object or a collection of objects. I want to be able to run object.collect on the result of that method whether or not it is a single object or a collection already. How can i do this?</p>
<pre><code>profiles = ProfileResource.search(params)
output = profiles.collect do | profile |
profile.to_hash
end
</code></pre>
<p>If profiles is a single object, I get a NoMethodError exception when I try to execute collect on that object.</p>
| [
{
"answer_id": 79416,
"author": "Matt Haley",
"author_id": 14142,
"author_profile": "https://Stackoverflow.com/users/14142",
"pm_score": 1,
"selected": false,
"text": "<pre><code>profiles = [ProfileResource.search(params)].flatten\noutput = profiles.collect do |profile|\n profile.to_h... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1486/"
] | I have a method that can return either a single object or a collection of objects. I want to be able to run object.collect on the result of that method whether or not it is a single object or a collection already. How can i do this?
```
profiles = ProfileResource.search(params)
output = profiles.collect do | profile |
profile.to_hash
end
```
If profiles is a single object, I get a NoMethodError exception when I try to execute collect on that object. | Careful with the flatten approach, if search() returned nested arrays then unexpected behaviour might result.
```
profiles = ProfileResource.search(params)
profiles = [profiles] if !profiles.respond_to?(:collect)
output = profiles.collect do |profile|
profile.to_hash
end
``` |
79,367 | <p>I have a query:</p>
<pre><code>SELECT *
FROM Items
WHERE column LIKE '%foo%'
OR column LIKE '%bar%'
</code></pre>
<p>How do I order the results?</p>
<p>Let's say I have rows that match 'foo' and rows that match 'bar' but I also have a row with 'foobar'.</p>
<p>How do I order the returned rows so that the first results are the ones that matched more LIKEs? </p>
| [
{
"answer_id": 79375,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 0,
"selected": false,
"text": "<p>Which DBMS?</p>\n\n<p>It can be done via CTE or Union for example, but if you are using, for example, MySQL, then... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a query:
```
SELECT *
FROM Items
WHERE column LIKE '%foo%'
OR column LIKE '%bar%'
```
How do I order the results?
Let's say I have rows that match 'foo' and rows that match 'bar' but I also have a row with 'foobar'.
How do I order the returned rows so that the first results are the ones that matched more LIKEs? | Case or the kind of conditional construct your RDBMS supports is a way to do it
```
select *, case when col like '%foo%' and col like '%bar%' then 2 end
else 1 end as ordcol
from items
where col like '%foo%' or col like '%bar%' order by ordcol
``` |
79,445 | <p>I'd like to write a simple C# application to monitor the line-in audio and give me the current (well, the rolling average) beats per minute.</p>
<p>I've seen <a href="http://www.gamedev.net/page/resources/_/technical/math-and-physics/beat-detection-algorithms-r1952" rel="noreferrer">this gamedev article</a>, and that was absolutely no help. I went through and tried to implement what he was doing but it just wasn't working.</p>
<p>I know there have to be tons of solutions for this, because lots of DJ software does it, but I'm not having any luck in finding any open-source library or instructions on doing it myself.</p>
| [
{
"answer_id": 79480,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 3,
"selected": false,
"text": "<p>This is by no means an easy problem. I'll try to give you an overview only.</p>\n\n<p>What you could do is something like... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14758/"
] | I'd like to write a simple C# application to monitor the line-in audio and give me the current (well, the rolling average) beats per minute.
I've seen [this gamedev article](http://www.gamedev.net/page/resources/_/technical/math-and-physics/beat-detection-algorithms-r1952), and that was absolutely no help. I went through and tried to implement what he was doing but it just wasn't working.
I know there have to be tons of solutions for this, because lots of DJ software does it, but I'm not having any luck in finding any open-source library or instructions on doing it myself. | Calculate a powerspectrum with a sliding window FFT:
Take 1024 samples:
```
double[] signal = stream.Take(1024);
```
Feed it to an FFT algorithm:
```
double[] real = new double[signal.Length];
double[] imag = new double[signal.Length);
FFT(signal, out real, out imag);
```
You will get a real part and an imaginary part. Do NOT throw away the imaginary part. Do the same to the real part as the imaginary. While it is true that the imaginary part is pi / 2 out of phase with the real, it still contains 50% of the spectrum information.
EDIT:
Calculate the power as opposed to the amplitude so that you have a high number when it is loud and close to zero when it is quiet:
```
for (i=0; i < real.Length; i++) real[i] = real[i] * real[i];
```
Similarly for the imaginary part.
```
for (i=0; i < imag.Length; i++) imag[i] = imag[i] * imag[i];
```
Now you have a power spectrum for the last 1024 samples. Where the first part of the spectrum is the low frequencies and the last part of the spectrum is the high
frequencies.
If you want to find BPM in popular music you should probably focus on the bass. You can pick up the bass intensity by summing the lower part of the power spectrum. Which numbers to use depends on the sampling frequency:
```
double bassIntensity = 0;
for (i=8; i < 96; i++) bassIntensity += real[i];
```
Now do the same again but move the window 256 samples before you calculate a new spectrum. Now you end up with calculating the bassIntensity for every 256 samples.
This is a good input for your BPM analysis. When the bass is quiet you do not have a beat and when it is loud you have a beat.
Good luck! |
79,454 | <p>Recently I've been experimenting with TDD while developing a GUI application in Python. I find it very reassuring to have tests that verify the functionality of my code, but it's been tricky to follow some of the recommened practices of TDD. Namely, writing tests first has been hard. And I'm finding it difficult to make my tests readable (due to extensive use of a mocking library).</p>
<p>I chose a mocking library called <a href="http://labix.org/mocker" rel="noreferrer">mocker</a>. I use it a lot since much of the code I'm testing makes calls to (a) other methods in my application that depend on system state or (b) ObjC/Cocoa objects that cannot exist without an event loop, etc.</p>
<p>Anyway, I've got a lot of tests that look like this:</p>
<pre><code>def test_current_window_controller():
def test(config):
ac = AppController()
m = Mocker()
ac.iter_window_controllers = iwc = m.replace(ac.iter_window_controllers)
expect(iwc()).result(iter(config))
with m:
result = ac.current_window_controller()
assert result == (config[0] if config else None)
yield test, []
yield test, [0]
yield test, [1, 0]
</code></pre>
<p>Notice that this is actually three tests; all use the same parameterized test function. Here's the code that is being tested:</p>
<pre><code>def current_window_controller(self):
try:
# iter_window_controllers() iterates in z-order starting
# with the controller of the top-most window
# assumption: the top-most window is the "current" one
wc = self.iter_window_controllers().next()
except StopIteration:
return None
return wc
</code></pre>
<p>One of the things I've noticed with using mocker is that it's easier to write the application code first and then go back and write the tests second, since most of the time I'm mocking many method calls and the syntax to write the mocked calls is much more verbose (thus harder to write) than the application code. It's easier to write the app code and then model the test code off of that.</p>
<p>I find that with this testing method (and a bit of discipline) I can easily write code with 100% test coverage.</p>
<p>I'm wondering if these tests are good tests? Will I regret doing it this way down the road when I finally discover the secret to writing good tests?</p>
<p>Am I violating the core principles of TDD so much that my testing is in vain?</p>
| [
{
"answer_id": 79667,
"author": "etchasketch",
"author_id": 14640,
"author_profile": "https://Stackoverflow.com/users/14640",
"pm_score": -1,
"selected": false,
"text": "<p>Unit tests are really useful when you refactor your code (ie. completely rewrite or move a module). As long as you ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10840/"
] | Recently I've been experimenting with TDD while developing a GUI application in Python. I find it very reassuring to have tests that verify the functionality of my code, but it's been tricky to follow some of the recommened practices of TDD. Namely, writing tests first has been hard. And I'm finding it difficult to make my tests readable (due to extensive use of a mocking library).
I chose a mocking library called [mocker](http://labix.org/mocker). I use it a lot since much of the code I'm testing makes calls to (a) other methods in my application that depend on system state or (b) ObjC/Cocoa objects that cannot exist without an event loop, etc.
Anyway, I've got a lot of tests that look like this:
```
def test_current_window_controller():
def test(config):
ac = AppController()
m = Mocker()
ac.iter_window_controllers = iwc = m.replace(ac.iter_window_controllers)
expect(iwc()).result(iter(config))
with m:
result = ac.current_window_controller()
assert result == (config[0] if config else None)
yield test, []
yield test, [0]
yield test, [1, 0]
```
Notice that this is actually three tests; all use the same parameterized test function. Here's the code that is being tested:
```
def current_window_controller(self):
try:
# iter_window_controllers() iterates in z-order starting
# with the controller of the top-most window
# assumption: the top-most window is the "current" one
wc = self.iter_window_controllers().next()
except StopIteration:
return None
return wc
```
One of the things I've noticed with using mocker is that it's easier to write the application code first and then go back and write the tests second, since most of the time I'm mocking many method calls and the syntax to write the mocked calls is much more verbose (thus harder to write) than the application code. It's easier to write the app code and then model the test code off of that.
I find that with this testing method (and a bit of discipline) I can easily write code with 100% test coverage.
I'm wondering if these tests are good tests? Will I regret doing it this way down the road when I finally discover the secret to writing good tests?
Am I violating the core principles of TDD so much that my testing is in vain? | **If you are writing your tests after you've written your code and making them pass, you are not doing TDD** (nor are you getting any benefits of Test-First or Test-Driven development.. check out SO questions for definitive books on TDD)
>
> One of the things I've noticed with
> using mocker is that it's easier to
> write the application code first and
> then go back and write the tests
> second, since most of the time I'm
> mocking many method calls and the
> syntax to write the mocked calls is
> much more verbose (thus harder to
> write) than the application code. It's
> easier to write the app code and then
> model the test code off of that.
>
>
>
Of course, its easier because you are just testing that the sky is orange after you made it orange by painting it with a specific kind of brush.
This is retrofitting tests (for self-assurance). Mocks are good but you should know how and when to use them - Like the saying goes 'When you have a hammer everything looks like a nail' It's also easy to write a whole load of unreadable and not-as-helpful-as-can-be tests. The time spent understanding what the test is about is time lost that can be used to fix broken ones.
And the point is:
* Read [Mocks aren't stubs - Martin Fowler](http://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting) if you haven't already. Google out some documented instances of good [ModelViewPresenter](http://martinfowler.com/eaaDev/ModelViewPresenter.html) patterned GUIs (Fake/Mock out the UIs if necessary).
* Study your options and choose wisely. I'll play the guy with the halo on your left shoulder in white saying 'Don't do it.' Read this question as to [my reasons](https://stackoverflow.com/questions/59195/how-are-mocks-meant-to-be-used) - St. Justin is on your right shoulder. I believe he has also something to say:) |
79,455 | <p>Given this example:</p>
<pre><code><img class="a" />
<img />
<img class="a" />
<img class="a" id="active" />
<img class="a" />
<img class="a" />
<img />
<img class="a" />
</code></pre>
<p><em>(I've just used img tags as an example, that's not what it is in my code)</em></p>
<p>Using jQuery, how would you select the img tags with class "a" that are adjacent to #active (the middle four, in this example)?</p>
<p>You could do it fairly easily by looping over all the following and preceding elements, stopping when the filter condition fails, but I was wondering if jQuery could it natively?</p>
| [
{
"answer_id": 79471,
"author": "Xenph Yan",
"author_id": 264,
"author_profile": "https://Stackoverflow.com/users/264",
"pm_score": 2,
"selected": false,
"text": "<p>I believe looping is your best bet. But you could try, each active, and then move before and after until the condition bre... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] | Given this example:
```
<img class="a" />
<img />
<img class="a" />
<img class="a" id="active" />
<img class="a" />
<img class="a" />
<img />
<img class="a" />
```
*(I've just used img tags as an example, that's not what it is in my code)*
Using jQuery, how would you select the img tags with class "a" that are adjacent to #active (the middle four, in this example)?
You could do it fairly easily by looping over all the following and preceding elements, stopping when the filter condition fails, but I was wondering if jQuery could it natively? | Here's what I came up with in the end.
```
// here's our active element.
var $active = $('#active');
// here is the filter we'll be testing against.
var filter = "img.a";
// $all will be the final jQuery object with all the consecutively matched elements.
// start it out by populating it with the current object.
var $all = $active;
for ($curr = $active.prev(filter); $curr.length > 0; $curr = $curr.prev(filter)) {
$all = $all.add($curr);
}
for ($curr = $td.next(filter); $curr.length > 0; $curr = $curr.next(filter)) {
$all = $all.add($curr);
}
```
For a follow up question, I could see how this could easily be generalised by making it into a function which takes two arguments: an initial element, and a filter string - can anyone point me in the right direction to find out how to extend the jQuery object to add such a function?
---
**Edit**: I've since found that the each() function would do this rather well for some purposes. In my own case it doesn't work as cleanly, since I want a single jQuery object for all those elements, but here's how you could use each for a different purpose (hiding consecutive ".a" elements, in this example:)
```
$('#active')
.nextAll()
.each(hideConsecutive)
.end()
.prevAll()
.each(hideConsecutive)
;
function hideConsecutive(index, element) {
var $e = $(element);
if (!$e.is(".a")) {
return false; // this stops the each function.
} else {
$e.hide('slow');
}
}
```
--
Edit: I've put this together into a plugin now. Take a look at <http://plugins.jquery.com/project/Adjacent> if you're interested. |
79,461 | <p>I have a <code>div</code> with two images and an <code>h1</code>. All of them need to be vertically aligned within the div, next to each other. One of the images needs to be <code>absolute</code> positioned within the <code>div</code>.</p>
<p>What is the CSS needed for this to work on all common browsers?</p>
<pre class="lang-html prettyprint-override"><code><div id="header">
<img src=".." ></img>
<h1>testing...</h1>
<img src="..."></img>
</div>
</code></pre>
| [
{
"answer_id": 79513,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": -1,
"selected": false,
"text": "<pre><code><div id=\"header\" style=\"display: table-cell; vertical-align:middle;\">\n</code></pre>\n\n<p>...</... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232/"
] | I have a `div` with two images and an `h1`. All of them need to be vertically aligned within the div, next to each other. One of the images needs to be `absolute` positioned within the `div`.
What is the CSS needed for this to work on all common browsers?
```html
<div id="header">
<img src=".." ></img>
<h1>testing...</h1>
<img src="..."></img>
</div>
``` | Wow, this problem is popular. It's based on a misunderstanding in the `vertical-align` property. This excellent article explains it:
[Understanding `vertical-align`, or "How (Not) To Vertically Center Content"](http://phrogz.net/CSS/vertical-align/index.html) by Gavin Kistner.
**[“How to center in CSS”](http://howtocenterincss.com/)** is a great web tool which helps to find the necessary CSS centering attributes for different situations.
---
In a nutshell (and to prevent link rot):
* **Inline elements** (and *only* inline elements) can be vertically aligned in their context via `vertical-align: middle`. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in. [jsfiddle example](http://jsfiddle.net/jBthq/)
* For block elements, vertical alignment is harder and strongly depends on the specific situation:
+ If the inner element can have a **fixed height**, you can make its position `absolute` and specify its `height`, `margin-top` and `top` position. [jsfiddle example](http://jsfiddle.net/YFncP/2/)
+ If the centered element **consists of a single line** *and* **its parent height is fixed** you can simply set the container’s `line-height` to fill its height. This method is quite versatile in my experience. [jsfiddle example](http://jsfiddle.net/d4zGF/)
+ … there are more such special cases. |
79,466 | <p>(sorry I should have been clearer with the code the first time I posted this. Hope this makes sense)</p>
<p>File "size_specification.rb"</p>
<pre><code>class SizeSpecification
def fits?
end
end
</code></pre>
<p>File "some_module.rb"</p>
<pre><code>require 'size_specification'
module SomeModule
def self.sizes
YAML.load_file(File.dirname(__FILE__) + '/size_specification_data.yml')
end
end
</code></pre>
<p>File "size_specification_data.yml</p>
<pre><code>---
- !ruby/object:SizeSpecification
height: 250
width: 300
</code></pre>
<p>Then when I call</p>
<pre><code>SomeModule.sizes.first.fits?
</code></pre>
<p>I get an exception because "sizes" are Object's not SizeSpecification's so they don't have a "fits" function.</p>
| [
{
"answer_id": 80075,
"author": "robertpostill",
"author_id": 11219,
"author_profile": "https://Stackoverflow.com/users/11219",
"pm_score": 0,
"selected": false,
"text": "<p>On second reading I'm a little confused, you seem to want to mix the class into module, which is porbably not so a... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14796/"
] | (sorry I should have been clearer with the code the first time I posted this. Hope this makes sense)
File "size\_specification.rb"
```
class SizeSpecification
def fits?
end
end
```
File "some\_module.rb"
```
require 'size_specification'
module SomeModule
def self.sizes
YAML.load_file(File.dirname(__FILE__) + '/size_specification_data.yml')
end
end
```
File "size\_specification\_data.yml
```
---
- !ruby/object:SizeSpecification
height: 250
width: 300
```
Then when I call
```
SomeModule.sizes.first.fits?
```
I get an exception because "sizes" are Object's not SizeSpecification's so they don't have a "fits" function. | Are your settings and ruby installation ok? I created those 3 files and wrote what follows in "test.rb"
```
require 'yaml'
require "some_module"
SomeModule.sizes.first.fits?
```
Then I ran it.
```
$ ruby --version
ruby 1.8.6 (2008-06-20 patchlevel 230) [i486-linux]
$ ruby -w test.rb
$
```
No errors! |
79,474 | <p>I've set up Passenger in development (Mac OS X) and it works flawlessly. The only problem came later: now I have a custom <code>GEM_HOME</code> path and ImageMagick binaries installed in <code>"/usr/local"</code>. I can put them in one of the shell rc files that get sourced and this solves the environment variables for processes spawned from the console; but what about Passenger? The same application cannot find my gems when run this way.</p>
| [
{
"answer_id": 79615,
"author": "Brian Phillips",
"author_id": 7230,
"author_profile": "https://Stackoverflow.com/users/7230",
"pm_score": 1,
"selected": false,
"text": "<p>I've run into this issue as well. It <a href=\"http://groups.google.com/group/phusion-passenger/browse_thread/thre... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11687/"
] | I've set up Passenger in development (Mac OS X) and it works flawlessly. The only problem came later: now I have a custom `GEM_HOME` path and ImageMagick binaries installed in `"/usr/local"`. I can put them in one of the shell rc files that get sourced and this solves the environment variables for processes spawned from the console; but what about Passenger? The same application cannot find my gems when run this way. | I know of two solutions. The first (documented [here](http://www.viget.com/extend/rubyinline-in-shared-rails-environments/)) is essentially the same as manveru's—set the ENV variable directly in your code.
The second is to create a wrapper around the Ruby interpreter that Passenger uses, and is documented [here](http://blog.rayapps.com/2008/05/21/using-mod_rails-with-rails-applications-on-oracle/) (look for passenger\_with\_ruby). The gist is that you create (and point PassengerRuby in your Apache config to) /usr/bin/ruby\_with\_env, an executable file consisting of:
```
#!/bin/bash
export ENV_VAR=value
/usr/bin/ruby $*
```
Both work; the former approach is a little less hackish, I think. |
79,490 | <p>How can I get a history of uptimes for my debian box? After a reboot, I dont see an option for the uptime command to print a history of uptimes. If it matters, I would like to use these uptimes for graphing a page in php to show my webservers uptime lengths between boots.</p>
<p>Update:
Not sure if it is based on a length of time or if last gets reset on reboot but I only get the most recent boot timestamp with the last command. last -x also does not return any further info. Sounds like a script is my best bet.</p>
<p>Update:
Uptimed is the information I am looking for, not sure how to grep that info in code. Managing my own script for a db sounds like the best fit for an application.</p>
| [
{
"answer_id": 79503,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 1,
"selected": false,
"text": "<p>i dont think this information is saved between reboots.</p>\n\n<p>if shutting down properly you could run a command on ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/777/"
] | How can I get a history of uptimes for my debian box? After a reboot, I dont see an option for the uptime command to print a history of uptimes. If it matters, I would like to use these uptimes for graphing a page in php to show my webservers uptime lengths between boots.
Update:
Not sure if it is based on a length of time or if last gets reset on reboot but I only get the most recent boot timestamp with the last command. last -x also does not return any further info. Sounds like a script is my best bet.
Update:
Uptimed is the information I am looking for, not sure how to grep that info in code. Managing my own script for a db sounds like the best fit for an application. | You could create a simple script which runs uptime and dumps it to a file.
```
uptime >> uptime.log
```
Then set up a cron job for it. |
79,493 | <p>I want to use Apple's or RedHat's built-in Apache but I want to use Perl 5.10 and mod_perl. What's the least intrusive way to accomplish this? I want the advantage of free security patching for the vendor's Apache, dav, php, etc., but I care a lot about which version of Perl I use and what's in my @INC path. I don't mind compiling my own mod_perl.</p>
| [
{
"answer_id": 79696,
"author": "Ian",
"author_id": 2311,
"author_profile": "https://Stackoverflow.com/users/2311",
"pm_score": 1,
"selected": false,
"text": "<p>You'll want to look into <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_so.html\" rel=\"nofollow noreferrer\">mod_so</a></... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14783/"
] | I want to use Apple's or RedHat's built-in Apache but I want to use Perl 5.10 and mod\_perl. What's the least intrusive way to accomplish this? I want the advantage of free security patching for the vendor's Apache, dav, php, etc., but I care a lot about which version of Perl I use and what's in my @INC path. I don't mind compiling my own mod\_perl. | 1. Build your version of Perl 5.10 following any special instructions from the mod\_perl documentation. Tell Perl configurator to install in some non-standard place, like /usr/local/perl/5.10.0
2. Use the instructions to build a shared library (or dynamic, or .so) mod\_perl against your distribution's Apache, but make sure you run the Makefile.PL using *your* version of perl:
/usr/local/perl/5.10.0/bin/perl Makefile.PL APXS=/usr/bin/apxs
3. Install and configure mod\_perl like normal.
It may be helpful, after step one, to change your path so you don't accidentially get confused about which version of Perl you're using:
```
export PATH=/usr/local/perl/5.10.0/bin:$PATH
``` |
79,498 | <p>I have determined that my JSON, coming from the server, is valid (making the ajax call manually), but I would really like to use JQuery. I have also determined that the "post" URL, being sent to the server, is correct, using firebug. However, the error callback is still being triggered (parse error). I also tried datatype: text.</p>
<p>Are there other options that I should include?</p>
<pre><code>$(function() {
$("#submit").bind("click", function() {
$.ajax({
type: "post",
url: "http://myServer/cgi-bin/broker" ,
datatype: "json",
data: {'start' : start,'end' : end},
error: function(request,error){
alert(error);
},
success: function(request) {
alert(request.length);
}
}); // End ajax
}); // End bind
}); // End eventlistener
</code></pre>
| [
{
"answer_id": 79617,
"author": "Adam Weber",
"author_id": 9324,
"author_profile": "https://Stackoverflow.com/users/9324",
"pm_score": 5,
"selected": true,
"text": "<p>Here are a few suggestions I would try:</p>\n\n<p>1) the 'datatype' option you have specified should be 'dataType' (case... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] | I have determined that my JSON, coming from the server, is valid (making the ajax call manually), but I would really like to use JQuery. I have also determined that the "post" URL, being sent to the server, is correct, using firebug. However, the error callback is still being triggered (parse error). I also tried datatype: text.
Are there other options that I should include?
```
$(function() {
$("#submit").bind("click", function() {
$.ajax({
type: "post",
url: "http://myServer/cgi-bin/broker" ,
datatype: "json",
data: {'start' : start,'end' : end},
error: function(request,error){
alert(error);
},
success: function(request) {
alert(request.length);
}
}); // End ajax
}); // End bind
}); // End eventlistener
``` | Here are a few suggestions I would try:
1) the 'datatype' option you have specified should be 'dataType' (case-sensitive I believe)
2) try using the 'contentType' option as so:
```
contentType: "application/json; charset=utf-8"
```
I'm not sure how much that will help as it's used in the request to your post url, not in the response.
See this article for more info: <http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax>
(It's written for asp.net, but may be applicable)
3) Triple check the output of your post url and run the output through a JSON validator just to be absolutely sure it's valid and can be parsed into a JSON object. <http://www.jsonlint.com>
Hope some of this helps! |
79,538 | <p>I just installed Ubuntu 8.04 and I'm taking a course in Java so I figured why not install a IDE while I am installing it. So I pick my IDE of choice, Eclipse, and I make a very simple program, Hello World, to make sure everything is running smoothly. When I go to use Scanner for user input I get a very odd error:</p>
<p><b>My code:</b><pre>import java.util.Scanner;</p>
<p>class test {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.println("hi");
}
}</pre></p>
<p><b>The output:</b></p>
<pre>
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Scanner cannot be resolved to a type
Scanner cannot be resolved to a type
at test.main(test.java:5)
</pre>
| [
{
"answer_id": 79551,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 3,
"selected": true,
"text": "<p>The Scanner class is new in Java 5. I do not know what Hardy's default Java environment is, but it is not Sun's and theref... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/97220/"
] | I just installed Ubuntu 8.04 and I'm taking a course in Java so I figured why not install a IDE while I am installing it. So I pick my IDE of choice, Eclipse, and I make a very simple program, Hello World, to make sure everything is running smoothly. When I go to use Scanner for user input I get a very odd error:
**My code:**
```
import java.util.Scanner;
```
class test {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.println("hi");
}
}
**The output:**
```
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Scanner cannot be resolved to a type
Scanner cannot be resolved to a type
at test.main(test.java:5)
``` | The Scanner class is new in Java 5. I do not know what Hardy's default Java environment is, but it is not Sun's and therefore may be outdated.
I recommend installing the package sun-java6-jdk to get the most up-to-date version, then telling Eclipse to use it. |
79,602 | <p>I am writing a web application that requires user interaction via email. I'm curious if there is a best practice or recommended source for learning about processing email. I am writing my application in Python, but I'm not sure what mail server to use or how to format the message or subject line to account for automated processing. I'm also looking for guidance on processing bouncebacks. </p>
| [
{
"answer_id": 79670,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 3,
"selected": true,
"text": "<p>There are some pretty serious concerns here for how to send email automatically, and here are a few:</p>\n\n<p>Use an email... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322887/"
] | I am writing a web application that requires user interaction via email. I'm curious if there is a best practice or recommended source for learning about processing email. I am writing my application in Python, but I'm not sure what mail server to use or how to format the message or subject line to account for automated processing. I'm also looking for guidance on processing bouncebacks. | There are some pretty serious concerns here for how to send email automatically, and here are a few:
Use an email library. Python includes one called 'email'. This is your friend, it will stop you from doing anything tragically wrong. Read an example from [the Python Manual](http://docs.python.org/lib/node161.html).
Some points that will stop you from getting blocked by spam filters:
Always send from a valid email address. You must be able to send email to this address and have it received (it can go into /dev/null after it's received, but it must be possible to /deliver/ there). This will stop spam filters that do Sender Address Verification from blocking your mail.
The email address you send from on the server.sendmail(fromaddr, [toaddr]) line will be where bounces go. The From: line in the email is a totally different address, and that's where mail will go when the user hits 'Reply:'. Use this to your advantage, bounces can go to one place, while reply goes to another.
Send email to a local mail server, I recommend postfix. This local server will receive your mail and be responsible for sending it to your upstream server. Once it has been delivered to the local server, treat it as 'sent' from a programmatic point of view.
If you have a site that is on a static ip in a datacenter of good reputation, don't be afraid to simply relay the mail directly to the internet. If you're in a datacenter full of script kiddies and spammers, you will need to relay this mail via a public MTA of good reputation, hopefully you will be able to work this out without a hassle.
Don't send an email in only HTML. Always send it in Plain and HTML, or just Plain. Be nice, I use a text only email client, and you don't want to annoy me.
Verify that you're not running SPF on your email domain, or get it configured to allow your server to send the mail. Do this by doing a TXT lookup on your domain.
```
$ dig google.com txt
...snip...
;; ANSWER SECTION:
google.com. 300 IN TXT "v=spf1 include:_netblocks.google.com ~all"
```
As you can see from that result, there's an SPF record there. If you don't have SPF, there won't be a TXT record. Read more about [SPF on wikipedia](http://en.wikipedia.org/wiki/Sender_Policy_Framework).
Hope that helps. |
79,612 | <p>Looking for a <code>Linux application</code> <em>(or Firefox extension)</em> that will allow me to scrape an HTML mockup and keep the page's integrity.</p>
<p>Firefox does an almost perfect job but doesn't grab images referenced in the CSS.</p>
<p>The Scrapbook extension for Firefox gets everything, but flattens the directory structure. </p>
<p>I wouldn't terribly mind if all folders became children of the <code>index</code> page.</p>
| [
{
"answer_id": 79623,
"author": "etchasketch",
"author_id": 14640,
"author_profile": "https://Stackoverflow.com/users/14640",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried <a href=\"http://linuxreviews.org/quicktips/wget/\" rel=\"nofollow noreferrer\">wget?</a></p>\n"
},... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13320/"
] | Looking for a `Linux application` *(or Firefox extension)* that will allow me to scrape an HTML mockup and keep the page's integrity.
Firefox does an almost perfect job but doesn't grab images referenced in the CSS.
The Scrapbook extension for Firefox gets everything, but flattens the directory structure.
I wouldn't terribly mind if all folders became children of the `index` page. | See [Website Mirroring With wget](http://www.devarticles.com/c/a/Web-Services/Website-Mirroring-With-wget/1/)
```
wget --mirror –w 2 –p --HTML-extension –-convert-links http://www.yourdomain.com
``` |
79,632 | <p>I have a two tables joined with a join table - this is just pseudo code:</p>
<pre><code>Library
Book
LibraryBooks
</code></pre>
<p>What I need to do is if i have the id of a library, i want to get all the libraries that all the books that this library has are in.</p>
<p>So if i have Library 1, and Library 1 has books A and B in them, and books A and B are in Libraries 1, 2, and 3, is there an elegant (one line) way todo this in rails?</p>
<p>I was thinking:</p>
<pre><code>l = Library.find(1)
allLibraries = l.books.libraries
</code></pre>
<p>But that doesn't seem to work. Suggestions?</p>
| [
{
"answer_id": 79646,
"author": "Jim Puls",
"author_id": 6010,
"author_profile": "https://Stackoverflow.com/users/6010",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps:</p>\n\n<pre><code>l.books.map {|b| b.libraries}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>l.books.map {|b| b.lib... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | I have a two tables joined with a join table - this is just pseudo code:
```
Library
Book
LibraryBooks
```
What I need to do is if i have the id of a library, i want to get all the libraries that all the books that this library has are in.
So if i have Library 1, and Library 1 has books A and B in them, and books A and B are in Libraries 1, 2, and 3, is there an elegant (one line) way todo this in rails?
I was thinking:
```
l = Library.find(1)
allLibraries = l.books.libraries
```
But that doesn't seem to work. Suggestions? | ```
l = Library.find(:all, :include => :books)
l.books.map { |b| b.library_ids }.flatten.uniq
```
Note that `map(&:library_ids)` is slower than `map { |b| b.library_ids }` in Ruby 1.8.6, and faster in 1.9.0.
I should also mention that if you used `:joins` instead of `include` there, it would find the library and related books all in the same query speeding up the database time. `:joins` will only work however if a library has books. |
79,669 | <p>I need to copy about 40 databases from one server to another. The new databases should have new names, but all the same tables, data and indexes as the original databases. So far I've been: </p>
<p>1) creating each destination database<br>
2) using the "<a href="http://msdn.microsoft.com/en-us/library/ms140052.aspx" rel="noreferrer">Tasks->Export Data</a>" command to create and populate tables for each database individually<br>
3) rebuilding all of the indexes for each database with a SQL script </p>
<p>Only three steps per database, but I'll bet there's an easier way. Do any MS SQL Server experts out there have any advice?</p>
| [
{
"answer_id": 79673,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 2,
"selected": false,
"text": "<p>Backup -> Restore is the simplest, if not to use the replication.</p>\n"
},
{
"answer_id": 79679,
"auth... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13728/"
] | I need to copy about 40 databases from one server to another. The new databases should have new names, but all the same tables, data and indexes as the original databases. So far I've been:
1) creating each destination database
2) using the "[Tasks->Export Data](http://msdn.microsoft.com/en-us/library/ms140052.aspx)" command to create and populate tables for each database individually
3) rebuilding all of the indexes for each database with a SQL script
Only three steps per database, but I'll bet there's an easier way. Do any MS SQL Server experts out there have any advice? | Given that you're performing this on multiple databases -- you want a simple scripted solution, not a point and click solution.
This is a backup script that i keep around.
Get it working for one file and then modify it for many.
```
(on source server...)
BACKUP DATABASE Northwind
TO DISK = 'c:\Northwind.bak'
(target server...)
RESTORE FILELISTONLY
FROM DISK = 'c:\Northwind.bak'
(look at the device names... and determine where you want the mdf and
ldf files to go on this target server)
RESTORE DATABASE TestDB
FROM DISK = 'c:\Northwind.bak'
WITH MOVE 'Northwind' TO 'c:\test\testdb.mdf',
MOVE 'Northwind_log' TO 'c:\test\testdb.ldf'
GO
``` |
79,677 | <p>I need to speed up a program for the Nintendo DS which doesn't have an FPU, so I need to change floating-point math (which is emulated and slow) to fixed-point.</p>
<p>How I started was I changed floats to ints and whenever I needed to convert them, I used <strong>x>>8</strong> to convert the fixed-point variable x to the actual number and <strong>x<<8</strong> to convert to fixed-point. Soon I found out it was impossible to keep track of what needed to be converted and I also realized it would be difficult to change the precision of the numbers (8 in this case.)</p>
<p>My question is, how should I make this easier and still fast? Should I make a FixedPoint class, or just a FixedPoint8 typedef or struct with some functions/macros to convert them, or something else? Should I put something in the variable name to show it's fixed-point?</p>
| [
{
"answer_id": 79700,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 0,
"selected": false,
"text": "<p>Whichever way you decide to go (I'd lean toward a typedef and some CPP macros for converting), you will need to be careful ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
] | I need to speed up a program for the Nintendo DS which doesn't have an FPU, so I need to change floating-point math (which is emulated and slow) to fixed-point.
How I started was I changed floats to ints and whenever I needed to convert them, I used **x>>8** to convert the fixed-point variable x to the actual number and **x<<8** to convert to fixed-point. Soon I found out it was impossible to keep track of what needed to be converted and I also realized it would be difficult to change the precision of the numbers (8 in this case.)
My question is, how should I make this easier and still fast? Should I make a FixedPoint class, or just a FixedPoint8 typedef or struct with some functions/macros to convert them, or something else? Should I put something in the variable name to show it's fixed-point? | You can try my fixed point class (Latest available @ <https://github.com/eteran/cpp-utilities>)
```
// From: https://github.com/eteran/cpp-utilities/edit/master/Fixed.h
// See also: http://stackoverflow.com/questions/79677/whats-the-best-way-to-do-fixed-point-math
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Evan Teran
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef FIXED_H_
#define FIXED_H_
#include <ostream>
#include <exception>
#include <cstddef> // for size_t
#include <cstdint>
#include <type_traits>
#include <boost/operators.hpp>
namespace numeric {
template <size_t I, size_t F>
class Fixed;
namespace detail {
// helper templates to make magic with types :)
// these allow us to determine resonable types from
// a desired size, they also let us infer the next largest type
// from a type which is nice for the division op
template <size_t T>
struct type_from_size {
static const bool is_specialized = false;
typedef void value_type;
};
#if defined(__GNUC__) && defined(__x86_64__)
template <>
struct type_from_size<128> {
static const bool is_specialized = true;
static const size_t size = 128;
typedef __int128 value_type;
typedef unsigned __int128 unsigned_type;
typedef __int128 signed_type;
typedef type_from_size<256> next_size;
};
#endif
template <>
struct type_from_size<64> {
static const bool is_specialized = true;
static const size_t size = 64;
typedef int64_t value_type;
typedef uint64_t unsigned_type;
typedef int64_t signed_type;
typedef type_from_size<128> next_size;
};
template <>
struct type_from_size<32> {
static const bool is_specialized = true;
static const size_t size = 32;
typedef int32_t value_type;
typedef uint32_t unsigned_type;
typedef int32_t signed_type;
typedef type_from_size<64> next_size;
};
template <>
struct type_from_size<16> {
static const bool is_specialized = true;
static const size_t size = 16;
typedef int16_t value_type;
typedef uint16_t unsigned_type;
typedef int16_t signed_type;
typedef type_from_size<32> next_size;
};
template <>
struct type_from_size<8> {
static const bool is_specialized = true;
static const size_t size = 8;
typedef int8_t value_type;
typedef uint8_t unsigned_type;
typedef int8_t signed_type;
typedef type_from_size<16> next_size;
};
// this is to assist in adding support for non-native base
// types (for adding big-int support), this should be fine
// unless your bit-int class doesn't nicely support casting
template <class B, class N>
B next_to_base(const N& rhs) {
return static_cast<B>(rhs);
}
struct divide_by_zero : std::exception {
};
template <size_t I, size_t F>
Fixed<I,F> divide(const Fixed<I,F> &numerator, const Fixed<I,F> &denominator, Fixed<I,F> &remainder, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) {
typedef typename Fixed<I,F>::next_type next_type;
typedef typename Fixed<I,F>::base_type base_type;
static const size_t fractional_bits = Fixed<I,F>::fractional_bits;
next_type t(numerator.to_raw());
t <<= fractional_bits;
Fixed<I,F> quotient;
quotient = Fixed<I,F>::from_base(next_to_base<base_type>(t / denominator.to_raw()));
remainder = Fixed<I,F>::from_base(next_to_base<base_type>(t % denominator.to_raw()));
return quotient;
}
template <size_t I, size_t F>
Fixed<I,F> divide(Fixed<I,F> numerator, Fixed<I,F> denominator, Fixed<I,F> &remainder, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) {
// NOTE(eteran): division is broken for large types :-(
// especially when dealing with negative quantities
typedef typename Fixed<I,F>::base_type base_type;
typedef typename Fixed<I,F>::unsigned_type unsigned_type;
static const int bits = Fixed<I,F>::total_bits;
if(denominator == 0) {
throw divide_by_zero();
} else {
int sign = 0;
Fixed<I,F> quotient;
if(numerator < 0) {
sign ^= 1;
numerator = -numerator;
}
if(denominator < 0) {
sign ^= 1;
denominator = -denominator;
}
base_type n = numerator.to_raw();
base_type d = denominator.to_raw();
base_type x = 1;
base_type answer = 0;
// egyptian division algorithm
while((n >= d) && (((d >> (bits - 1)) & 1) == 0)) {
x <<= 1;
d <<= 1;
}
while(x != 0) {
if(n >= d) {
n -= d;
answer += x;
}
x >>= 1;
d >>= 1;
}
unsigned_type l1 = n;
unsigned_type l2 = denominator.to_raw();
// calculate the lower bits (needs to be unsigned)
// unfortunately for many fractions this overflows the type still :-/
const unsigned_type lo = (static_cast<unsigned_type>(n) << F) / denominator.to_raw();
quotient = Fixed<I,F>::from_base((answer << F) | lo);
remainder = n;
if(sign) {
quotient = -quotient;
}
return quotient;
}
}
// this is the usual implementation of multiplication
template <size_t I, size_t F>
void multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) {
typedef typename Fixed<I,F>::next_type next_type;
typedef typename Fixed<I,F>::base_type base_type;
static const size_t fractional_bits = Fixed<I,F>::fractional_bits;
next_type t(static_cast<next_type>(lhs.to_raw()) * static_cast<next_type>(rhs.to_raw()));
t >>= fractional_bits;
result = Fixed<I,F>::from_base(next_to_base<base_type>(t));
}
// this is the fall back version we use when we don't have a next size
// it is slightly slower, but is more robust since it doesn't
// require and upgraded type
template <size_t I, size_t F>
void multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) {
typedef typename Fixed<I,F>::base_type base_type;
static const size_t fractional_bits = Fixed<I,F>::fractional_bits;
static const size_t integer_mask = Fixed<I,F>::integer_mask;
static const size_t fractional_mask = Fixed<I,F>::fractional_mask;
// more costly but doesn't need a larger type
const base_type a_hi = (lhs.to_raw() & integer_mask) >> fractional_bits;
const base_type b_hi = (rhs.to_raw() & integer_mask) >> fractional_bits;
const base_type a_lo = (lhs.to_raw() & fractional_mask);
const base_type b_lo = (rhs.to_raw() & fractional_mask);
const base_type x1 = a_hi * b_hi;
const base_type x2 = a_hi * b_lo;
const base_type x3 = a_lo * b_hi;
const base_type x4 = a_lo * b_lo;
result = Fixed<I,F>::from_base((x1 << fractional_bits) + (x3 + x2) + (x4 >> fractional_bits));
}
}
/*
* inheriting from boost::operators enables us to be a drop in replacement for base types
* without having to specify all the different versions of operators manually
*/
template <size_t I, size_t F>
class Fixed : boost::operators<Fixed<I,F>> {
static_assert(detail::type_from_size<I + F>::is_specialized, "invalid combination of sizes");
public:
static const size_t fractional_bits = F;
static const size_t integer_bits = I;
static const size_t total_bits = I + F;
typedef detail::type_from_size<total_bits> base_type_info;
typedef typename base_type_info::value_type base_type;
typedef typename base_type_info::next_size::value_type next_type;
typedef typename base_type_info::unsigned_type unsigned_type;
public:
static const size_t base_size = base_type_info::size;
static const base_type fractional_mask = ~((~base_type(0)) << fractional_bits);
static const base_type integer_mask = ~fractional_mask;
public:
static const base_type one = base_type(1) << fractional_bits;
public: // constructors
Fixed() : data_(0) {
}
Fixed(long n) : data_(base_type(n) << fractional_bits) {
// TODO(eteran): assert in range!
}
Fixed(unsigned long n) : data_(base_type(n) << fractional_bits) {
// TODO(eteran): assert in range!
}
Fixed(int n) : data_(base_type(n) << fractional_bits) {
// TODO(eteran): assert in range!
}
Fixed(unsigned int n) : data_(base_type(n) << fractional_bits) {
// TODO(eteran): assert in range!
}
Fixed(float n) : data_(static_cast<base_type>(n * one)) {
// TODO(eteran): assert in range!
}
Fixed(double n) : data_(static_cast<base_type>(n * one)) {
// TODO(eteran): assert in range!
}
Fixed(const Fixed &o) : data_(o.data_) {
}
Fixed& operator=(const Fixed &o) {
data_ = o.data_;
return *this;
}
private:
// this makes it simpler to create a fixed point object from
// a native type without scaling
// use "Fixed::from_base" in order to perform this.
struct NoScale {};
Fixed(base_type n, const NoScale &) : data_(n) {
}
public:
static Fixed from_base(base_type n) {
return Fixed(n, NoScale());
}
public: // comparison operators
bool operator==(const Fixed &o) const {
return data_ == o.data_;
}
bool operator<(const Fixed &o) const {
return data_ < o.data_;
}
public: // unary operators
bool operator!() const {
return !data_;
}
Fixed operator~() const {
Fixed t(*this);
t.data_ = ~t.data_;
return t;
}
Fixed operator-() const {
Fixed t(*this);
t.data_ = -t.data_;
return t;
}
Fixed operator+() const {
return *this;
}
Fixed& operator++() {
data_ += one;
return *this;
}
Fixed& operator--() {
data_ -= one;
return *this;
}
public: // basic math operators
Fixed& operator+=(const Fixed &n) {
data_ += n.data_;
return *this;
}
Fixed& operator-=(const Fixed &n) {
data_ -= n.data_;
return *this;
}
Fixed& operator&=(const Fixed &n) {
data_ &= n.data_;
return *this;
}
Fixed& operator|=(const Fixed &n) {
data_ |= n.data_;
return *this;
}
Fixed& operator^=(const Fixed &n) {
data_ ^= n.data_;
return *this;
}
Fixed& operator*=(const Fixed &n) {
detail::multiply(*this, n, *this);
return *this;
}
Fixed& operator/=(const Fixed &n) {
Fixed temp;
*this = detail::divide(*this, n, temp);
return *this;
}
Fixed& operator>>=(const Fixed &n) {
data_ >>= n.to_int();
return *this;
}
Fixed& operator<<=(const Fixed &n) {
data_ <<= n.to_int();
return *this;
}
public: // conversion to basic types
int to_int() const {
return (data_ & integer_mask) >> fractional_bits;
}
unsigned int to_uint() const {
return (data_ & integer_mask) >> fractional_bits;
}
float to_float() const {
return static_cast<float>(data_) / Fixed::one;
}
double to_double() const {
return static_cast<double>(data_) / Fixed::one;
}
base_type to_raw() const {
return data_;
}
public:
void swap(Fixed &rhs) {
using std::swap;
swap(data_, rhs.data_);
}
public:
base_type data_;
};
// if we have the same fractional portion, but differing integer portions, we trivially upgrade the smaller type
template <size_t I1, size_t I2, size_t F>
typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator+(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {
typedef typename std::conditional<
I1 >= I2,
Fixed<I1,F>,
Fixed<I2,F>
>::type T;
const T l = T::from_base(lhs.to_raw());
const T r = T::from_base(rhs.to_raw());
return l + r;
}
template <size_t I1, size_t I2, size_t F>
typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator-(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {
typedef typename std::conditional<
I1 >= I2,
Fixed<I1,F>,
Fixed<I2,F>
>::type T;
const T l = T::from_base(lhs.to_raw());
const T r = T::from_base(rhs.to_raw());
return l - r;
}
template <size_t I1, size_t I2, size_t F>
typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator*(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {
typedef typename std::conditional<
I1 >= I2,
Fixed<I1,F>,
Fixed<I2,F>
>::type T;
const T l = T::from_base(lhs.to_raw());
const T r = T::from_base(rhs.to_raw());
return l * r;
}
template <size_t I1, size_t I2, size_t F>
typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator/(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {
typedef typename std::conditional<
I1 >= I2,
Fixed<I1,F>,
Fixed<I2,F>
>::type T;
const T l = T::from_base(lhs.to_raw());
const T r = T::from_base(rhs.to_raw());
return l / r;
}
template <size_t I, size_t F>
std::ostream &operator<<(std::ostream &os, const Fixed<I,F> &f) {
os << f.to_double();
return os;
}
template <size_t I, size_t F>
const size_t Fixed<I,F>::fractional_bits;
template <size_t I, size_t F>
const size_t Fixed<I,F>::integer_bits;
template <size_t I, size_t F>
const size_t Fixed<I,F>::total_bits;
}
#endif
```
It is designed to be a near drop in replacement for floats/doubles and has a choose-able precision. It does make use of boost to add all the necessary math operator overloads, so you will need that as well (I believe for this it is just a header dependency, not a library dependency).
BTW, common usage could be something like this:
```
using namespace numeric;
typedef Fixed<16, 16> fixed;
fixed f;
```
The only real rule is that the number have to add up to a native size of your system such as 8, 16, 32, 64. |
79,688 | <p>What's the best way to calculate percentile rankings (e.g. the 90th percentile or the median score) in MSSQL 2005?</p>
<p>I'd like to be able to select the 25th, median, and 75th percentiles for a single column of scores (preferably in a single record so I can combine with average, max, and min). So for example, table output of the results might be:</p>
<pre><code>Group MinScore MaxScore AvgScore pct25 median pct75
----- -------- -------- -------- ----- ------ -----
T1 52 96 74 68 76 84
T2 48 98 74 68 75 85
</code></pre>
| [
{
"answer_id": 79758,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>i'd probably use a the sql server 2005 </p>\n\n<blockquote>\n <p>row_number() over (order by score ) / (select count(*) fr... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] | What's the best way to calculate percentile rankings (e.g. the 90th percentile or the median score) in MSSQL 2005?
I'd like to be able to select the 25th, median, and 75th percentiles for a single column of scores (preferably in a single record so I can combine with average, max, and min). So for example, table output of the results might be:
```
Group MinScore MaxScore AvgScore pct25 median pct75
----- -------- -------- -------- ----- ------ -----
T1 52 96 74 68 76 84
T2 48 98 74 68 75 85
``` | I would think that this would be the simplest solution:
```
SELECT TOP N PERCENT FROM TheTable ORDER BY TheScore DESC
```
Where N = (100 - desired percentile). So if you wanted all rows in the 90th percentile, you'd select the top 10%.
I'm not sure what you mean by "preferably in a single record". Do you mean calculate which percentile a given score for a single record would fall into? e.g. do you want to be able to make statements like "your score is 83, which puts you in the 91st percentile." ?
EDIT: OK, I thought some more about your question and came up with this interpretation. Are you asking how to calculate the cutoff score for a particular percentile? e.g. something like this: to be in the 90th percentile you must have a score greater than 78.
If so, this query works. I dislike sub-queries though, so depending on what it was for, I'd probably try to find a more elegant solution. It does, however, return a single record with a single score.
```
-- Find the minimum score for all scores in the 90th percentile
SELECT Min(subq.TheScore) FROM
(SELECT TOP 10 PERCENT TheScore FROM TheTable
ORDER BY TheScore DESC) AS subq
``` |
79,693 | <p>How do you get all the classes in a namespace through reflection in C#?</p>
| [
{
"answer_id": 79706,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 5,
"selected": false,
"text": "<pre><code>using System.Reflection;\nusing System.Collections.Generic;\n//...\n\nstatic List<string> GetClasses(str... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How do you get all the classes in a namespace through reflection in C#? | Following code prints names of classes in specified `namespace` defined in current assembly.
As other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.
```
string nspace = "...";
var q = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.IsClass && t.Namespace == nspace
select t;
q.ToList().ForEach(t => Console.WriteLine(t.Name));
``` |
79,709 | <p>I have a function inside a loop inside a function. The inner function acquires and stores a large vector of data in memory (as a global variable... I'm using "R" which is like "S-Plus"). The loop loops through a long list of data to be acquired. The outer function starts the process and passes in the list of datasets to be acquired.</p>
<pre><code>for (dataset in list_of_datasets) {
for (datachunk in dataset) {
<process datachunk>
<store result? as vector? where?>
}
}
</code></pre>
<p>I programmed the inner function to store each dataset before moving to the next, so all the work of the outer function occurs as side effects on global variables... a big no-no. Is this better or worse than collecting and returning a giant, memory-hogging vector of vectors? Is there a superior third approach?</p>
<p>Would the answer change if I were storing the data vectors in a database rather than in memory? Ideally, I'd like to be able to terminate the function (or have it fail due to network timeouts) without losing all the information processed prior to termination.</p>
| [
{
"answer_id": 79741,
"author": "Jeffrey",
"author_id": 3259,
"author_profile": "https://Stackoverflow.com/users/3259",
"pm_score": -1,
"selected": false,
"text": "<p>It's tough to say definitively without knowing the language/compiler used. However, if you can simply pass a pointer/ref... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a function inside a loop inside a function. The inner function acquires and stores a large vector of data in memory (as a global variable... I'm using "R" which is like "S-Plus"). The loop loops through a long list of data to be acquired. The outer function starts the process and passes in the list of datasets to be acquired.
```
for (dataset in list_of_datasets) {
for (datachunk in dataset) {
<process datachunk>
<store result? as vector? where?>
}
}
```
I programmed the inner function to store each dataset before moving to the next, so all the work of the outer function occurs as side effects on global variables... a big no-no. Is this better or worse than collecting and returning a giant, memory-hogging vector of vectors? Is there a superior third approach?
Would the answer change if I were storing the data vectors in a database rather than in memory? Ideally, I'd like to be able to terminate the function (or have it fail due to network timeouts) without losing all the information processed prior to termination. | use variables in the outer function instead of global variables. This gets you the best of both approaches: you're not mutating global state, and you're not copying a big wad of data. If you have to exit early, just return the partial results.
(See the "Scope" section in the R manual: <http://cran.r-project.org/doc/manuals/R-intro.html#Scope>) |
79,737 | <p>This question may be too product specifc but I'd like to know if anyone is exporting bug track data from HP Quality Center.</p>
<p>HP Quality Center (QC) has an old school COM API but I'd rather use a web service or maybe even screen scraper to export the data into an excel spreadsheet.</p>
<p>In any case, what's the best way to export bug tracking data from hosted HP Quality Center?</p>
| [
{
"answer_id": 80813,
"author": "granth",
"author_id": 11210,
"author_profile": "https://Stackoverflow.com/users/11210",
"pm_score": 4,
"selected": true,
"text": "<p>You can use this QC API Code to modify bugs/requirements.</p>\n\n<pre><code>TDAPIOLELib.TDConnection connection = new TDAP... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3048/"
] | This question may be too product specifc but I'd like to know if anyone is exporting bug track data from HP Quality Center.
HP Quality Center (QC) has an old school COM API but I'd rather use a web service or maybe even screen scraper to export the data into an excel spreadsheet.
In any case, what's the best way to export bug tracking data from hosted HP Quality Center? | You can use this QC API Code to modify bugs/requirements.
```
TDAPIOLELib.TDConnection connection = new TDAPIOLELib.TDConnection();
connection.InitConnectionEx("http://SERVER:8080/qcbin");
connection.Login("USERNAME", "PASSWORD");
connection.Connect("QCDOMAIN", "QCPROJECT");
TDAPIOLELib.BugFactory bugFactory = connection.BugFactory as TDAPIOLELib.BugFactory;
TDAPIOLELib.List bugList = bugFactory.NewList("");
foreach (TDAPIOLELib.Bug bug in bugList)
{
// View / Modify the properties
// bug.ID, bug.Name, etc.
// Save them when done
// bug.Post();
}
``` |
79,745 | <p>We have an application which needs to use Direct3D. Specifically, it needs at least DirectX 9.0c version 4.09.0000.0904. While this should be present on all newer XP machines it might not be installed on older XP machines. How can I programmatically (using C++) determine if it is installed? I want to be able to give an information message to the user that Direct3D will not be available.</p>
| [
{
"answer_id": 79801,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 0,
"selected": false,
"text": "<p>According to the DirectX 9.0 SDK (summer 2004) documentation, see the GetDXVer SDK sample at \\Samples\\Multimedia\\DXMi... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5022/"
] | We have an application which needs to use Direct3D. Specifically, it needs at least DirectX 9.0c version 4.09.0000.0904. While this should be present on all newer XP machines it might not be installed on older XP machines. How can I programmatically (using C++) determine if it is installed? I want to be able to give an information message to the user that Direct3D will not be available. | Call DirectXSetupGetVersion: <http://msdn.microsoft.com/en-us/library/microsoft.directx_sdk.directsetup.directxsetupgetversion>
You'll need to include dsetup.h
Here's the sample code from the site:
```
DWORD dwVersion;
DWORD dwRevision;
if (DirectXSetupGetVersion(&dwVersion, &dwRevision))
{
printf("DirectX version is %d.%d.%d.%d\n",
HIWORD(dwVersion), LOWORD(dwVersion),
HIWORD(dwRevision), LOWORD(dwRevision));
}
``` |
79,754 | <p>No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.</p>
<pre><code>IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
</code></pre>
| [
{
"answer_id": 79826,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 3,
"selected": false,
"text": "<p>Don't try to run <code>unittest.main()</code> from IDLE. It's trying to access <code>sys.argv</code>, and it's getting the a... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176/"
] | No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.
```
IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
``` | Your example is exiting on my install too. I can make it execute the tests and stay within Python by changing
```
unittest.main()
```
to
```
unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))
```
More information is available [here](http://docs.python.org/library/unittest.html#basic-example) in the Python Library Reference. |
79,774 | <p>Ok - a bit of a mouthful. So the problem I have is this - I need to store a Date for expiry where <em>only</em> the date part is required and I don't want any timezone conversion. So for example if I have an expiry set to "08 March 2008" I want that value to be returned to any client - no matter what their timezone is.
The problem with remoting it as a DateTime is that it gets stored/sent as "08 March 2008 00:00", which means for clients connecting from any timezone West of me it gets converted and therefore flipped to "07 March 2008"
Any suggestions for cleanly handling this scenario ? Obviously sending it as a string would work. anything else ?
thanks,
Ian</p>
| [
{
"answer_id": 79792,
"author": "Yitzchok",
"author_id": 5723,
"author_profile": "https://Stackoverflow.com/users/5723",
"pm_score": 0,
"selected": false,
"text": "<p>You can send it as UTC Time</p>\n\n<p>dateTime1.ToUniversalTime()</p>\n"
},
{
"answer_id": 79810,
"author": "... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14871/"
] | Ok - a bit of a mouthful. So the problem I have is this - I need to store a Date for expiry where *only* the date part is required and I don't want any timezone conversion. So for example if I have an expiry set to "08 March 2008" I want that value to be returned to any client - no matter what their timezone is.
The problem with remoting it as a DateTime is that it gets stored/sent as "08 March 2008 00:00", which means for clients connecting from any timezone West of me it gets converted and therefore flipped to "07 March 2008"
Any suggestions for cleanly handling this scenario ? Obviously sending it as a string would work. anything else ?
thanks,
Ian | You could create a struct Date that provides access to the details you want/need, like:
```
public struct Date
{
public int Month; //or string instead of int
public int Day;
public int Year;
}
```
This is lightweight, flexible and gives you full control. |
79,780 | <p>I've had a new found interest in building a small, efficient web server in C and have had some trouble parsing POST methods from the HTTP Header. Would anyone have any advice as to how to handle retrieving the name/value pairs from the "posted" data?</p>
<pre><code>POST /test HTTP/1.1
Host: test-domain.com:7017
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://test-domain.com:7017/index.html
Cookie: __utma=43166241.217413299.1220726314.1221171690.1221200181.16; __utmz=43166241.1220726314.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
Cache-Control: max-age=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 25
field1=asfd&field2=a3f3f3
// ^-this
</code></pre>
<p>I see no tangible way to retrieve the bottom line as a whole and ensure that it works every time. I'm not a fan of hard-coding in anything.</p>
| [
{
"answer_id": 79812,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 5,
"selected": true,
"text": "<p>You can retrieve the name/value pairs by searching for newline newline or more specifically \\r\\n\\r\\n (after this... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14877/"
] | I've had a new found interest in building a small, efficient web server in C and have had some trouble parsing POST methods from the HTTP Header. Would anyone have any advice as to how to handle retrieving the name/value pairs from the "posted" data?
```
POST /test HTTP/1.1
Host: test-domain.com:7017
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://test-domain.com:7017/index.html
Cookie: __utma=43166241.217413299.1220726314.1221171690.1221200181.16; __utmz=43166241.1220726314.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
Cache-Control: max-age=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 25
field1=asfd&field2=a3f3f3
// ^-this
```
I see no tangible way to retrieve the bottom line as a whole and ensure that it works every time. I'm not a fan of hard-coding in anything. | You can retrieve the name/value pairs by searching for newline newline or more specifically \r\n\r\n (after this, the body of the message will start).
Then you can simply split the list by the &, and then split each of those returned strings between the = for name/value pairs.
See the [HTTP 1.1 RFC](https://www.rfc-editor.org/rfc/rfc2616). |
79,789 | <p>I have a list of timesheet entries that show a start and stop time. This is sitting in a MySQL database. I need to create bar charts based on this data with the 24 hours of the day along the bottom and the amount of man-hours worked for each hour of the day.</p>
<p>For example, if Alice worked a job from 15:30 to 19:30 and Bob worked from 12:15 to 17:00, the chart would look like this:</p>
<p><a href="https://i.stack.imgur.com/HHrs0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HHrs0.png" alt="Example Chart"></a></p>
<p>I have a WTFey solution right now that involves a spreadsheet going out to column DY or something like that. The needed resolution is 15-minute intervals.</p>
<p>I'm assuming this is something best done in the database then exported for chart creation. Let me know if I'm missing any details. Thanks.</p>
| [
{
"answer_id": 80125,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I came up with a pseudocode solution, hope it helps.</p>\n\n<pre><code>create an array named timetable with 24 entries\ninit... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9867/"
] | I have a list of timesheet entries that show a start and stop time. This is sitting in a MySQL database. I need to create bar charts based on this data with the 24 hours of the day along the bottom and the amount of man-hours worked for each hour of the day.
For example, if Alice worked a job from 15:30 to 19:30 and Bob worked from 12:15 to 17:00, the chart would look like this:
[](https://i.stack.imgur.com/HHrs0.png)
I have a WTFey solution right now that involves a spreadsheet going out to column DY or something like that. The needed resolution is 15-minute intervals.
I'm assuming this is something best done in the database then exported for chart creation. Let me know if I'm missing any details. Thanks. | Create a table with just time in it from midnight to midnight containing each minute of the day. In the data warehouse world we would call this a time dimension. Here's an example:
```
TIME_DIM
-id
-time_of_day
-interval_15
-interval_30
```
an example of the data in the table would be
```
id time_of_day interval_15 interval_30
1 00:00 00:00 00:00
...
30 00:23 00:15 00:00
...
100 05:44 05:30 05:30
```
Then all you have to do is join your table to the time dimension and then group by interval\_15. For example:
```
SELECT b.interval_15, count(*)
FROM my_data_table a
INNER JOIN time_dim b ON a.time_field = b.time
WHERE a.date_field = now()
GROUP BY b.interval_15
``` |
79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/" rel="noreferrer">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| [
{
"answer_id": 79808,
"author": "Chuck Callebs",
"author_id": 14877,
"author_profile": "https://Stackoverflow.com/users/14877",
"pm_score": 5,
"selected": false,
"text": "<pre><code>def local_to_utc(t):\n secs = time.mktime(t)\n return time.gmtime(secs)\n\ndef utc_to_local(t):\n ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] | How do I convert a datetime *string in local time* to a *string in UTC time*?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
**Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with the equivalent `UTC` time: `2008-09-17 04:02:00`.
Also, from <http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time. | Thanks @rofly, the full conversion from string to string is as follows:
```
import time
time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00",
"%Y-%m-%d %H:%M:%S"))))
```
My summary of the `time`/`calendar` functions:
`time.strptime`
string --> tuple (no timezone applied, so matches string)
`time.mktime`
local time tuple --> seconds since epoch (always local time)
`time.gmtime`
seconds since epoch --> tuple in UTC
and
`calendar.timegm`
tuple in UTC --> seconds since epoch
`time.localtime`
seconds since epoch --> tuple in local timezone |
79,816 | <p>I'd like a short smallest possible javascript routine that when a mousedown occurs on a button it first responds just like a mouseclick and then if the user keeps the button pressed it responds as if the user was continously sending mouseclicks and after a while with the button held down acts as if the user was accelerating their mouseclicks...basically think of it like a keypress repeat with acceleration in time.<br>
i.e. user holds down mouse button (x=call function) - x___x___x___x__x__x_x_x_x_xxxxxxx</p>
| [
{
"answer_id": 79830,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 2,
"selected": false,
"text": "<p>When the button is pressed, call <code>window.setTimeout</code> with your intended time and the function <code>x</code>, ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14907/"
] | I'd like a short smallest possible javascript routine that when a mousedown occurs on a button it first responds just like a mouseclick and then if the user keeps the button pressed it responds as if the user was continously sending mouseclicks and after a while with the button held down acts as if the user was accelerating their mouseclicks...basically think of it like a keypress repeat with acceleration in time.
i.e. user holds down mouse button (x=call function) - x\_\_\_x\_\_\_x\_\_\_x\_\_x\_\_x\_x\_x\_x\_xxxxxxx | ```
function holdit(btn, action, start, speedup) {
var t;
var repeat = function () {
action();
t = setTimeout(repeat, start);
start = start / speedup;
}
btn.mousedown = function() {
repeat();
}
btn.mouseup = function () {
clearTimeout(t);
}
};
/* to use */
holdit(btn, function () { }, 1000, 2); /* x..1000ms..x..500ms..x..250ms..x */
``` |
79,843 | <p>The situation is this:</p>
<ul>
<li>You have a Hibernate context with an
object graph that has some lazy
loading defined. </li>
<li>You want to use
the Hibernate objects in your UI as
is without having to copy the data
somewhere. </li>
<li>There are different UI
contexts that require different
amounts of data. </li>
<li>The data is too
big to just eager load the whole
graph each time.</li>
</ul>
<p>What is the best means to load all the appropriate objects in the object graph in a configurable way so that they can be accessed without having to go back to the database to load more data?</p>
<p>Any help.</p>
| [
{
"answer_id": 79933,
"author": "sirrocco",
"author_id": 5246,
"author_profile": "https://Stackoverflow.com/users/5246",
"pm_score": 3,
"selected": true,
"text": "<p>Let's say you have the Client and at one point you have to something with his Orders and maybe he has a Bonus for his Orde... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14893/"
] | The situation is this:
* You have a Hibernate context with an
object graph that has some lazy
loading defined.
* You want to use
the Hibernate objects in your UI as
is without having to copy the data
somewhere.
* There are different UI
contexts that require different
amounts of data.
* The data is too
big to just eager load the whole
graph each time.
What is the best means to load all the appropriate objects in the object graph in a configurable way so that they can be accessed without having to go back to the database to load more data?
Any help. | Let's say you have the Client and at one point you have to something with his Orders and maybe he has a Bonus for his Orders.
Then I would define a Repository with a fluent interface that will allow me to say something like :
```
new ClientRepo().LoadClientBy(id)
.WithOrders()
.WithBonus()
.OrderByName();
```
And there you have the client with everything you need. It's preferably that you know in advance what you will need for the current operation. This way you can avoid unwanted trips to the database.(new devs in your team will usually do this - call a property and not be aware of the fact that it's actually a call to the DB) |
79,880 | <p>I'm looking for a variation on the <code>#save</code> method that will only save
attributes that do not have errors attached to them.
So a model can be updated without being valid overall, and this will
still prevent saving invalid data to the database.</p>
<p>By "valid attributes", I mean those attributes that give nil when calling @model_instance.errors.on(:attribute)</p>
<p>Anyone have an idea of how to accomplish this?</p>
<p>So far, I have the following:</p>
<pre><code>def save_valid_attributes
valid?
update_atrtibutes attributes.inject({}){|k, v, m| m[k] = v unless errors_on(k.to_sym); m}
end
</code></pre>
<p>This works if there's no processing done on assignment, which in my case there is.
For example, I have a database column "start_date", and two methods defined:</p>
<pre><code>def nice_start_date=(startdate)
self.start_date = Chronic.parse(startdate) || startdate
end
def nice_start_date
self.start_date.to_s
end
</code></pre>
<p>These two methods allow me to properly parse the user inputted dates using Chronic before saving. So, second way of doing this, one attribute at a time:</p>
<pre><code>def save_valid_attributes(attrib)
valid?
attrib.each{|(k,v)| send("${k}=", v); save; reload)
end
</code></pre>
<p>The model needs to be reloaded each time since, if one of the dates is invalid and doesn't save, it will prevent all further attributes from saving.</p>
<p>Is there a better way to do this? I'm sure this isn't an uncommon problem in the Rails world, I just can't seem to find anything in the Google universe of knowledge.</p>
| [
{
"answer_id": 79900,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 3,
"selected": true,
"text": "<p>Since OpenSSL is Apache-licensed (i.e. BSD-style), you can simply distribute it as a DLL along with your application. (May... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14843/"
] | I'm looking for a variation on the `#save` method that will only save
attributes that do not have errors attached to them.
So a model can be updated without being valid overall, and this will
still prevent saving invalid data to the database.
By "valid attributes", I mean those attributes that give nil when calling @model\_instance.errors.on(:attribute)
Anyone have an idea of how to accomplish this?
So far, I have the following:
```
def save_valid_attributes
valid?
update_atrtibutes attributes.inject({}){|k, v, m| m[k] = v unless errors_on(k.to_sym); m}
end
```
This works if there's no processing done on assignment, which in my case there is.
For example, I have a database column "start\_date", and two methods defined:
```
def nice_start_date=(startdate)
self.start_date = Chronic.parse(startdate) || startdate
end
def nice_start_date
self.start_date.to_s
end
```
These two methods allow me to properly parse the user inputted dates using Chronic before saving. So, second way of doing this, one attribute at a time:
```
def save_valid_attributes(attrib)
valid?
attrib.each{|(k,v)| send("${k}=", v); save; reload)
end
```
The model needs to be reloaded each time since, if one of the dates is invalid and doesn't save, it will prevent all further attributes from saving.
Is there a better way to do this? I'm sure this isn't an uncommon problem in the Rails world, I just can't seem to find anything in the Google universe of knowledge. | Since OpenSSL is Apache-licensed (i.e. BSD-style), you can simply distribute it as a DLL along with your application. (Maybe build it yourself to have only the features you need and all in a single DLL.) Then use p/invoke calls to talk with this DLL.
(Maybe you can even link the native code straight into your .NET executable? Not sure about that.) |
79,935 | <p>Is there an equivalent to Java's Robot class (java.awt.Robot) for Perl?</p>
| [
{
"answer_id": 79976,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 1,
"selected": false,
"text": "<p>There is on Linux/Unix:</p>\n\n<p><a href=\"http://sourceforge.net/projects/x11guitest\" rel=\"nofollow noreferrer\"><a... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14948/"
] | Is there an equivalent to Java's Robot class (java.awt.Robot) for Perl? | Alternatively, you can surely use the [WWW::Mechanize](http://search.cpan.org/~petdance/WWW-Mechanize-1.34/lib/WWW/Mechanize.pm) module to create an agent as we do here at work. We have a tool called AppMon that is really just a dramatized wrapper around Mechanize.
The Mechanize module allows you to use scripts that look a lot like this:
```
use WWW::Mechanize;
my $Agent = WWW::Mechanize->new(cookie_jar => {});
$Agent->get("http://www.google.com/search?q=stack+overflow+mechanize");
print "Found Mechanize" $Agent->content =~ /WWW::Mechanize/;
```
and will result in "Found Mechanize" being output. This is a very simple script, but rest assured you can interact with forms quite well.
You can also move to Ruby and use Watir, or Selenium as another alternative, albeit not as interesting (in terms of coding) or automate-able. Selenium has a firefox extension that is quite useful for creating the selenium scripts and can change them between the various languages that it supports, which is pretty extensive in terms of automation.
Update - Nov 2016
-----------------
Although I haven't had much of an opportunity to play with it, there are also webdriver packages for most languages, and Perl is no different.
[Selenium::Remote::Driver](http://search.cpan.org/~aivaturi/Selenium-Remote-Driver-0.15/lib/Selenium/Remote/Driver.pm) |
79,939 | <p>I have the following (pretty standard) table structure:</p>
<pre><code>Post <-> PostTag <-> Tag
</code></pre>
<p>Suppose I have the following records:</p>
<pre><code>PostID Title
1, 'Foo'
2, 'Bar'
3, 'Baz'
TagID Name
1, 'Foo'
2, 'Bar'
PostID TagID
1 1
1 2
2 2
</code></pre>
<p>In other words, the first post has two tags, the second has one and the third one doesn't have any.</p>
<p><strong>I'd like to load all posts and it's tags in one query</strong> but haven't been able to find the right combination of operators. I've been able to load either <em>posts with tags only</em> or <em>repeated posts when more than one tag</em>.</p>
<p>Given the database above, <strong>I'd like to receive three posts and their tags (if any) in a collection property of the Post objects</strong>. Is it possible at all?</p>
<p>Thanks</p>
| [
{
"answer_id": 79979,
"author": "sirrocco",
"author_id": 5246,
"author_profile": "https://Stackoverflow.com/users/5246",
"pm_score": 0,
"selected": false,
"text": "<p>I've answered this in another post : <a href=\"https://stackoverflow.com/questions/50169/optimizing-a-linq-to-sql-query#5... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have the following (pretty standard) table structure:
```
Post <-> PostTag <-> Tag
```
Suppose I have the following records:
```
PostID Title
1, 'Foo'
2, 'Bar'
3, 'Baz'
TagID Name
1, 'Foo'
2, 'Bar'
PostID TagID
1 1
1 2
2 2
```
In other words, the first post has two tags, the second has one and the third one doesn't have any.
**I'd like to load all posts and it's tags in one query** but haven't been able to find the right combination of operators. I've been able to load either *posts with tags only* or *repeated posts when more than one tag*.
Given the database above, **I'd like to receive three posts and their tags (if any) in a collection property of the Post objects**. Is it possible at all?
Thanks | Yay! It worked.
If anyone is having the same problem here's what I did:
```
public IList<Post> GetPosts(int page, int record)
{
var options = new DataLoadOptions();
options.LoadWith<Post>(p => p.PostTags);
options.LoadWith<PostTag>(pt => pt.Tag);
using (var db = new DatabaseDataContext(m_connectionString))
{
var publishDateGmt = (from p in db.Posts
where p.Status != PostStatus.Hidden
orderby p.PublishDateGmt descending
select p.PublishDateGmt)
.Skip(page * record)
.Take(record)
.ToList()
.Last();
db.LoadOptions = options;
return (from p in db.Posts
where p.Status != PostStatus.Closed
&& p.PublishDateGmt >= publishDateGmt
orderby p.PublishDateGmt descending
select p)
.Skip(page * record)
.ToList();
}
}
```
This executes only two queries and loads all tags for each post.
The idea is to get some value to limit the query at the last post that we need (in this case the PublishDateGmt column will suffice) and then limit the second query with that value instead of Take().
Thanks for your help sirrocco. |
79,960 | <p>I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last <i>word</i> before 200 chars.</p>
| [
{
"answer_id": 79986,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 9,
"selected": true,
"text": "<p>By using the <a href=\"http://www.php.net/wordwrap\" rel=\"noreferrer\">wordwrap</a> function. It splits the texts in ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14956/"
] | I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last *word* before 200 chars. | By using the [wordwrap](http://www.php.net/wordwrap) function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:
```
substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));
```
One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:
```
if (strlen($string) > $your_desired_width)
{
$string = wordwrap($string, $your_desired_width);
$string = substr($string, 0, strpos($string, "\n"));
}
```
---
The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:
```
function tokenTruncate($string, $your_desired_width) {
$parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
$parts_count = count($parts);
$length = 0;
$last_part = 0;
for (; $last_part < $parts_count; ++$last_part) {
$length += strlen($parts[$last_part]);
if ($length > $your_desired_width) { break; }
}
return implode(array_slice($parts, 0, $last_part));
}
```
Also, here is the PHPUnit testclass used to test the implementation:
```
class TokenTruncateTest extends PHPUnit_Framework_TestCase {
public function testBasic() {
$this->assertEquals("1 3 5 7 9 ",
tokenTruncate("1 3 5 7 9 11 14", 10));
}
public function testEmptyString() {
$this->assertEquals("",
tokenTruncate("", 10));
}
public function testShortString() {
$this->assertEquals("1 3",
tokenTruncate("1 3", 10));
}
public function testStringTooLong() {
$this->assertEquals("",
tokenTruncate("toooooooooooolooooong", 10));
}
public function testContainingNewline() {
$this->assertEquals("1 3\n5 7 9 ",
tokenTruncate("1 3\n5 7 9 11 14", 10));
}
}
```
**EDIT :**
==========
Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the REGEX to handle it:
`$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);` |
79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this', 'is', 'a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| [
{
"answer_id": 79985,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 10,
"selected": true,
"text": "<p>You want <code>split</code>, from the built-in <a href=\"https://docs.python.org/library/shlex.html\" rel=\"noreferrer\"><... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
] | I have a string which is like this:
```
this is "a test"
```
I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:
```
['this', 'is', 'a test']
```
PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen. | You want `split`, from the built-in [`shlex`](https://docs.python.org/library/shlex.html) module.
```
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
```
This should do exactly what you want.
If you want to preserve the quotation marks, then you can pass the `posix=False` kwarg.
```
>>> shlex.split('this is "a test"', posix=False)
['this', 'is', '"a test"']
``` |
79,992 | <p>Ideally the reader has upgraded a native C++ program to Visual Studio 2008, which contains an OpenClipboard() block. Why not try setting a breakpoint just after getting a successful return-code from OpenClipboard() and step through your code. According to the Internet it may work on your system, but of course, not on mine, thanks for trying. </p>
<p>Googling on e.g. (( OpenClipboard 1418 vc6 )) finds articles like "GetClipboardData fails in debugger" and "No Error in VC++6 but Error in VC++ 2005". Pragmatically for-the-moment, problem solved - I simply cannot set breakpoints within such code, I need to squirrel information and set the breakpoint after the clipboard operations are done. Error 1418 is "Thread does not have a clipboard open" but it works fine as long as you don't step with VS.NET, or like I say if you keep breakpoints outside of the clipboard-open-close-block.<p>
I would feel better knowing what the exact issue is with the VS.NET debugger.<p>
Being a C++ person I am only dimly aware that you are not supposed to think in terms of threads when doing dot-Net. Anyway I did not find a guru-quality explanation of what's really going on, whether in-fact the problem is that the dot-Net debugger is subtly interfering with the thread-information somehow, when you single-step thru native C++ code. <P></p>
<p>System-wise: about a year old, two dual-core Xeon's, 4 CPU's according to XP-pro.
I had just finished debugging the code by single-stepping thru it in vc6 under XP-SP2-32-bit. So I know the code was pretty-much-fine under vc6. However when I tested with a 10-megabyte CF_TEXT I got exceptions. I thought to try debugging under the nicer exception model of XP-x64.<p>
Recompiled with visual-studio-2008, I could not get the code to single-step at all. OpenClipboard worked, but EnumClipboardFormats() did not work, nothing worked when single-stepped. However, when I set the breakpoint below the complete block of code, everything worked fine. And <em>YES</em> vc2008 made a pinpoint diagnostic 'stack frame corruption around szBuf. There is a lot to like about vc2008. It would be nice if this were somehow merely a clipboard problem - without knowing that I would feel compelled to worry about stepping thru ANYTHING, whether thread-context-issues might be due to the dot-Net-debugger.</p>
| [
{
"answer_id": 79985,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 10,
"selected": true,
"text": "<p>You want <code>split</code>, from the built-in <a href=\"https://docs.python.org/library/shlex.html\" rel=\"noreferrer\"><... | 2008/09/17 | [
"https://Stackoverflow.com/questions/79992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10972/"
] | Ideally the reader has upgraded a native C++ program to Visual Studio 2008, which contains an OpenClipboard() block. Why not try setting a breakpoint just after getting a successful return-code from OpenClipboard() and step through your code. According to the Internet it may work on your system, but of course, not on mine, thanks for trying.
Googling on e.g. (( OpenClipboard 1418 vc6 )) finds articles like "GetClipboardData fails in debugger" and "No Error in VC++6 but Error in VC++ 2005". Pragmatically for-the-moment, problem solved - I simply cannot set breakpoints within such code, I need to squirrel information and set the breakpoint after the clipboard operations are done. Error 1418 is "Thread does not have a clipboard open" but it works fine as long as you don't step with VS.NET, or like I say if you keep breakpoints outside of the clipboard-open-close-block.
I would feel better knowing what the exact issue is with the VS.NET debugger.
Being a C++ person I am only dimly aware that you are not supposed to think in terms of threads when doing dot-Net. Anyway I did not find a guru-quality explanation of what's really going on, whether in-fact the problem is that the dot-Net debugger is subtly interfering with the thread-information somehow, when you single-step thru native C++ code.
System-wise: about a year old, two dual-core Xeon's, 4 CPU's according to XP-pro.
I had just finished debugging the code by single-stepping thru it in vc6 under XP-SP2-32-bit. So I know the code was pretty-much-fine under vc6. However when I tested with a 10-megabyte CF\_TEXT I got exceptions. I thought to try debugging under the nicer exception model of XP-x64.
Recompiled with visual-studio-2008, I could not get the code to single-step at all. OpenClipboard worked, but EnumClipboardFormats() did not work, nothing worked when single-stepped. However, when I set the breakpoint below the complete block of code, everything worked fine. And *YES* vc2008 made a pinpoint diagnostic 'stack frame corruption around szBuf. There is a lot to like about vc2008. It would be nice if this were somehow merely a clipboard problem - without knowing that I would feel compelled to worry about stepping thru ANYTHING, whether thread-context-issues might be due to the dot-Net-debugger. | You want `split`, from the built-in [`shlex`](https://docs.python.org/library/shlex.html) module.
```
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
```
This should do exactly what you want.
If you want to preserve the quotation marks, then you can pass the `posix=False` kwarg.
```
>>> shlex.split('this is "a test"', posix=False)
['this', 'is', '"a test"']
``` |
80,031 | <p>I have a asp:menu object which I set up to use a <em>SiteMapDataSource</em> but everytime I try to run the site, I get a yellow screen from firefox saying it cannot find the <code>web.sitemap</code>. Here's the code for the <em>sitemapdatasource</em> and the menu. The Web.sitemap file is sitting in the root directory of the website.</p>
<pre><code><div>
<asp:Menu ID="MainMenu" CssClass="wTheme" Orientation="Horizontal" runat="server" DataSourceID="SiteMapDataSource1">
</asp:Menu>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" SiteMapProvider="Web.sitemap" />
</div>
</code></pre>
<p>And this is the Web.sitemap looks like so:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
</code></pre>
<p>
</p>
| [
{
"answer_id": 80060,
"author": "Encoder",
"author_id": 14629,
"author_profile": "https://Stackoverflow.com/users/14629",
"pm_score": 3,
"selected": true,
"text": "<p>I had a similar problem where I was specifying the path to the SiteMap from within my DataSource control. I tried removin... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4298/"
] | I have a asp:menu object which I set up to use a *SiteMapDataSource* but everytime I try to run the site, I get a yellow screen from firefox saying it cannot find the `web.sitemap`. Here's the code for the *sitemapdatasource* and the menu. The Web.sitemap file is sitting in the root directory of the website.
```
<div>
<asp:Menu ID="MainMenu" CssClass="wTheme" Orientation="Horizontal" runat="server" DataSourceID="SiteMapDataSource1">
</asp:Menu>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" SiteMapProvider="Web.sitemap" />
</div>
```
And this is the Web.sitemap looks like so:
```
<?xml version="1.0" encoding="utf-8" ?>
``` | I had a similar problem where I was specifying the path to the SiteMap from within my DataSource control. I tried removing it and it worked.
Try removing the path from the SiteMapDataSource and ensure that web.sitemap is in the root directory and see if that fixes it. |
80,042 | <p>Can you provide an example of a byte buffer transferred between two java classes via UDP datagram?</p>
| [
{
"answer_id": 80071,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 3,
"selected": true,
"text": "<p>Hows' this ?</p>\n\n<pre>\nimport java.io.IOException;\nimport java.net.DatagramPacket;\nimport java.net.DatagramSocket... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Can you provide an example of a byte buffer transferred between two java classes via UDP datagram? | Hows' this ?
```
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class Server {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(new InetSocketAddress(5000));
byte[] message = new byte[512];
DatagramPacket packet = new DatagramPacket(message, message.length);
socket.receive(packet);
System.out.println(new String(packet.getData(), packet.getOffset(), packet.getLength()));
}
}
```
```
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class Client {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
socket.connect(new InetSocketAddress(5000));
byte[] message = "Oh Hai!".getBytes();
DatagramPacket packet = new DatagramPacket(message, message.length);
socket.send(packet);
}
}
``` |
80,084 | <p>In JavaScript, the "this" operator can refer to different things under different scenarios. </p>
<p>Typically in a method within a JavaScript "object", it refers to the current object.</p>
<p>But when used as a callback, it becomes a reference to the calling object.</p>
<p>I have found that this causes problems in code, because if you use a method within a JavaScript "object" as a callback function you can't tell whether "this" refers to the current "object" or whether "this" refers to the calling object.</p>
<p>Can someone clarify usage and best practices regarding how to get around this problem?</p>
<pre><code> function TestObject() {
TestObject.prototype.firstMethod = function(){
this.callback();
YAHOO.util.Connect.asyncRequest(method, uri, callBack);
}
TestObject.prototype.callBack = function(o){
// do something with "this"
//when method is called directly, "this" resolves to the current object
//when invoked by the asyncRequest callback, "this" is not the current object
//what design patterns can make this consistent?
this.secondMethod();
}
TestObject.prototype.secondMethod = function() {
alert('test');
}
}
</code></pre>
| [
{
"answer_id": 80095,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 0,
"selected": false,
"text": "<p>I believe this may be due to how the idea of [closures](<a href=\"http://en.wikipedia.org/wiki/Closure_(computer_science)\" re... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In JavaScript, the "this" operator can refer to different things under different scenarios.
Typically in a method within a JavaScript "object", it refers to the current object.
But when used as a callback, it becomes a reference to the calling object.
I have found that this causes problems in code, because if you use a method within a JavaScript "object" as a callback function you can't tell whether "this" refers to the current "object" or whether "this" refers to the calling object.
Can someone clarify usage and best practices regarding how to get around this problem?
```
function TestObject() {
TestObject.prototype.firstMethod = function(){
this.callback();
YAHOO.util.Connect.asyncRequest(method, uri, callBack);
}
TestObject.prototype.callBack = function(o){
// do something with "this"
//when method is called directly, "this" resolves to the current object
//when invoked by the asyncRequest callback, "this" is not the current object
//what design patterns can make this consistent?
this.secondMethod();
}
TestObject.prototype.secondMethod = function() {
alert('test');
}
}
``` | In JavaScript, `this` always refers to the object invoking the function that is being executed. So if the function is being used as an event handler, `this` will refer to the node that fired the event. But if you have an object and call a function on it like:
```
myObject.myFunction();
```
Then `this` inside `myFunction` will refer to `myObject`. Does it make sense?
To get around it you need to use closures. You can change your code as follows:
```
function TestObject() {
TestObject.prototype.firstMethod = function(){
this.callback();
YAHOO.util.Connect.asyncRequest(method, uri, callBack);
}
var that = this;
TestObject.prototype.callBack = function(o){
that.secondMethod();
}
TestObject.prototype.secondMethod = function() {
alert('test');
}
}
``` |
80,152 | <p>What are the potential pros and cons of each of these queries given different databases, configurations, etc? Is there ever a time when one would be more efficient than the other? Vice versa? Is there an even better way to do it? Can you explain why?</p>
<p>Query 1:</p>
<pre><code>SELECT
*
FROM
table_a, table_b, table_c
WHERE
table_a.id = table_b.id AND
table_a.id = table_c.id AND
table_a.create_date > DATE('1998-01-01');
</code></pre>
<p>Query 2:</p>
<pre><code>SELECT
*
FROM
table_a
INNER JOIN table_b ON
table_a.id = table_b.id
INNER JOIN table_c ON
table_a.id = table_c.id
WHERE
table_a.create_date > DATE('1998-01-01');
</code></pre>
| [
{
"answer_id": 80169,
"author": "Encoder",
"author_id": 14629,
"author_profile": "https://Stackoverflow.com/users/14629",
"pm_score": -1,
"selected": false,
"text": "<p>I agree, it's sounding a bit too much like Homework!</p>\n\n<p>If it isn't homework then I guess the simplest answer is... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What are the potential pros and cons of each of these queries given different databases, configurations, etc? Is there ever a time when one would be more efficient than the other? Vice versa? Is there an even better way to do it? Can you explain why?
Query 1:
```
SELECT
*
FROM
table_a, table_b, table_c
WHERE
table_a.id = table_b.id AND
table_a.id = table_c.id AND
table_a.create_date > DATE('1998-01-01');
```
Query 2:
```
SELECT
*
FROM
table_a
INNER JOIN table_b ON
table_a.id = table_b.id
INNER JOIN table_c ON
table_a.id = table_c.id
WHERE
table_a.create_date > DATE('1998-01-01');
``` | Same query, different revision of SQL spec. The query optimizer should come up with the same query plan for those. |
80,175 | <p>This is somewhat similar to <a href="https://stackoverflow.com/questions/25653/hide-a-column-in-aspnet-dynamic-data">this question</a>.</p>
<p>However, rather than wanting to hide a column all together, I am just looking to hide the column on the List.aspx page.</p>
<p>My specific example is that fields that are long (or at least nvarchar(MAX)) automatically hide from the List.aspx page as is but are still visible on the Edit.aspx page.</p>
<p>I would like to replicate this behaviour for other (shorter) columns.</p>
<p>Is this possible?</p>
| [
{
"answer_id": 81806,
"author": "Mark Pattison",
"author_id": 15519,
"author_profile": "https://Stackoverflow.com/users/15519",
"pm_score": 4,
"selected": true,
"text": "<p>You can create a custom page for the particular table you want to change. There's an example <a href=\"http://davi... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | This is somewhat similar to [this question](https://stackoverflow.com/questions/25653/hide-a-column-in-aspnet-dynamic-data).
However, rather than wanting to hide a column all together, I am just looking to hide the column on the List.aspx page.
My specific example is that fields that are long (or at least nvarchar(MAX)) automatically hide from the List.aspx page as is but are still visible on the Edit.aspx page.
I would like to replicate this behaviour for other (shorter) columns.
Is this possible? | You can create a custom page for the particular table you want to change. There's an example [here](http://davidhayden.com/blog/dave/archive/2007/12/30/ASPNETDynamicDataWebsitesCustomizingPagesValidation.aspx).
Within your custom page, you can then set `AutoGenerateColumns="false"` within the `asp:GridView` control, and then define exactly the columns you want, like this:
```
<Columns>
...
<asp:DynamicField DataField="Product" HeaderText="Product" />
<asp:DynamicField DataField="Colour" HeaderText="Colour" />
</Columns>
``` |
80,186 | <p>I can't seem to find much documentation on X-Sendfile or example code for PHP (there is some rails code).</p>
<p>Anyone used it before and would mind giving a quick snippet of code and a brief description?</p>
| [
{
"answer_id": 80201,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 5,
"selected": false,
"text": "<p>X-Sendfile is an HTTP header, so you want something like this:</p>\n\n<pre><code>header(\"X-Sendfile: $filename\");\... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I can't seem to find much documentation on X-Sendfile or example code for PHP (there is some rails code).
Anyone used it before and would mind giving a quick snippet of code and a brief description? | X-Sendfile is an HTTP header, so you want something like this:
```
header("X-Sendfile: $filename");
```
Your web server picks it up if correctly configured. Here's some more details:
<http://www.jasny.net/articles/how-i-php-x-sendfile/> |
80,195 | <p>I would like to make 2 TB or so available via NFS and CIFS. I am looking for a 2 (or more) server solution for high availability and the ability to load balance across the servers if possible. Any suggestions for clustering or high availability solutions?</p>
<p>This is business use, planning on growing to 5-10 TB over next few years. Our facility is almost 24 hours a day, six days a week. We could have 15-30 minutes of downtime, but we want to minimize data loss. I want to minimize 3 AM calls. </p>
<p>We are currently running one server with ZFS on Solaris and we are looking at AVS for the HA part, but we have had minor issues with Solaris (CIFS implementation doesn't work with Vista, etc) that have held us up. </p>
<p>We have started looking at </p>
<ul>
<li>DRDB over GFS (GFS for distributed
lock capability)</li>
<li>Gluster (needs
client pieces, no native CIFS
support?)</li>
<li>Windows DFS (doc says only
replicates after file closes?)</li>
</ul>
<p>We are looking for a "black box" that serves up data.</p>
<p>We currently snapshot the data in ZFS and send the snapshot over the net to a remote datacenter for offsite backup.</p>
<p>Our original plan was to have a 2nd machine and rsync every 10 - 15 min. The issue on a failure would be that ongoing production processes would lose 15 minutes of data and be left "in the middle". They would almost be easier to start from the beginning than to figure out where to pickup in the middle. That is what drove us to look at HA solutions.</p>
| [
{
"answer_id": 80211,
"author": "David Ackerman",
"author_id": 2504,
"author_profile": "https://Stackoverflow.com/users/2504",
"pm_score": 0,
"selected": false,
"text": "<p>Are you looking for an \"enterprise\" solution or a \"home\" solution? It is hard to tell from your question, beca... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15020/"
] | I would like to make 2 TB or so available via NFS and CIFS. I am looking for a 2 (or more) server solution for high availability and the ability to load balance across the servers if possible. Any suggestions for clustering or high availability solutions?
This is business use, planning on growing to 5-10 TB over next few years. Our facility is almost 24 hours a day, six days a week. We could have 15-30 minutes of downtime, but we want to minimize data loss. I want to minimize 3 AM calls.
We are currently running one server with ZFS on Solaris and we are looking at AVS for the HA part, but we have had minor issues with Solaris (CIFS implementation doesn't work with Vista, etc) that have held us up.
We have started looking at
* DRDB over GFS (GFS for distributed
lock capability)
* Gluster (needs
client pieces, no native CIFS
support?)
* Windows DFS (doc says only
replicates after file closes?)
We are looking for a "black box" that serves up data.
We currently snapshot the data in ZFS and send the snapshot over the net to a remote datacenter for offsite backup.
Our original plan was to have a 2nd machine and rsync every 10 - 15 min. The issue on a failure would be that ongoing production processes would lose 15 minutes of data and be left "in the middle". They would almost be easier to start from the beginning than to figure out where to pickup in the middle. That is what drove us to look at HA solutions. | I've recently deployed hanfs using DRBD as the backend, in my situation, I'm running active/standby mode, but I've tested it successfully using OCFS2 in primary/primary mode too. There unfortunately isn't much documentation out there on how best to achieve this, most that exists is barely useful at best. If you do go along the drbd route, I highly recommend joining the drbd mailing list, and reading all of the documentation. Here's my ha/drbd setup and script I wrote to handle ha's failures:
---
DRBD8 is required - this is provided by drbd8-utils and drbd8-source. Once these are installed (I believe they're provided by backports), you can use module-assistant to install it - m-a a-i drbd8. Either depmod -a or reboot at this point, if you depmod -a, you'll need to modprobe drbd.
You'll require a backend partition to use for drbd, do not make this partition LVM, or you'll hit all sorts of problems. Do not put LVM on the drbd device or you'll hit all sorts of problems.
Hanfs1:
```
/etc/drbd.conf
global {
usage-count no;
}
common {
protocol C;
disk { on-io-error detach; }
}
resource export {
syncer {
rate 125M;
}
on hanfs2 {
address 172.20.1.218:7789;
device /dev/drbd1;
disk /dev/sda3;
meta-disk internal;
}
on hanfs1 {
address 172.20.1.219:7789;
device /dev/drbd1;
disk /dev/sda3;
meta-disk internal;
}
}
```
Hanfs2's /etc/drbd.conf:
```
global {
usage-count no;
}
common {
protocol C;
disk { on-io-error detach; }
}
resource export {
syncer {
rate 125M;
}
on hanfs2 {
address 172.20.1.218:7789;
device /dev/drbd1;
disk /dev/sda3;
meta-disk internal;
}
on hanfs1 {
address 172.20.1.219:7789;
device /dev/drbd1;
disk /dev/sda3;
meta-disk internal;
}
}
```
Once configured, we need to bring up drbd next.
```
drbdadm create-md export
drbdadm attach export
drbdadm connect export
```
We must now perform an initial synchronization of data - obviously, if this is a brand new drbd cluster, it doesn't matter which node you choose.
Once done, you'll need to mkfs.yourchoiceoffilesystem on your drbd device - the device in our config above is /dev/drbd1. <http://www.drbd.org/users-guide/p-work.html> is a useful document to read while working with drbd.
Heartbeat
Install heartbeat2. (Pretty simple, apt-get install heartbeat2).
/etc/ha.d/ha.cf on each machine should consist of:
hanfs1:
```
logfacility local0
keepalive 2
warntime 10
deadtime 30
initdead 120
```
ucast eth1 172.20.1.218
auto\_failback no
node hanfs1
node hanfs2
hanfs2:
```
logfacility local0
keepalive 2
warntime 10
deadtime 30
initdead 120
```
ucast eth1 172.20.1.219
auto\_failback no
node hanfs1
node hanfs2
/etc/ha.d/haresources should be the same on both ha boxes:
```
hanfs1 IPaddr::172.20.1.230/24/eth1
hanfs1 HeartBeatWrapper
```
I wrote a wrapper script to deal with the idiosyncracies caused by nfs and drbd in a failover scenario. This script should exist within /etc/ha.d/resources.d/ on each machine.
!/bin/bash
==========
heartbeat fails hard.
=====================
so this is a wrapper
====================
to get around that stupidity
============================
I'm just wrapping the heartbeat scripts, except for in the case of umount
=========================================================================
as they work, mostly
====================
if [[ -e /tmp/heartbeatwrapper ]]; then
runningpid=$(cat /tmp/heartbeatwrapper)
if [[ -z $(ps --no-heading -p $runningpid) ]]; then
echo "PID found, but process seems dead. Continuing."
else
echo "PID found, process is alive, exiting."
exit 7
fi
fi
echo $$ > /tmp/heartbeatwrapper
if [[ x$1 == "xstop" ]]; then
/etc/init.d/nfs-kernel-server stop #>/dev/null 2>&1
NFS init script isn't LSB compatible, exit codes are 0 no matter what happens.
==============================================================================
Thanks guys, you really make my day with this bullshit.
=======================================================
Because of the above, we just have to hope that nfs actually catches the signal
===============================================================================
to exit, and manages to shut down its connections.
==================================================
If it doesn't, we'll kill it later, then term any other nfs stuff afterwards.
=============================================================================
I found this to be an interesting insight into just how badly NFS is written.
=============================================================================
sleep 1
```
#we don't want to shutdown nfs first!
#The lock files might go away, which would be bad.
#The above seems to not matter much, the only thing I've determined
#is that if you have anything mounted synchronously, it's going to break
#no matter what I do. Basically, sync == screwed; in NFSv3 terms.
#End result of failing over while a client that's synchronous is that
#the client hangs waiting for its nfs server to come back - thing doesn't
#even bother to time out, or attempt a reconnect.
#async works as expected - it insta-reconnects as soon as a connection seems
#to be unstable, and continues to write data. In all tests, md5sums have
#remained the same with/without failover during transfer.
#So, we first unmount /export - this prevents drbd from having a shit-fit
#when we attempt to turn this node secondary.
#That's a lie too, to some degree. LVM is entirely to blame for why DRBD
#was refusing to unmount. Don't get me wrong, having /export mounted doesn't
#help either, but still.
#fix a usecase where one or other are unmounted already, which causes us to terminate early.
if [[ "$(grep -o /varlibnfs/rpc_pipefs /etc/mtab)" ]]; then
for ((test=1; test <= 10; test++)); do
umount /export/varlibnfs/rpc_pipefs >/dev/null 2>&1
if [[ -z $(grep -o /varlibnfs/rpc_pipefs /etc/mtab) ]]; then
break
fi
if [[ $? -ne 0 ]]; then
#try again, harder this time
umount -l /var/lib/nfs/rpc_pipefs >/dev/null 2>&1
if [[ -z $(grep -o /varlibnfs/rpc_pipefs /etc/mtab) ]]; then
break
fi
fi
done
if [[ $test -eq 10 ]]; then
rm -f /tmp/heartbeatwrapper
echo "Problem unmounting rpc_pipefs"
exit 1
fi
fi
if [[ "$(grep -o /dev/drbd1 /etc/mtab)" ]]; then
for ((test=1; test <= 10; test++)); do
umount /export >/dev/null 2>&1
if [[ -z $(grep -o /dev/drbd1 /etc/mtab) ]]; then
break
fi
if [[ $? -ne 0 ]]; then
#try again, harder this time
umount -l /export >/dev/null 2>&1
if [[ -z $(grep -o /dev/drbd1 /etc/mtab) ]]; then
break
fi
fi
done
if [[ $test -eq 10 ]]; then
rm -f /tmp/heartbeatwrapper
echo "Problem unmount /export"
exit 1
fi
fi
#now, it's important that we shut down nfs. it can't write to /export anymore, so that's fine.
#if we leave it running at this point, then drbd will screwup when trying to go to secondary.
#See contradictory comment above for why this doesn't matter anymore. These comments are left in
#entirely to remind me of the pain this caused me to resolve. A bit like why churches have Jesus
#nailed onto a cross instead of chilling in a hammock.
pidof nfsd | xargs kill -9 >/dev/null 2>&1
sleep 1
if [[ -n $(ps aux | grep nfs | grep -v grep) ]]; then
echo "nfs still running, trying to kill again"
pidof nfsd | xargs kill -9 >/dev/null 2>&1
fi
sleep 1
/etc/init.d/nfs-kernel-server stop #>/dev/null 2>&1
sleep 1
#next we need to tear down drbd - easy with the heartbeat scripts
#it takes input as resourcename start|stop|status
#First, we'll check to see if it's stopped
/etc/ha.d/resource.d/drbddisk export status >/dev/null 2>&1
if [[ $? -eq 2 ]]; then
echo "resource is already stopped for some reason..."
else
for ((i=1; i <= 10; i++)); do
/etc/ha.d/resource.d/drbddisk export stop >/dev/null 2>&1
if [[ $(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2) == "Secondary/Secondary" ]] || [[ $(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2) == "Secondary/Unknown" ]]; then
echo "Successfully stopped DRBD"
break
else
echo "Failed to stop drbd for some reason"
cat /proc/drbd
if [[ $i -eq 10 ]]; then
exit 50
fi
fi
done
fi
rm -f /tmp/heartbeatwrapper
exit 0
```
elif [[ x$1 == "xstart" ]]; then
```
#start up drbd first
/etc/ha.d/resource.d/drbddisk export start >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "Something seems to have broken. Let's check possibilities..."
testvar=$(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2)
if [[ $testvar == "Primary/Unknown" ]] || [[ $testvar == "Primary/Secondary" ]]
then
echo "All is fine, we are already the Primary for some reason"
elif [[ $testvar == "Secondary/Unknown" ]] || [[ $testvar == "Secondary/Secondary" ]]
then
echo "Trying to assume Primary again"
/etc/ha.d/resource.d/drbddisk export start >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "I give up, something's seriously broken here, and I can't help you to fix it."
rm -f /tmp/heartbeatwrapper
exit 127
fi
fi
fi
sleep 1
#now we remount our partitions
for ((test=1; test <= 10; test++)); do
mount /dev/drbd1 /export >/tmp/mountoutput
if [[ -n $(grep -o export /etc/mtab) ]]; then
break
fi
done
if [[ $test -eq 10 ]]; then
rm -f /tmp/heartbeatwrapper
exit 125
fi
#I'm really unsure at this point of the side-effects of not having rpc_pipefs mounted.
#The issue here, is that it cannot be mounted without nfs running, and we don't really want to start
#nfs up at this point, lest it ruin everything.
#For now, I'm leaving mine unmounted, it doesn't seem to cause any problems.
#Now we start up nfs.
/etc/init.d/nfs-kernel-server start >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "There's not really that much that I can do to debug nfs issues."
echo "probably your configuration is broken. I'm terminating here."
rm -f /tmp/heartbeatwrapper
exit 129
fi
#And that's it, done.
rm -f /tmp/heartbeatwrapper
exit 0
```
elif [[ "x$1" == "xstatus" ]]; then
```
#Lets check to make sure nothing is broken.
#DRBD first
/etc/ha.d/resource.d/drbddisk export status >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "stopped"
rm -f /tmp/heartbeatwrapper
exit 3
fi
#mounted?
grep -q drbd /etc/mtab >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "stopped"
rm -f /tmp/heartbeatwrapper
exit 3
fi
#nfs running?
/etc/init.d/nfs-kernel-server status >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "stopped"
rm -f /tmp/heartbeatwrapper
exit 3
fi
echo "running"
rm -f /tmp/heartbeatwrapper
exit 0
```
fi
With all of the above done, you'll then just want to configure /etc/exports
```
/export 172.20.1.0/255.255.255.0(rw,sync,fsid=1,no_root_squash)
```
Then it's just a case of starting up heartbeat on both machines and issuing hb\_takeover on one of them. You can test that it's working by making sure the one you issued the takeover on is primary - check /proc/drbd, that the device is mounted correctly, and that you can access nfs.
--
Best of luck man. Setting it up from the ground up was, for me, an extremely painful experience. |
80,202 | <p>I want to use javascript to insert some elements into the current page.
Such as this is the original document:
<p>Hello world!</p></p>
<p>Now I want to insert an element in to the text so that it will become:</p>
<p><p>Hello <span id=span1>new</span> world!</p></p>
<p>I need the span tag because I want to handle it later.Show or hide.
But now problem comes out, if the original page has already defined a strange CSS style on all <span> tags, the "new" I just inserted will not appear to be the same as "Hello" and "world". How can I avoid this? I want the "new" be exactly the same as the "Hello" and "world".</p>
| [
{
"answer_id": 80228,
"author": "Sev",
"author_id": 83819,
"author_profile": "https://Stackoverflow.com/users/83819",
"pm_score": 0,
"selected": false,
"text": "<p>Include the class definition that's defined in CSS on your JavaScript version of the <code><span></code> tag as well.<... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15023/"
] | I want to use javascript to insert some elements into the current page.
Such as this is the original document:
<p>Hello world!</p>
Now I want to insert an element in to the text so that it will become:
<p>Hello <span id=span1>new</span> world!</p>
I need the span tag because I want to handle it later.Show or hide.
But now problem comes out, if the original page has already defined a strange CSS style on all <span> tags, the "new" I just inserted will not appear to be the same as "Hello" and "world". How can I avoid this? I want the "new" be exactly the same as the "Hello" and "world". | Simply override any span styles. Set layout properties back to browser defaults and set formating to inherit from the parent:
```
span#yourSpan {
/* defaults */
position: static;
display: inline;
margin: 0;
padding: 0;
background: transparent;
border: none;
/* inherit from parent node */
font: inherit;
color: inherit;
text-decoration: inherit;
line-height: inherit;
letter-spacing: inherit;
text-transform: inherit;
white-space: inherit;
word-spacing: inherit;
}
```
This should be sufficient, although you may need to add !important if you are not using an id:
```
<span class="hello-node">hello</span>
span.hello-node {
/* defaults */
position: static !important;
display: inline !important;
...
}
``` |
80,247 | <p>How can I get all implementations of an interface through reflection in C#?</p>
| [
{
"answer_id": 80325,
"author": "Alex Duggleby",
"author_id": 5790,
"author_profile": "https://Stackoverflow.com/users/5790",
"pm_score": 1,
"selected": false,
"text": "<p>Do you mean all interfaces a Type implements?</p>\n\n<p>Like this:</p>\n\n<pre><code>ObjX foo = new ObjX();\nType tF... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How can I get all implementations of an interface through reflection in C#? | The answer is this; it searches through the entire application domain -- that is, every assembly currently loaded by your application.
```
/// <summary>
/// Returns all types in the current AppDomain implementing the interface or inheriting the type.
/// </summary>
public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)
{
return AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(type => desiredType.IsAssignableFrom(type));
}
```
It is used like this;
```
var disposableTypes = TypesImplementingInterface(typeof(IDisposable));
```
You may also want this function to find actual concrete types -- i.e., filtering out abstracts, interfaces, and generic type definitions.
```
public static bool IsRealClass(Type testType)
{
return testType.IsAbstract == false
&& testType.IsGenericTypeDefinition == false
&& testType.IsInterface == false;
}
``` |
80,278 | <p>I am trying to use the Google Maps API in a ColdFusion template that is a border type cflayoutarea container. However, the map simply doesn't show up:</p>
<pre><code><cfif isdefined("url.lat")>
<cfset lat="#url.lat#">
<cfset lng="#url.lng#">
</cfif>
<head>
<script src= "http://maps.google.com/maps?file=api&amp;v=2&amp;key=xxxx" type="text/javascript">
function getMap(lat,lng){
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var pt= new GLatLng(lat,lng);
map.setCenter(pt, 18,G_HYBRID_MAP);
map.addOverlay(new GMarker(pt));
}
}
</script>
</head>
<cfoutput>
<body onLoad="getMap(#lat#,#lng#)" onUnload="GUnload()">
Map:<br>
<div id="map_canvas" style="width: 500px; height: 300px"/>
</body>
</cfoutput>"
</code></pre>
<p>where lat and lng are the co-ordinates in degree.decimal format. I have traced down to the line where GBrowserIsCompatible() somehow never returns TRUE and thus no further action was taken.</p>
<p>If opened separately the template works perfectly but just not when opened as a cflayoutarea container. Anyone has experience in this? Any suggestions is much appreciated.</p>
<p>Lawrence</p>
<p>Using CF 8.01, Dreamweaver 8</p>
<hr>
<p>Tried your suggestion but still doesn't work; the map only shows when the calling code is inline. However, if this container page was called from yet another div the map disappears again.</p>
<p>I suspect this issue is related to the cflayout container; I'll look up the Extjs doc to see if there're any leads to a solution.</p>
| [
{
"answer_id": 80298,
"author": "convex hull",
"author_id": 10747,
"author_profile": "https://Stackoverflow.com/users/10747",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe the layout area doesn't have the right <strong>style</strong>. I think you may have to give the map_canvas a<... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15007/"
] | I am trying to use the Google Maps API in a ColdFusion template that is a border type cflayoutarea container. However, the map simply doesn't show up:
```
<cfif isdefined("url.lat")>
<cfset lat="#url.lat#">
<cfset lng="#url.lng#">
</cfif>
<head>
<script src= "http://maps.google.com/maps?file=api&v=2&key=xxxx" type="text/javascript">
function getMap(lat,lng){
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var pt= new GLatLng(lat,lng);
map.setCenter(pt, 18,G_HYBRID_MAP);
map.addOverlay(new GMarker(pt));
}
}
</script>
</head>
<cfoutput>
<body onLoad="getMap(#lat#,#lng#)" onUnload="GUnload()">
Map:<br>
<div id="map_canvas" style="width: 500px; height: 300px"/>
</body>
</cfoutput>"
```
where lat and lng are the co-ordinates in degree.decimal format. I have traced down to the line where GBrowserIsCompatible() somehow never returns TRUE and thus no further action was taken.
If opened separately the template works perfectly but just not when opened as a cflayoutarea container. Anyone has experience in this? Any suggestions is much appreciated.
Lawrence
Using CF 8.01, Dreamweaver 8
---
Tried your suggestion but still doesn't work; the map only shows when the calling code is inline. However, if this container page was called from yet another div the map disappears again.
I suspect this issue is related to the cflayout container; I'll look up the Extjs doc to see if there're any leads to a solution. | Success! (sort of...)
Finally got it working, but not in the way Adam suggested:
```
<script src= "http://maps.google.com/maps?file=api&v=2&key=xxxx" type="text/javascript"></script>
<script type="text/javascript">
getMap=function(lat,lng){
if (GBrowserIsCompatible()){
var map = new GMap2(document.getElementById("map_canvas"));
var pt = new GLatLng(lat,lng);
map.setCenter(pt, 18,G_HYBRID_MAP);
map.addOverlay(new GMarker(pt));
}
}
</script>
<cflayout name="testlayout" type="border">
<cflayoutarea name="left" position="left" size="250"/>
<cflayoutarea name="center" position="center">
<!--- sample hard-coded co-ordinates --->
<body onLoad="getMap(22.280161,114.185096)">
Map:<br />
<div id="map_canvas" style="width:500px; height: 300px"/>
</body>
</cflayoutarea>
<!--- <cflayoutarea name="center" position="center" source="map_content.cfm?lat=22.280161&lng=114.185096"/> --->
</cflayout>
```
The whole thing must be contained within the same file or it would not work. My suspicion is that the getElementByID function, as it stands, cannot not reference an element that is outside of its own file. If the div is in another file (as in Adam's exmaple), it results in an undefined map, ie a map object is created but with nothing in it.
So I think this question is now elevated to a different level: how do you reference an element that is inside an ajax container? |
80,291 | <p>In Sql Server 2000/2005, I have a few NT user groups that need to be granted access to hundreds of stored procedures.</p>
<p>Is there a nice easy way to do that?</p>
| [
{
"answer_id": 80340,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>Create a role in sql server.</li>\n<li>Write a\nscript that grants that role\npermission to use those sprocs.</li... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3276/"
] | In Sql Server 2000/2005, I have a few NT user groups that need to be granted access to hundreds of stored procedures.
Is there a nice easy way to do that? | Here's a script that I use for granting permissions to lots of procedures:
```
DECLARE @DB sysname ; set @DB = DB_NAME()
DECLARE @U sysname ; set @U = QUOTENAME('UserID')
DECLARE @ID integer,
@LAST_ID integer,
@NAME varchar(1000),
@SQL varchar(4000)
SET @LAST_ID = 0
WHILE @LAST_ID IS NOT NULL
BEGIN
SELECT @ID = MIN(id)
FROM dbo.sysobjects
WHERE id > @LAST_ID AND type = 'P' AND category = 0
SET @LAST_ID = @ID
-- We have a record so go get the name
IF @ID IS NOT NULL
BEGIN
SELECT @NAME = name
FROM dbo.sysobjects
WHERE id = @ID
-- Build the DCL to do the GRANT
SET @SQL = 'GRANT EXECUTE ON ' + @NAME + ' TO ' + @U
-- Run the SQL Statement you just generated
EXEC master.dbo.xp_execresultset @SQL, @DB
END
END
```
You can modify the select to get to a more specific group of stored procs. |
80,292 | <p>I was writing a database handler class in PHP using the mysqli class and prepared statements. I was attempting to print out the result. It didn't work right off the bat so I decided to do some debugging. I tried to use the <code>num_rows()</code> method from the <code>mysqli_statement</code> class, but it kept returning 0. I decided to write a small portion of the test code to keep it simpler so I could see what was going wrong. I was then able to return the data I wanted, but the <code>num_rows()</code> method still returns 0 even when it is actually selecting and retrieving some data. Here is the code:</p>
<pre><code>$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno())
{
die('connection failed');
}
$statement = $mysqli->stmt_init();
$query = "SELECT name FROM table WHERE id = '2000'";
if($statement->prepare($query))
{
$statement->execute();
$statement->bind_result($name);
$statement->fetch();
$statement->store_result();
echo $statement->num_rows();
echo $name;
}
else
{
echo 'prepare statement failed';
exit();
}
</code></pre>
<p>The expected result is:</p>
<pre><code>1name
</code></pre>
<p>And the actual result is:</p>
<pre><code>0name
</code></pre>
<p>Can anyone tell me why this is?</p>
| [
{
"answer_id": 80382,
"author": "Cetra",
"author_id": 15087,
"author_profile": "https://Stackoverflow.com/users/15087",
"pm_score": -1,
"selected": false,
"text": "<p>It doesn't look like you've declared $name.</p>\n\n<p>Also, try removing bind_result() and fetch() so it reads something ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3831/"
] | I was writing a database handler class in PHP using the mysqli class and prepared statements. I was attempting to print out the result. It didn't work right off the bat so I decided to do some debugging. I tried to use the `num_rows()` method from the `mysqli_statement` class, but it kept returning 0. I decided to write a small portion of the test code to keep it simpler so I could see what was going wrong. I was then able to return the data I wanted, but the `num_rows()` method still returns 0 even when it is actually selecting and retrieving some data. Here is the code:
```
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno())
{
die('connection failed');
}
$statement = $mysqli->stmt_init();
$query = "SELECT name FROM table WHERE id = '2000'";
if($statement->prepare($query))
{
$statement->execute();
$statement->bind_result($name);
$statement->fetch();
$statement->store_result();
echo $statement->num_rows();
echo $name;
}
else
{
echo 'prepare statement failed';
exit();
}
```
The expected result is:
```
1name
```
And the actual result is:
```
0name
```
Can anyone tell me why this is? | I wonder if num\_rows() is reporting relative to the current resultset. Try capturing num\_rows() prior to fetching the data. e.g.
```
if($statement->prepare($query))
{
$statement->execute();
$statement->store_result();
echo $statement->num_rows();
$statement->bind_result($name);
$statement->fetch();
echo $name;
}
```
Does that have any effect? |
80,307 | <p>I've read in a couple of places that the desktop wallpaper can be set to an HTML document. Has anyone had any success changing it programmatically? </p>
<p>The following snippet of VB6 helps me set things up for BMPs but when I try to use it for HTML, I get a nice blue background and nothing else.</p>
<pre><code>Dim reg As New StdRegistry
Public Function CurrentWallpaper() As String
CurrentWallpaper = reg.ValueEx(HKEY_CURRENT_USER, "Control Panel\Desktop", "Wallpaper", REG_SZ, "")
End Function
Public Sub SetWallpaper(cFilename As Variant)
reg.ClassKey = HKEY_CURRENT_USER
reg.SectionKey = "Control Panel\Desktop"
reg.ValueKey = "Wallpaper"
reg.ValueType = REG_SZ
reg.Default = ""
reg.Value = cFilename
End Sub
Public Sub RefreshDesktop()
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
oShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters", 1, True
End Sub
</code></pre>
<p>Perhaps there's some other setting that's required. Any ideas?</p>
| [
{
"answer_id": 80334,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to make sure \"Active Desktop\" is turned on.</p>\n\n<p>You might try setting <code>HKCU\\Software\\Micr... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426/"
] | I've read in a couple of places that the desktop wallpaper can be set to an HTML document. Has anyone had any success changing it programmatically?
The following snippet of VB6 helps me set things up for BMPs but when I try to use it for HTML, I get a nice blue background and nothing else.
```
Dim reg As New StdRegistry
Public Function CurrentWallpaper() As String
CurrentWallpaper = reg.ValueEx(HKEY_CURRENT_USER, "Control Panel\Desktop", "Wallpaper", REG_SZ, "")
End Function
Public Sub SetWallpaper(cFilename As Variant)
reg.ClassKey = HKEY_CURRENT_USER
reg.SectionKey = "Control Panel\Desktop"
reg.ValueKey = "Wallpaper"
reg.ValueType = REG_SZ
reg.Default = ""
reg.Value = cFilename
End Sub
Public Sub RefreshDesktop()
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
oShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters", 1, True
End Sub
```
Perhaps there's some other setting that's required. Any ideas? | I'm not sure if there's an official API for this, but if you have your heart set on it you could use Sysinternal's [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) and see what registry keys get touched when you set an HTML desktop background via the UI. Then you'd just need to repeat those edits in your code. However, an API call would be far preferable in terms of backward/forward compatibility. |
80,319 | <p>I have video durations stored in HH:MM:SS format. I'd like to display it as HH hours, MM minutes, SS seconds. It shouldn't display hours if it's less than 1.</p>
<p>What would be the best approach?</p>
| [
{
"answer_id": 80366,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 2,
"selected": false,
"text": "<p>Something like this?</p>\n\n<pre><code>$vals = explode(':', $duration);\n\nif ( $vals[0] == 0 )\n $result = ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have video durations stored in HH:MM:SS format. I'd like to display it as HH hours, MM minutes, SS seconds. It shouldn't display hours if it's less than 1.
What would be the best approach? | try using split
```
list($hh,$mm,$ss)= split(':',$duration);
``` |
80,348 | <p>In C++0x I would like to write a function like this:</p>
<pre><code>template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
//Put things into the tuple
}
</code></pre>
<p>I first tried to use a for loop on <code>int i</code> and then do:</p>
<pre><code>get<i>(my_tuple);
</code></pre>
<p>And then store some value in the result. However, <code>get</code> only works on <code>constexpr</code>.</p>
<p>If I could get the variables out of the <code>tuple</code> and pass them to a variadic templated function I could recurse through the arguments very easily, but I have no idea how to get the variables out of the tuple without <code>get</code>. Any ideas on how to do that? Or does anyone have another way of modifying this <code>tuple</code>?</p>
| [
{
"answer_id": 80573,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 3,
"selected": true,
"text": "<p>Since the \"i\" in</p>\n\n<pre><code>get<i>(tup)\n</code></pre>\n\n<p>needs to be a compile-time constant, template... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In C++0x I would like to write a function like this:
```
template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
//Put things into the tuple
}
```
I first tried to use a for loop on `int i` and then do:
```
get<i>(my_tuple);
```
And then store some value in the result. However, `get` only works on `constexpr`.
If I could get the variables out of the `tuple` and pass them to a variadic templated function I could recurse through the arguments very easily, but I have no idea how to get the variables out of the tuple without `get`. Any ideas on how to do that? Or does anyone have another way of modifying this `tuple`? | Since the "i" in
```
get<i>(tup)
```
needs to be a compile-time constant, template instantiation is used to "iterate" (actually recurse) through the values. Boost tuples have the "length" and "element" meta-functions that can be helpful here -- I assume C++0x has these too. |
80,357 | <p>Is there a quick way to find every match of a regular expression in Ruby? I've looked through the Regex object in the Ruby STL and searched on Google to no avail.</p>
| [
{
"answer_id": 80387,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 11,
"selected": true,
"text": "<p>Using <a href=\"http://ruby-doc.org/core-1.9.3/String.html#method-i-scan\" rel=\"noreferrer\"><code>scan</code></a> should do... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] | Is there a quick way to find every match of a regular expression in Ruby? I've looked through the Regex object in the Ruby STL and searched on Google to no avail. | Using [`scan`](http://ruby-doc.org/core-1.9.3/String.html#method-i-scan) should do the trick:
```
string.scan(/regex/)
``` |
80,388 | <p>I'm trying to trigger a progress animation when ever the ViewModel/Presentation Model is Busy. I have an IsBusy Property, and the ViewModel is set as the DataContext of the UserControl. What is the best way to trigger a "progressAnimation" storyboard when the IsBusy property is true? Blend only lets me add event triggers at the UserControl level, and I can only create property triggers in my data templates.</p>
<p>The "progressAnimation" is defined as a resource in the user control.</p>
<p>I tried adding the DataTriggers as a Style on the UserControl, but when I try to start the StoryBoard I get the following error:</p>
<blockquote>
<p>'System.Windows.Style' value cannot be assigned to property 'Style'
of object'Colorful.Control.SearchPanel'. A Storyboard tree in a Style
cannot specify a TargetName. Remove TargetName 'progressWheel'.</p>
</blockquote>
<p>ProgressWheel is the name of the object I'm trying to animate, so removing the target name is obviously NOT what I want.</p>
<p>I was hoping to solve this in XAML using data binding techniques, instead of having to expose events and start/stop the animation through code.</p>
| [
{
"answer_id": 80455,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend to use RoutedEvent instead of your IsBusy property. Just fire OnBusyStarted and OnBusyStopped event and... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
] | I'm trying to trigger a progress animation when ever the ViewModel/Presentation Model is Busy. I have an IsBusy Property, and the ViewModel is set as the DataContext of the UserControl. What is the best way to trigger a "progressAnimation" storyboard when the IsBusy property is true? Blend only lets me add event triggers at the UserControl level, and I can only create property triggers in my data templates.
The "progressAnimation" is defined as a resource in the user control.
I tried adding the DataTriggers as a Style on the UserControl, but when I try to start the StoryBoard I get the following error:
>
> 'System.Windows.Style' value cannot be assigned to property 'Style'
> of object'Colorful.Control.SearchPanel'. A Storyboard tree in a Style
> cannot specify a TargetName. Remove TargetName 'progressWheel'.
>
>
>
ProgressWheel is the name of the object I'm trying to animate, so removing the target name is obviously NOT what I want.
I was hoping to solve this in XAML using data binding techniques, instead of having to expose events and start/stop the animation through code. | What you want is possible by declaring the animation on the progressWheel itself:
The XAML:
```
<UserControl x:Class="TriggerSpike.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<UserControl.Resources>
<DoubleAnimation x:Key="SearchAnimation" Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:4"/>
<DoubleAnimation x:Key="StopSearchAnimation" Storyboard.TargetProperty="Opacity" To="0" Duration="0:0:4"/>
</UserControl.Resources>
<StackPanel>
<TextBlock Name="progressWheel" TextAlignment="Center" Opacity="0">
<TextBlock.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsBusy}" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<StaticResource ResourceKey="SearchAnimation"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<StaticResource ResourceKey="StopSearchAnimation"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
Searching
</TextBlock>
<Label Content="Here your search query"/>
<TextBox Text="{Binding SearchClause}"/>
<Button Click="Button_Click">Search!</Button>
<TextBlock Text="{Binding Result}"/>
</StackPanel>
```
Code behind:
```
using System.Windows;
using System.Windows.Controls;
namespace TriggerSpike
{
public partial class UserControl1 : UserControl
{
private MyViewModel myModel;
public UserControl1()
{
myModel=new MyViewModel();
DataContext = myModel;
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
myModel.Search(myModel.SearchClause);
}
}
}
```
The viewmodel:
```
using System.ComponentModel;
using System.Threading;
using System.Windows;
namespace TriggerSpike
{
class MyViewModel:DependencyObject
{
public string SearchClause{ get;set;}
public bool IsBusy
{
get { return (bool)GetValue(IsBusyProperty); }
set { SetValue(IsBusyProperty, value); }
}
public static readonly DependencyProperty IsBusyProperty =
DependencyProperty.Register("IsBusy", typeof(bool), typeof(MyViewModel), new UIPropertyMetadata(false));
public string Result
{
get { return (string)GetValue(ResultProperty); }
set { SetValue(ResultProperty, value); }
}
public static readonly DependencyProperty ResultProperty =
DependencyProperty.Register("Result", typeof(string), typeof(MyViewModel), new UIPropertyMetadata(string.Empty));
public void Search(string search_clause)
{
Result = string.Empty;
SearchClause = search_clause;
var worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
IsBusy = true;
worker.RunWorkerAsync();
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
IsBusy=false;
Result = "Sorry, no results found for: " + SearchClause;
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(5000);
}
}
}
```
Hope this helps! |
80,415 | <p>I have a string which starts with <code>//#...</code> goes upto the newline characater. I have figured out the regex for the which is this <code>..#([^\n]*)</code>.</p>
<p>My question is how do you remove this line from a file if the following condition matches</p>
| [
{
"answer_id": 80444,
"author": "EricSchaefer",
"author_id": 8976,
"author_profile": "https://Stackoverflow.com/users/8976",
"pm_score": 0,
"selected": false,
"text": "<p>Read the file line by line and only write those lines to a new file that don't match the regex.\nYou cannot just remo... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13046/"
] | I have a string which starts with `//#...` goes upto the newline characater. I have figured out the regex for the which is this `..#([^\n]*)`.
My question is how do you remove this line from a file if the following condition matches | Your regex is badly chosen on several points:
1. Instead of matching two slashes specifically, you use `..` to match two characters that can be anything at all, presumably because you don’t know how to match slashes when you’re also using them as delimiters. (Actually, dots match *almost* anything, as we’ll see in #3.)
Within a slash-delimited regex literal, `//`, you can match slashes simply by protecting them with backslashes, eg. `/\/\//`. The nicer variant, however, is to use the longer form of regex literal, `m//`, where you can choose the delimiter, eg. `m!!`. Since you use something other than slashes for delimitation, you can then write them without escaping them: `m!//!`. See [perldoc perlop](http://p3rl.org/op#Quote-and-Quote-like-Operators).
2. It’s not anchored to the start of the string so it will match anywhere. Use the `^` start-of-string assertion in front.
3. You wrote `[^\n]` to match “any character except newline” when there is a much simpler way to write that, which is just the `.` wildcard. It does exactly that – match any character except newline.
4. You are using parentheses to group a part of the match, but the group is neither quantified (you are not specifying that it can match any other number of times than exactly once) nor are you interested in keeping it. So the parentheses are superfluous.
Altogether, that makes it `m!^//#.*!`. But putting an uncaptured `.*` (or anything with a `*` quantifier) at the end of a regex is meaningless, since it never changes whether a string will match or not: the `*` is happy to match nothing at all.
So that leaves you with `m!^//#!`.
As for removing the line from the file, as everyone else explained, read it in line by line and print all the lines you want to keep back to another file. If you are not doing this within a larger program, use perl’s command line switches to do it easily:
```
perl -ni.bak -e'print unless m!^//#!' somefile.txt
```
Here, the `-n` switch makes perl put a loop around the code you provide which will read all the files you pass on the command line in sequence. The `-i` switch (for “in-place”) says to collect the output from your script and overwrite the original contents of each file with it. The `.bak` parameter to the `-i` option tells perl to keep a backup of the original file in a file named after the original file name with `.bak` appended. For all of these bits, see [perldoc perlrun](http://p3rl.org/run).
If you want to do this within the context of a larger program, the easiest way to do it safely is to open the file twice, once for reading, and separately, with [IO::AtomicFile](http://p3rl.org/IO::AtomicFile), another time for writing. IO::AtomicFile will replace the original file only if it’s successfully closed. |
80,424 | <p>I have a few models that need to have custom find conditions placed on them. For example, if I have a Contact model, every time Contact.find is called, I want to restrict the contacts returned that only belong to the Account in use.</p>
<p>I found this via Google (which I've customized a little):</p>
<pre><code>def self.find(*args)
with_scope(:find => { :conditions => "account_id = #{$account.id}" }) do
super(*args)
end
end
</code></pre>
<p>This works great, except for a few occasions where account_id is ambiguous so I adapted it to:</p>
<pre><code>def self.find(*args)
with_scope(:find => { :conditions => "#{self.to_s.downcase.pluralize}.account_id = #{$account.id}" }) do
super(*args)
end
end
</code></pre>
<p>This also works great, however, I want it to be DRY. Now I have a few different models that I want this kind of function to be used. What is the best way to do this?</p>
<p>When you answer, please include the code to help our minds grasp the metaprogramming Ruby-fu.</p>
<p>(I'm using Rails v2.1)</p>
| [
{
"answer_id": 80440,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 4,
"selected": true,
"text": "<p>You don't tell us which version of rails you are using [edit - it is on rails 2.1 thus following advice is fully operational],... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14530/"
] | I have a few models that need to have custom find conditions placed on them. For example, if I have a Contact model, every time Contact.find is called, I want to restrict the contacts returned that only belong to the Account in use.
I found this via Google (which I've customized a little):
```
def self.find(*args)
with_scope(:find => { :conditions => "account_id = #{$account.id}" }) do
super(*args)
end
end
```
This works great, except for a few occasions where account\_id is ambiguous so I adapted it to:
```
def self.find(*args)
with_scope(:find => { :conditions => "#{self.to_s.downcase.pluralize}.account_id = #{$account.id}" }) do
super(*args)
end
end
```
This also works great, however, I want it to be DRY. Now I have a few different models that I want this kind of function to be used. What is the best way to do this?
When you answer, please include the code to help our minds grasp the metaprogramming Ruby-fu.
(I'm using Rails v2.1) | You don't tell us which version of rails you are using [edit - it is on rails 2.1 thus following advice is fully operational], but I would recommand you use the following form instead of overloading find yourself :
```
account.contacts.find(...)
```
this will automatically wrap the find in a scope where the user clause is included (since you have the account\_id I assume you have the account somewhere close)
I suggest you check the following resources on scopes
* <http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality>
(this is not edge anymore :) )
* <http://ryandaigle.com/articles/2008/8/20/named-scope-it-s-not-just-for-conditions-ya-know> |
80,427 | <p>Code I have:</p>
<pre><code>cell_val = CStr(Nz(fld.value, ""))
Dim iter As Long
For iter = 0 To Len(cell_val) - 1 Step 1
If Asc(Mid(cell_val, iter, 1)) > 127 Then
addlog "Export contains ascii character > 127"
End If
Next iter
</code></pre>
<p>This code doesn't work. Anyone know how to do this? I've simply got no idea with VB or VBA.</p>
| [
{
"answer_id": 80457,
"author": "jan.vdbergh",
"author_id": 9540,
"author_profile": "https://Stackoverflow.com/users/9540",
"pm_score": 5,
"selected": true,
"text": "<p>I believe your problem is that in VBA string indexes start at 1 and not at 0. Try the following:</p>\n\n<pre><code>For ... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/924607/"
] | Code I have:
```
cell_val = CStr(Nz(fld.value, ""))
Dim iter As Long
For iter = 0 To Len(cell_val) - 1 Step 1
If Asc(Mid(cell_val, iter, 1)) > 127 Then
addlog "Export contains ascii character > 127"
End If
Next iter
```
This code doesn't work. Anyone know how to do this? I've simply got no idea with VB or VBA. | I believe your problem is that in VBA string indexes start at 1 and not at 0. Try the following:
```
For iter = 1 To Len(cell_val)
If Asc(Mid(cell_val, iter, 1)) > 127 Then
addlog "Export contains ascii character > 127"
End If
Next
``` |
80,476 | <p>I need to concatenate two <code>String</code> arrays in Java.</p>
<pre><code>void f(String[] first, String[] second) {
String[] both = ???
}
</code></pre>
<p>Which is the easiest way to do this?</p>
| [
{
"answer_id": 80503,
"author": "jeannicolas",
"author_id": 14981,
"author_profile": "https://Stackoverflow.com/users/14981",
"pm_score": 10,
"selected": false,
"text": "<p>Here's a simple method that will concatenate two arrays and return the result:</p>\n\n<pre><code>public <T> T... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2948/"
] | I need to concatenate two `String` arrays in Java.
```
void f(String[] first, String[] second) {
String[] both = ???
}
```
Which is the easiest way to do this? | Here's a simple method that will concatenate two arrays and return the result:
```
public <T> T[] concatenate(T[] a, T[] b) {
int aLen = a.length;
int bLen = b.length;
@SuppressWarnings("unchecked")
T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
```
Note that it will not work with primitive data types, only with object types.
The following slightly more complicated version works with both object and primitive arrays. It does this by using `T` instead of `T[]` as the argument type.
It also makes it possible to concatenate arrays of two different types by picking the most general type as the component type of the result.
```
public static <T> T concatenate(T a, T b) {
if (!a.getClass().isArray() || !b.getClass().isArray()) {
throw new IllegalArgumentException();
}
Class<?> resCompType;
Class<?> aCompType = a.getClass().getComponentType();
Class<?> bCompType = b.getClass().getComponentType();
if (aCompType.isAssignableFrom(bCompType)) {
resCompType = aCompType;
} else if (bCompType.isAssignableFrom(aCompType)) {
resCompType = bCompType;
} else {
throw new IllegalArgumentException();
}
int aLen = Array.getLength(a);
int bLen = Array.getLength(b);
@SuppressWarnings("unchecked")
T result = (T) Array.newInstance(resCompType, aLen + bLen);
System.arraycopy(a, 0, result, 0, aLen);
System.arraycopy(b, 0, result, aLen, bLen);
return result;
}
```
Here is an example:
```
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 }));
Assert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f }));
``` |
80,486 | <p>I need to know how to turn on Code Coverage when running TFS builds on a solution with a .testrunconfig file. </p>
<p>There is an option in the testrunconfig file that is for code coverage, but when running a TFS build there is no code coverage results.</p>
<p>I am running my tests using the *Tests.dll mask and NOT using Test Lists (.vsmdi).</p>
| [
{
"answer_id": 80600,
"author": "Martin Woodward",
"author_id": 6438,
"author_profile": "https://Stackoverflow.com/users/6438",
"pm_score": 5,
"selected": true,
"text": "<p>How are you running the tests? Are you using a .vsmdi file or just specifying that you run all tests in *Tests.dll... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5132/"
] | I need to know how to turn on Code Coverage when running TFS builds on a solution with a .testrunconfig file.
There is an option in the testrunconfig file that is for code coverage, but when running a TFS build there is no code coverage results.
I am running my tests using the \*Tests.dll mask and NOT using Test Lists (.vsmdi). | How are you running the tests? Are you using a .vsmdi file or just specifying that you run all tests in \*Tests.dll assemblies?
If it is the latter and you are using TFS 2008, then you need to add the following to the and of the first PropertyGroup in your TFSBuild.proj file for the build.
```
<RunConfigFile>$(SolutionRoot)\TestRunConfig.testrunconfig</RunConfigFile>
```
This points the build at your .testrunconfig so it can pick up the instructions to run code coverage. |
80,493 | <p>In C, using the standard Windows API, what is the best way to read an unformatted disk? Specifically, I have an <a href="http://en.wikipedia.org/wiki/MultiMediaCard" rel="nofollow noreferrer">MMC</a> or <a href="http://en.wikipedia.org/wiki/Secure_Digital_card" rel="nofollow noreferrer">SD card</a> with data, but no file system (not FAT16, not FAT32, just raw data). If there was a simple way to open the entire card for byte by byte binary access, that would be great.</p>
<p>Thanks!</p>
| [
{
"answer_id": 80533,
"author": "Kasprzol",
"author_id": 5957,
"author_profile": "https://Stackoverflow.com/users/5957",
"pm_score": 1,
"selected": false,
"text": "<p>You have to open the device file with <a href=\"http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx\" rel=\"nofo... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3175/"
] | In C, using the standard Windows API, what is the best way to read an unformatted disk? Specifically, I have an [MMC](http://en.wikipedia.org/wiki/MultiMediaCard) or [SD card](http://en.wikipedia.org/wiki/Secure_Digital_card) with data, but no file system (not FAT16, not FAT32, just raw data). If there was a simple way to open the entire card for byte by byte binary access, that would be great.
Thanks! | I would go with
```
HANDLE drive = CreateFile(_T("\\.\PhysicalDrive0"), GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
// error handling
DWORD br = 0;
DISK_GEOMETRY dg;
DeviceIOControl(drive, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0, &dg, sizeof(dg), &br, 0);
//
LARGE_INTEGER pos;
pos.QuadPart = static_cast<LONGLONG>(sectorToRead) * dg.BytesPerSector;
SetFilePointerEx(drive, pos, 0, FILE_BEGIN);
const bool success = ReadFile(drive, sectorData, dg.BytesPerSector, &br) && br == dg.BytesPerSector;
//
CloseHandle(drive);
```
Please note that in order to verify that you've successfully read a sector you must verify that the read byte count corresponds to the number of bytes you wanted to read, i.e. in my experience ReadFile() on a physical disk can return TRUE even when no bytes are read (or maybe I just have a buggy driver).
The problem that remains is to determine your drive number (0 as is used in my example refers to C: which is probably not what you want). I don't know how to do that, but if you only have one drive connected which is not formatted, it ought to be possible by calling opening each PhysicalDrive in order and calling DeviceIOControl() with `IOCTL_DISK_GET_DRIVE_LAYOUT_EX` as a command:
```
DRIVE_LAYOUT_INFORMATION_EX dl;
DeviceIOControl(drive, IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, 0, &dl, sizeof(dl), &br, 0);
if(dl.PartitionStyle == PARTITION_STYLE_RAW)
{
// found correct disk
}
```
But that's just a guess. |
80,541 | <p>The title is pretty much self explanatory. Given two dates what is the best way of finding the number of week days using PHP? Week days being Monday to Friday.</p>
<p>For instance, how would I find out that there are 10 week days in between <code>31/08/2008</code> and <code>13/09/2008</code>?</p>
| [
{
"answer_id": 80553,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 0,
"selected": false,
"text": "<p>One way would be to convert the dates to unix timestamps using strtotime(...), subtracting the results and div'ing with 86... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131/"
] | The title is pretty much self explanatory. Given two dates what is the best way of finding the number of week days using PHP? Week days being Monday to Friday.
For instance, how would I find out that there are 10 week days in between `31/08/2008` and `13/09/2008`? | ```
$datefrom = strtotime($datefrom, 0);
$dateto = strtotime($dateto, 0);
$difference = $dateto - $datefrom;
$days_difference = floor($difference / 86400);
$weeks_difference = floor($days_difference / 7); // Complete weeks
$first_day = date("w", $datefrom);
$days_remainder = floor($days_difference % 7);
$odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
if ($odd_days > 7) { // Sunday
$days_remainder--;
}
if ($odd_days > 6) { // Saturday
$days_remainder--;
}
$datediff = ($weeks_difference * 5) + $days_remainder;
```
From here: <http://www.addedbytes.com/php/php-datediff-function/> |
80,592 | <pre><code>public class Test {
public static void main(String[] args) {
}
}
class Outer {
void aMethod() {
class MethodLocalInner {
void bMethod() {
System.out.println("Inside method-local bMethod");
}
}
}
}
</code></pre>
<p>Can someone tell me how to print the message from <code>bMethod</code>?</p>
| [
{
"answer_id": 80615,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>You can only instantiate <code>MethodLocalInner</code> within <code>aMethod</code>. So do </p>\n\n<pre><code>void aMethod() {... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
] | ```
public class Test {
public static void main(String[] args) {
}
}
class Outer {
void aMethod() {
class MethodLocalInner {
void bMethod() {
System.out.println("Inside method-local bMethod");
}
}
}
}
```
Can someone tell me how to print the message from `bMethod`? | You can only instantiate `MethodLocalInner` within `aMethod`. So do
```
void aMethod() {
class MethodLocalInner {
void bMethod() {
System.out.println("Inside method-local bMethod");
}
}
MethodLocalInner foo = new MethodLocalInner(); // Default Constructor
foo.bMethod();
}
``` |
80,593 | <p>I have a FlowDocument in a standard WPF application window where I have some text, and in this text some hyperlinks and buttons.</p>
<p>The problem is, if I put this FlowDocument inside anything <strong>except</strong> a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.flowdocumentpageviewer.aspx" rel="nofollow noreferrer">FlowDocumentPageViewer</a> the hyperlinks and buttons are disabled ("grayed out").</p>
<pre><code><FlowDocumentScrollViewer>
<FlowDocument>
<Paragraph>
Hello, World!
<Hyperlink NavigateUri="some-uri">click me</Hyperlink>
<Button Click="myButton_Click" Content="Click me too!" />
</Paragraph>
</FlowDocument>
</FlowDocumentScrollViewer>
</code></pre>
<p>The above will work and the link will be clickable. However, I don't want the full pageviewer thing since it will show navigation buttons (back/forward) zoom and it also has a weird column behavior.</p>
<p>I want it in a simple <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.flowdocumentscrollviewer.aspx" rel="nofollow noreferrer">FlowDocumentScrollViewer</a> (or anything else that just displays the text without additional fuzz).</p>
<p><strong>EDIT:</strong>
It's not only hyperlinks that is the problem. <em>Any</em> control, like Button, ListBox, ComboBox - anything that the user can interact with - is "grayed out" regardless of the IsEnabled properties if the FlowDocument is inside a FlowDocumentScrollViewer.</p>
<p><strong>EDIT2:</strong>
Alright, it must have been a mistake or something from my end, because I ended up rewriting the control and now it works. I guess there was some sort if IsEnabled=False somewhere in the visual tree that caused this.</p>
| [
{
"answer_id": 80757,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 0,
"selected": false,
"text": "<p>I am wondering whether you expecing some thing like this?</p>\n\n<pre><code><TextBlock>\n<Hyperlink>\n <... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8521/"
] | I have a FlowDocument in a standard WPF application window where I have some text, and in this text some hyperlinks and buttons.
The problem is, if I put this FlowDocument inside anything **except** a [FlowDocumentPageViewer](http://msdn.microsoft.com/en-us/library/system.windows.controls.flowdocumentpageviewer.aspx) the hyperlinks and buttons are disabled ("grayed out").
```
<FlowDocumentScrollViewer>
<FlowDocument>
<Paragraph>
Hello, World!
<Hyperlink NavigateUri="some-uri">click me</Hyperlink>
<Button Click="myButton_Click" Content="Click me too!" />
</Paragraph>
</FlowDocument>
</FlowDocumentScrollViewer>
```
The above will work and the link will be clickable. However, I don't want the full pageviewer thing since it will show navigation buttons (back/forward) zoom and it also has a weird column behavior.
I want it in a simple [FlowDocumentScrollViewer](http://msdn.microsoft.com/en-us/library/system.windows.controls.flowdocumentscrollviewer.aspx) (or anything else that just displays the text without additional fuzz).
**EDIT:**
It's not only hyperlinks that is the problem. *Any* control, like Button, ListBox, ComboBox - anything that the user can interact with - is "grayed out" regardless of the IsEnabled properties if the FlowDocument is inside a FlowDocumentScrollViewer.
**EDIT2:**
Alright, it must have been a mistake or something from my end, because I ended up rewriting the control and now it works. I guess there was some sort if IsEnabled=False somewhere in the visual tree that caused this. | I'm using a FlowDocumentScrollViewer for my about box:
```
<FlowDocumentScrollViewer VerticalScrollBarVisibility="Auto">
<FlowDocument>
<Paragraph>
<!-- ... -->
```
I don't have any of the controls or issues you mention. |
80,609 | <p>I need to "merge" two XML documents, overwriting the overlapsed attributes and elements. For instance if I have <strong>document1</strong>:</p>
<pre><code><mapping>
<key value="assigned">
<a/>
</key>
<whatever attribute="x">
<k/>
<j/>
</whatever>
</mapping>
</code></pre>
<p>and <strong>document2</strong>:</p>
<pre><code><mapping>
<key value="identity">
<a/>
<b/>
</key>
</mapping>
</code></pre>
<p>I want to merge the two like this:</p>
<pre><code><mapping>
<key value="identity">
<a/>
<b/>
</key>
<whatever attribute="x">
<k/>
<j/>
</whatever>
</mapping>
</code></pre>
<p>I prefer <strong>Java</strong> or <strong>XSLT</strong>-based solutions, <strong>ant</strong> will do fine, but if there's an easy way to do that in <strong>Rake</strong>, <strong>Ruby</strong> or <strong>Python</strong> please don't be shy :-)</p>
<p><strong>EDIT:</strong> actually I find I'd rather use an automated tool/script, even <a href="http://web.archive.org/web/20100818203850/http://stackoverflow.com:80/questions/58640/great-programming-quotes" rel="nofollow noreferrer">writing it by myself</a>, because manually merging some 30 XML files is a bit unwieldy... :-(</p>
| [
{
"answer_id": 80656,
"author": "moobaa",
"author_id": 3569,
"author_profile": "https://Stackoverflow.com/users/3569",
"pm_score": 1,
"selected": false,
"text": "<p>Unsure as to whether you want to do this programatically or not.</p>\n\n<p>Edit: Ah, I posted that before the Edit. Don't I... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4690/"
] | I need to "merge" two XML documents, overwriting the overlapsed attributes and elements. For instance if I have **document1**:
```
<mapping>
<key value="assigned">
<a/>
</key>
<whatever attribute="x">
<k/>
<j/>
</whatever>
</mapping>
```
and **document2**:
```
<mapping>
<key value="identity">
<a/>
<b/>
</key>
</mapping>
```
I want to merge the two like this:
```
<mapping>
<key value="identity">
<a/>
<b/>
</key>
<whatever attribute="x">
<k/>
<j/>
</whatever>
</mapping>
```
I prefer **Java** or **XSLT**-based solutions, **ant** will do fine, but if there's an easy way to do that in **Rake**, **Ruby** or **Python** please don't be shy :-)
**EDIT:** actually I find I'd rather use an automated tool/script, even [writing it by myself](http://web.archive.org/web/20100818203850/http://stackoverflow.com:80/questions/58640/great-programming-quotes), because manually merging some 30 XML files is a bit unwieldy... :-( | If you like XSLT, there's a nice merge script I've used before at:
[Oliver's XSLT page](http://web.archive.org/web/20160809092524/http://www2.informatik.hu-berlin.de/~obecker/XSLT/) |
80,619 | <p>While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere.</p>
<p>This led me to think about the best way to group 'helper' functions together. The Java/C# way would be to use a class of static functions with a private constructor, e.g.:</p>
<pre><code>class Helper
{
private:
Helper() { }
public:
static int HelperFunc1();
static int HelperFunc2();
};
</code></pre>
<p>However, being C++ you could also use a namespace:</p>
<pre><code>namespace Helper
{
int HelperFunc1();
int HelperFunc2();
}
</code></pre>
<p>In most cases I think I would prefer the namespace approach but I wanted to know what the pros and cons of each approach are. If used the class approach for example, would there be any overheads?</p>
| [
{
"answer_id": 80636,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 2,
"selected": false,
"text": "<p>The main advantage to using a namespace is that you can reopen it and add more stuff later, you can't do that with a... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] | While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere.
This led me to think about the best way to group 'helper' functions together. The Java/C# way would be to use a class of static functions with a private constructor, e.g.:
```
class Helper
{
private:
Helper() { }
public:
static int HelperFunc1();
static int HelperFunc2();
};
```
However, being C++ you could also use a namespace:
```
namespace Helper
{
int HelperFunc1();
int HelperFunc2();
}
```
In most cases I think I would prefer the namespace approach but I wanted to know what the pros and cons of each approach are. If used the class approach for example, would there be any overheads? | Overhead is not an issue, namespaces have some advantages though
* You can reopen a namespace in another header, grouping things more logically while
keeping compile dependencies low
* You can use namespace aliasing to your advantage
(debug/release, platform specific helpers, ....)
e.g. I've done stuff like
```
namespace LittleEndianHelper {
void Function();
}
namespace BigEndianHelper {
void Function();
}
#if powerpc
namespace Helper = BigEndianHelper;
#elif intel
namespace Helper = LittleEndianHelper;
#endif
``` |
80,650 | <p>How do I register a custom protocol with Windows so that when clicking a link in an email or on a web page my application is opened and the parameters from the URL are passed to it?</p>
| [
{
"answer_id": 81954,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 5,
"selected": false,
"text": "<p>The MSDN link is nice, but the security information there isn't complete. The handler registration should contain \"%1\... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2189521/"
] | How do I register a custom protocol with Windows so that when clicking a link in an email or on a web page my application is opened and the parameters from the URL are passed to it? | 1. Go to `Start` then in `Find` type `regedit` -> it should open Registry editor
2. Click `Right Mouse` on `HKEY_CLASSES_ROOT` then `New` -> `Key`
[](https://i.stack.imgur.com/9boI6.png)
3. In the Key give the lowercase name by which you want urls to be called (in my case it will be `testus://sdfsdfsdf`) then Click `Right Mouse` on `testus` -> then `New` -> `String Value` and add `URL Protocol` without value.
[](https://i.stack.imgur.com/4wLev.png)
4. Then add more entries like you did with protocol ( `Right Mouse` `New` -> `Key` ) and create hierarchy like `testus` -> `shell` -> `open` -> `command` and inside `command` change `(Default)` to the path where `.exe` you want to launch is, if you want to pass parameters to your exe then wrap path to exe in `""` and add `"%1"` to look like: `"c:\testing\test.exe" "%1"`
[](https://i.stack.imgur.com/VbhsZ.png)
5. To test if it works go to Internet Explorer (not Chrome or Firefox) and enter `testus:have_you_seen_this_man` this should fire your `.exe` (give you some prompts that you want to do this - say Yes) and pass into args `testus://have_you_seen_this_man`.
Here's sample console app to test:
```
using System;
namespace Testing
{
class Program
{
static void Main(string[] args)
{
if (args!= null && args.Length > 0)
Console.WriteLine(args[0]);
Console.ReadKey();
}
}
}
```
Hope this saves you some time. |
80,653 | <p>I may be wrong, but if you are working with SmtpClient.SendAsync in ASP.NET
2.0 and it throws an exception, the thread processing the request waits
indefinitely for the operation to complete.</p>
<p>To reproduce this problem, simply use an invalid SMTP address for the host
that could not be resolved when sending an email.</p>
<p>Note that you should set Page.Async = true to use SendAsync.</p>
<p>If Page.Async is set to false and Send throws an exception the thread
does not block, and the page is processed correctly.</p>
<p>TIA.</p>
| [
{
"answer_id": 80887,
"author": "bzlm",
"author_id": 7724,
"author_profile": "https://Stackoverflow.com/users/7724",
"pm_score": 2,
"selected": false,
"text": "<p><strike></p>\n\n<blockquote>\n <p>Note that you should set Page.Async = true to use SendAsync.</p>\n</blockquote>\n\n<p>Plea... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15186/"
] | I may be wrong, but if you are working with SmtpClient.SendAsync in ASP.NET
2.0 and it throws an exception, the thread processing the request waits
indefinitely for the operation to complete.
To reproduce this problem, simply use an invalid SMTP address for the host
that could not be resolved when sending an email.
Note that you should set Page.Async = true to use SendAsync.
If Page.Async is set to false and Send throws an exception the thread
does not block, and the page is processed correctly.
TIA. | >
> Note that you should set Page.Async = true to use SendAsync.
>
>
>
Please explain the rationale behind this. Misunderstanding what Page.Async does may be the cause of your problems.
Sorry, I was unable to get an example working that reproduced the problem.
See <http://msdn.microsoft.com/en-us/magazine/cc163725.aspx> (WICKED CODE: Asynchronous Pages in ASP.NET 2.0)
**EDIT:** Looking at your code example, I can see that you're not using `RegisterAsyncTask()` and the `PageAsyncTask` class. I think you must do this when executing asynchronous tasks on a Page where `@Async` is set to true. The example from MSDN Magazine looks like this:
```
protected void Page_Load(object sender, EventArgs e)
{
PageAsyncTask task = new PageAsyncTask(
new BeginEventHandler(BeginAsyncOperation),
new EndEventHandler(EndAsyncOperation),
new EndEventHandler(TimeoutAsyncOperation),
null
);
RegisterAsyncTask(task);
}
```
Inside `BeginAsyncOperation`, then, should you send a mail asynchronously. |
80,657 | <p>In the process of learning <a href="https://en.wikipedia.org/wiki/TinyOS" rel="nofollow noreferrer">TinyOS</a> I have discovered that I am totally clueless about makefiles.</p>
<p>There are many optional compile time features that can be used by way of declaring preprocessor variables.</p>
<p>To use them you have to do things like:</p>
<p><code>CFLAGS="-DPACKET_LINK"</code> this enables a certain feature.</p>
<p>and</p>
<p><code>CFLAGS="-DPACKET_LINK" "-DLOW_POWER"</code> enables two features.</p>
<p>Can someone dissect these lines for me and tell me whats going on? Not in terms of TinyOS, but in terms of makefiles!</p>
| [
{
"answer_id": 80689,
"author": "Ilya",
"author_id": 6807,
"author_profile": "https://Stackoverflow.com/users/6807",
"pm_score": 3,
"selected": false,
"text": "<p>Somewhere in the makefile the CFLAG will be used in compilation line like this:<br>\n<code>$(CC) $(CFLAGS) $(C_INCLUDES) $<... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In the process of learning [TinyOS](https://en.wikipedia.org/wiki/TinyOS) I have discovered that I am totally clueless about makefiles.
There are many optional compile time features that can be used by way of declaring preprocessor variables.
To use them you have to do things like:
`CFLAGS="-DPACKET_LINK"` this enables a certain feature.
and
`CFLAGS="-DPACKET_LINK" "-DLOW_POWER"` enables two features.
Can someone dissect these lines for me and tell me whats going on? Not in terms of TinyOS, but in terms of makefiles! | CFLAGS is a variable that is most commonly used to add arguments to the compiler. In this case, it define macros.
So the `-DPACKET_LINK` is the equivalent of putting `#define PACKET_LINK 1` at the top of all .c and .h files in your project. Most likely, you have code inside your project that looks if these macros are defined and does something depending on that:
```
#ifdef PACKET_LINK
// This code will be ignored if PACKET_LINK is not defined
do_packet_link_stuff();
#endif
#ifdef LOW_POWER
// This code will be ignored if LOW_POWER is not defined
handle_powersaving_functions();
#endif
```
If you look further down in your makefile, you should see that `$(CFLAGS)` is probably used like:
```
$(CC) $(CFLAGS) ...some-more-arguments...
``` |
80,677 | <p>One of the best tips for using vim that I have learned so far has been that one can press <kbd>Ctrl</kbd>+<kbd>C</kbd> or <kbd>Ctrl</kbd>+<kbd>[</kbd> instead of the <kbd>Esc</kbd> key. However I use a dvorak keyboard so <kbd>Ctrl</kbd>+<kbd>[</kbd> is a little out of reach for me as well so I mostly use <kbd>Ctrl</kbd>+<kbd>C</kbd>. Now I've read somewhere that these two key combinations don't actually have exactly the same behaviour and that it is better to use <kbd>Ctrl</kbd>+<kbd>[</kbd>. I haven't come across any problems so far though so I'd like to know what exactly is the difference between the two?</p>
| [
{
"answer_id": 80761,
"author": "jeannicolas",
"author_id": 14981,
"author_profile": "https://Stackoverflow.com/users/14981",
"pm_score": 4,
"selected": false,
"text": "<p>According to Vim's documentation, <kbd>Ctrl</kbd>+<kbd>C</kbd> does not check for abbreviations and does not trigger... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13060/"
] | One of the best tips for using vim that I have learned so far has been that one can press `Ctrl`+`C` or `Ctrl`+`[` instead of the `Esc` key. However I use a dvorak keyboard so `Ctrl`+`[` is a little out of reach for me as well so I mostly use `Ctrl`+`C`. Now I've read somewhere that these two key combinations don't actually have exactly the same behaviour and that it is better to use `Ctrl`+`[`. I haven't come across any problems so far though so I'd like to know what exactly is the difference between the two? | According to Vim's documentation, `Ctrl`+`C` does not check for abbreviations and does not trigger the `InsertLeave` autocommand event while `Ctrl`+`[` does.
One option is to use the following to remap `Ctrl`+`C`
```
inoremap <C-c> <Esc><Esc>
``` |
80,691 | <p>I've started refactoring some legacy code recently and came across two functions for drawing a coordinate grid, the problem is that these functions differ only in orthogonal variables they treat, something like that</p>
<pre><code>void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int x = x0; x < x1; x += step)
{
MoveToEx(dc, x, y0, NULL);
LineTo(dc, x, y1);
}
}
void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int y = y0; y < y1; y += step)
{
MoveToEx(dc, x0, y, NULL);
LineTo(dc, x1, y);
}
}
</code></pre>
<p>So if I decide to add some fancy stuff, like antialiasing or merely change drawing pencil or whatever I'll have to put the same code in both of them and it's code duplication and it's bad we all know why.</p>
<p>My question is how would you rewrite these two functions into a single one to avoid this problem?</p>
| [
{
"answer_id": 80722,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my own solution</p>\n\n<pre><code>\nclass CoordGenerator\n{\npublic:\n CoordGenerator(int _from, int _to, int _st... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007/"
] | I've started refactoring some legacy code recently and came across two functions for drawing a coordinate grid, the problem is that these functions differ only in orthogonal variables they treat, something like that
```
void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int x = x0; x < x1; x += step)
{
MoveToEx(dc, x, y0, NULL);
LineTo(dc, x, y1);
}
}
void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int y = y0; y < y1; y += step)
{
MoveToEx(dc, x0, y, NULL);
LineTo(dc, x1, y);
}
}
```
So if I decide to add some fancy stuff, like antialiasing or merely change drawing pencil or whatever I'll have to put the same code in both of them and it's code duplication and it's bad we all know why.
My question is how would you rewrite these two functions into a single one to avoid this problem? | Drawing a line is simply joining two points, and drawing a scaling incrementing (x0,y0) and(x1,y1) in a particular direction, through X, and/or through Y.
This boils down to, in the scale case, which direction(s) stepping occurs (maybe both directions for fun).
```
template< int XIncrement, YIncrement >
struct DrawScale
{
void operator()(HDC dc, int step, int x0, int x1, int y0, int y1)
{
const int deltaX = XIncrement*step;
const int deltaY = YIncrement*step;
const int ymax = y1;
const int xmax = x1;
while( x0 < xmax && y0 < ymax )
{
MoveToEx(dc, x0, y0, NULL);
LineTo(dc, x1, y1);
x0 += deltaX;
x1 += deltaX;
y0 += deltaY;
y1 += deltaY;
}
}
};
typedef DrawScale< 1, 0 > DrawScaleX;
typedef DrawScale< 0, 1 > DrawScaleY;
```
The template will do its job: at compile time the compiler will remove all the null statements i.e. deltaX or deltaY is 0 regarding which function is called and half of the code goes away in each functor.
You can add you anti-alias, pencil stuff inside this uniq function and get the code properly generated generated by the compiler.
This is cut and paste on steroids ;-)
-- ppi |
80,692 | <pre><code>public static Logger getLogger() {
final Throwable t = new Throwable();
final StackTraceElement methodCaller = t.getStackTrace()[1];
final Logger logger = Logger.getLogger(methodCaller.getClassName());
logger.setLevel(ResourceManager.LOGLEVEL);
return logger;
}
</code></pre>
<p>This method would return a logger that knows the class it's logging for.
Any ideas against it?</p>
<p>Many years later: <a href="https://github.com/yanchenko/droidparts/blob/master/droidparts/src/org/droidparts/util/L.java" rel="noreferrer">https://github.com/yanchenko/droidparts/blob/master/droidparts/src/org/droidparts/util/L.java</a></p>
| [
{
"answer_id": 80754,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 2,
"selected": false,
"text": "<p>You could of course just use Log4J with the appropriate pattern layout:</p>\n\n<blockquote>\n <p>For example, for the class n... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15187/"
] | ```
public static Logger getLogger() {
final Throwable t = new Throwable();
final StackTraceElement methodCaller = t.getStackTrace()[1];
final Logger logger = Logger.getLogger(methodCaller.getClassName());
logger.setLevel(ResourceManager.LOGLEVEL);
return logger;
}
```
This method would return a logger that knows the class it's logging for.
Any ideas against it?
Many years later: <https://github.com/yanchenko/droidparts/blob/master/droidparts/src/org/droidparts/util/L.java> | I guess it adds a lot of overhead for every class. Every class has to be 'looked up'. You create new Throwable objects to do that... These throwables don't come for free. |
80,706 | <p>I want to find 2<sup>nd</sup>, 3<sup>rd</sup>, ... n<sup>th</sup> maximum value of a column.</p>
| [
{
"answer_id": 80720,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 5,
"selected": true,
"text": "<p>You could sort the column into descending format and then just obtain the value from the nth row.</p>\n\n<p>EDIT::</p>\n\n<p>Up... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15181/"
] | I want to find 2nd, 3rd, ... nth maximum value of a column. | You could sort the column into descending format and then just obtain the value from the nth row.
EDIT::
Updated as per comment request. ***WARNING*** completely untested!
```
SELECT DOB FROM (SELECT DOB FROM USERS ORDER BY DOB DESC) WHERE ROWID = 6
```
Something like the above should work for Oracle ... you might have to get the syntax right first! |
80,726 | <pre><code>> jruby -S gem install warbler
JRuby limited openssl loaded. gem install jruby-openssl for full support.
Successfully installed warbler-0.9.11
1 gem installed
Installing ri documentation for warbler-0.9.11...
Installing RDoc documentation for warbler-0.9.11...
> jruby -S warble
<snip>/jruby-1.1.4/bin/warble:1: undefined method `warble' for JRuby::Commands:Class (NoMethodError)
</code></pre>
<p>Any ideas why I don't get a warbler command in my jruby bin directory?</p>
<p>Thanks,</p>
| [
{
"answer_id": 92779,
"author": "Andrew Burgess",
"author_id": 12096,
"author_profile": "https://Stackoverflow.com/users/12096",
"pm_score": 1,
"selected": false,
"text": "<p>The only thing that I can really think of is to ensure that your instance of JRuby is using gems by default. I r... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14952/"
] | ```
> jruby -S gem install warbler
JRuby limited openssl loaded. gem install jruby-openssl for full support.
Successfully installed warbler-0.9.11
1 gem installed
Installing ri documentation for warbler-0.9.11...
Installing RDoc documentation for warbler-0.9.11...
> jruby -S warble
<snip>/jruby-1.1.4/bin/warble:1: undefined method `warble' for JRuby::Commands:Class (NoMethodError)
```
Any ideas why I don't get a warbler command in my jruby bin directory?
Thanks, | The only thing that I can really think of is to ensure that your instance of JRuby is using gems by default. I ran into that problem a few times when using gems where I would forget to either set the environmental variable or pass in the switch to Ruby. I don't know if things are different for JRuby though. |
80,766 | <p>I got a typed (not connected) dataset, and many records (binary seriliazed) created with this dataset.
I've added a property to one of the types, and I want to convert the old records with the new data set.
I know how to load them: providing custom binder for the BinaryFormatter with the old schema dll.
The question is how can I convert objects of the old type to objects of the new type - both types has the same name but the new one has one more property.</p>
| [
{
"answer_id": 81192,
"author": "paulwhit",
"author_id": 7301,
"author_profile": "https://Stackoverflow.com/users/7301",
"pm_score": 0,
"selected": false,
"text": "<p>Can you make the new class inherit from the old one? If so, maybe you can simply deserialize into the new one through cas... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I got a typed (not connected) dataset, and many records (binary seriliazed) created with this dataset.
I've added a property to one of the types, and I want to convert the old records with the new data set.
I know how to load them: providing custom binder for the BinaryFormatter with the old schema dll.
The question is how can I convert objects of the old type to objects of the new type - both types has the same name but the new one has one more property. | If the only difference between the existing dataset and the new one is an added field then you can "upgrade" them by writing out the old ones to XML and then reading that into the new ones. The value of the added field will be DBNull.
```
MyDataSet myDS = new MyDataSet();
MyDataSet.MyTableRow row1 = myDS.MyTable.NewMyTableRow();
row1.Name = "Brownie";
myDS.MyTable.Rows.Add(row1);
MyNewDataSet myNewDS = new MyNewDataSet();
using(MemoryStream ms = new MemoryStream()){
myDS.WriteXml(ms);
ms.Position = 0;
myNewDS.ReadXml(ms);
}
``` |
80,770 | <p>I have been reading a lot of XQuery tutorials on the website. Almost all of them are teaching me XQuery syntax. Let's say I have understood the XQuery syntax, how am I going to actually implement XQuery on my website?</p>
<p>For example, I have <strong>book.xml</strong>:</p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" ?>
<books>
<book>
<title>Doraemon</title>
<authorid>1</authorid>
</book>
<book>
<title>Ultraman</title>
<authorid>2</authorid>
</book>
</books>
</code></pre>
<p>Then, I have <strong>author.xml</strong></p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" ?>
<authors>
<author id="1">Mr A</author>
<author id="2">Mr B</author>
</authors>
</code></pre>
<p>I want to generate HTML which looks like following:</p>
<pre><code><table>
<tr> <td>Title</td> <td>Author</td> </tr>
<tr> <td>Doraemon</td> <td>Mr A</td> </tr>
<tr> <td>Ultraman</td> <td>Mr B</td> </tr>
</table>
</code></pre>
<p>Please show me some examples. Or any website that I can do reference. Thanks very much.</p>
| [
{
"answer_id": 82980,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code><table>\n<tr><td>Title<td><td>Author<td></tr>\n{\n let $authordoc := fn... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have been reading a lot of XQuery tutorials on the website. Almost all of them are teaching me XQuery syntax. Let's say I have understood the XQuery syntax, how am I going to actually implement XQuery on my website?
For example, I have **book.xml**:
```
<?xml version="1.0" encoding="iso-8859-1" ?>
<books>
<book>
<title>Doraemon</title>
<authorid>1</authorid>
</book>
<book>
<title>Ultraman</title>
<authorid>2</authorid>
</book>
</books>
```
Then, I have **author.xml**
```
<?xml version="1.0" encoding="iso-8859-1" ?>
<authors>
<author id="1">Mr A</author>
<author id="2">Mr B</author>
</authors>
```
I want to generate HTML which looks like following:
```
<table>
<tr> <td>Title</td> <td>Author</td> </tr>
<tr> <td>Doraemon</td> <td>Mr A</td> </tr>
<tr> <td>Ultraman</td> <td>Mr B</td> </tr>
</table>
```
Please show me some examples. Or any website that I can do reference. Thanks very much. | ```
(: file: titles.xqy :)
<table>
<tr><th>title</th><th>author</th></tr>
{
let $books-doc := doc("books.xml")
let $authors-doc := doc("authors.xml")
for $b in $books-doc//book,
$a in $authors-doc//author
where $a/@id = $b/authorid
return
<tr>
<td>{$b/title/text()}</td>
<td>{$a/text()}</td>
</tr>
}
``` |
80,787 | <p>Any ideas how to determine the number of active threads currently running in an <a href="https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ExecutorService.html" rel="noreferrer"><code>ExecutorService</code></a>?</p>
| [
{
"answer_id": 80809,
"author": "Daan",
"author_id": 197,
"author_profile": "https://Stackoverflow.com/users/197",
"pm_score": 7,
"selected": true,
"text": "<p>Use a <a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html\" rel=\"noreferrer\">ThreadPo... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8441/"
] | Any ideas how to determine the number of active threads currently running in an [`ExecutorService`](https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ExecutorService.html)? | Use a [ThreadPoolExecutor](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html) implementation and call [getActiveCount()](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#getActiveCount()) on it:
```
int getActiveCount()
// Returns the approximate number of threads that are actively executing tasks.
```
The ExecutorService interface does not provide a method for that, it depends on the implementation. |
80,788 | <p>I'm trying to get IKVM to build (see <a href="https://stackoverflow.com/questions/71599/how-to-get-ikvm-to-build-in-visual-studio-2008">this question</a>) but now have encountered a problem not having to do with IKVM so I'm opening up a new question:</p>
<p>When running nant on the IKVM directory with the Visual Studio 2008 Command Prompt (from the Start Menu), I get the following error:</p>
<blockquote>
<pre><code> ikvm-native-win32:
[cl] Compiling 2 files to C:\ikvm-0.36.0.11\native\Release'.
[cl] jni.c
[cl] os.c
[cl] C:\ikvm-0.36.0.11\native\os.c(25) : fatal error C1083: Cannot open include file: 'windows.h': No such
file or directory
[cl] Generating Code...
BUILD FAILED
C:\ikvm-0.36.0.11\native\native.build(17,10):
External Program Failed: cl (return code was 2)
</code></pre>
</blockquote>
<p>I have the Platform SDK installed. What am I missing? I'm sure it's something simple...</p>
<p><strong>Edit #1</strong> I just checked - I do have the directory containing windows.h on the Path.
<strong>Edit #2</strong> Found the answer (see my answer below): The directory containing windows.h needed to be in the "Include" path variable.</p>
| [
{
"answer_id": 81226,
"author": "Epaga",
"author_id": 6583,
"author_profile": "https://Stackoverflow.com/users/6583",
"pm_score": 4,
"selected": true,
"text": "<p>OK here is the answer I ended up finding: rather than being on the Path, the directory with windows.h (in my case, C:\\Progra... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] | I'm trying to get IKVM to build (see [this question](https://stackoverflow.com/questions/71599/how-to-get-ikvm-to-build-in-visual-studio-2008)) but now have encountered a problem not having to do with IKVM so I'm opening up a new question:
When running nant on the IKVM directory with the Visual Studio 2008 Command Prompt (from the Start Menu), I get the following error:
>
>
> ```
> ikvm-native-win32:
>
> [cl] Compiling 2 files to C:\ikvm-0.36.0.11\native\Release'.
>
> [cl] jni.c
> [cl] os.c
> [cl] C:\ikvm-0.36.0.11\native\os.c(25) : fatal error C1083: Cannot open include file: 'windows.h': No such
> file or directory
> [cl] Generating Code...
>
> BUILD FAILED
>
> C:\ikvm-0.36.0.11\native\native.build(17,10):
> External Program Failed: cl (return code was 2)
>
> ```
>
>
I have the Platform SDK installed. What am I missing? I'm sure it's something simple...
**Edit #1** I just checked - I do have the directory containing windows.h on the Path.
**Edit #2** Found the answer (see my answer below): The directory containing windows.h needed to be in the "Include" path variable. | OK here is the answer I ended up finding: rather than being on the Path, the directory with windows.h (in my case, C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include) needed to be set in the Include environment variable. |
80,801 | <p>If I have a large number of SQLite databases, all with the same schema, what is the best way to merge them together in order to perform a query on all databases? </p>
<p>I know it is possible to use <a href="http://www.sqlite.org/lang_attach.html" rel="noreferrer">ATTACH</a> to do this but it has <a href="http://www.sqlite.org/limits.html#max_attached" rel="noreferrer">a limit</a> of 32 and 64 databases depending on the memory system on the machine.</p>
| [
{
"answer_id": 80812,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>If you only need to do this merge operation once (to create a new bigger database), you could create a script/program that wi... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] | If I have a large number of SQLite databases, all with the same schema, what is the best way to merge them together in order to perform a query on all databases?
I know it is possible to use [ATTACH](http://www.sqlite.org/lang_attach.html) to do this but it has [a limit](http://www.sqlite.org/limits.html#max_attached) of 32 and 64 databases depending on the memory system on the machine. | To summarize from the [Nabble post](https://web.archive.org/web/20120615034014/http://sqlite.1065341.n5.nabble.com/Attempting-to-merge-large-databases-td39548.html) in DavidM's answer:
```
attach 'c:\test\b.db3' as toMerge;
BEGIN;
insert into AuditRecords select * from toMerge.AuditRecords;
COMMIT;
detach toMerge;
```
Repeat as needed.
*Note: added `detach toMerge;` as per mike's comment.* |
80,802 | <p>I've been wondering, is there a performance difference between using named functions and anonymous functions in Javascript? </p>
<pre><code>for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = function() {
// do something
};
}
</code></pre>
<p>vs</p>
<pre><code>function myEventHandler() {
// do something
}
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = myEventHandler;
}
</code></pre>
<p>The first is tidier since it doesn't clutter up your code with rarely-used functions, but does it matter that you're re-declaring that function multiple times?</p>
| [
{
"answer_id": 80823,
"author": "Tom Leys",
"author_id": 11440,
"author_profile": "https://Stackoverflow.com/users/11440",
"pm_score": 2,
"selected": false,
"text": "<p>As a general design principle, you should avoid implimenting the same code multiple times. Instead you should lift comm... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] | I've been wondering, is there a performance difference between using named functions and anonymous functions in Javascript?
```
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = function() {
// do something
};
}
```
vs
```
function myEventHandler() {
// do something
}
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = myEventHandler;
}
```
The first is tidier since it doesn't clutter up your code with rarely-used functions, but does it matter that you're re-declaring that function multiple times? | The performance problem here is the cost of creating a new function object at each iteration of the loop and not the fact that you use an anonymous function:
```
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = function() {
// do something
};
}
```
You are creating a thousand distinct function objects even though they have the same body of code and no binding to the lexical scope ([closure](http://www.google.com/search?q=javascript+closure)). The following seems faster, on the other hand, because it simply assigns the *same* function reference to the array elements throughout the loop:
```
function myEventHandler() {
// do something
}
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = myEventHandler;
}
```
If you were to create the anonymous function before entering the loop, then only assign references to it to the array elements while inside the loop, you will find that there is no performance or semantic difference whatsoever when compared to the named function version:
```
var handler = function() {
// do something
};
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = handler;
}
```
In short, there is no observable performance cost to using anonymous over named functions.
As an aside, it may appear from above that there is no difference between:
```
function myEventHandler() { /* ... */ }
```
and:
```
var myEventHandler = function() { /* ... */ }
```
The former is a *function declaration* whereas the latter is a variable assignment to an anonymous function. Although they may appear to have the same effect, JavaScript does treat them slightly differently. To understand the difference, I recommend reading, “[JavaScript function declaration ambiguity](http://www.dustindiaz.com/javascript-function-declaration-ambiguity/)”.
The actual execution time for any approach is largely going to be dictated by the browser's implementation of the compiler and runtime. For a complete comparison of modern browser performance, visit [the JS Perf site](http://jsperf.com/named-or-anonymous-functions/12) |
80,820 | <p>On a file path field, I want to capture the directory path like:</p>
<pre><code>textbox1.Text = directory path
</code></pre>
<p>Anyone?</p>
| [
{
"answer_id": 80824,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "<p>There is a FolderBrowserDialog class that you can use if you want the user to select a folder.</p>\n\n<p><a href=\"http://msd... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10385/"
] | On a file path field, I want to capture the directory path like:
```
textbox1.Text = directory path
```
Anyone? | Well I am using VS 2008 SP1. This all I need:
```
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog profilePath = new FolderBrowserDialog();
if (profilePath.ShowDialog() == DialogResult.OK)
{
profilePathTextBox.Text = profilePath.SelectedPath;
}
else
{
profilePathTextBox.Text = "Please Specify The Profile Path";
}
}
``` |
80,831 | <p>There is a <a href="http://support.microsoft.com/?scid=194627" rel="nofollow noreferrer">Microsoft knowledge base article</a> with sample code to open all mailboxes in a given information store. It works so far (requires a bit of <a href="http://blogs.msdn.com/jasonjoh/archive/2004/08/01/204585.aspx" rel="nofollow noreferrer">copy & pasting</a> on compilers newer than VC++ 6.0).</p>
<p>At one point it calls IExchangeManageStore::GetMailboxTable with the distinguished name of the information store. For the Exchange 2007 Trial Virtual Server image it has to look like this: </p>
<pre><code>"/o=Litware Inc/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=servers/cn=DC1".
</code></pre>
<p>Using <a href="http://www.dimastr.com/outspy/" rel="nofollow noreferrer">OutlookSpy</a> and clicking on IMsgStore and IExchangeManageStore reveals the desired string next to "Server DN:".</p>
<p>I want to avoid forcing the user to put this into a config file. So if OutlookSpy can do it, how can my application find out the distinguished name of the information store where the currently open mailbox is on?</p>
| [
{
"answer_id": 82342,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 0,
"selected": false,
"text": "<p>It'll be in Active Directory, so you'd use ADSI/LDAP to look at CN=Microsoft Exchange,CN=Services,CN=Configuration,DC... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4097/"
] | There is a [Microsoft knowledge base article](http://support.microsoft.com/?scid=194627) with sample code to open all mailboxes in a given information store. It works so far (requires a bit of [copy & pasting](http://blogs.msdn.com/jasonjoh/archive/2004/08/01/204585.aspx) on compilers newer than VC++ 6.0).
At one point it calls IExchangeManageStore::GetMailboxTable with the distinguished name of the information store. For the Exchange 2007 Trial Virtual Server image it has to look like this:
```
"/o=Litware Inc/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=servers/cn=DC1".
```
Using [OutlookSpy](http://www.dimastr.com/outspy/) and clicking on IMsgStore and IExchangeManageStore reveals the desired string next to "Server DN:".
I want to avoid forcing the user to put this into a config file. So if OutlookSpy can do it, how can my application find out the distinguished name of the information store where the currently open mailbox is on? | Thinking there must be a pure MAPI solution, I believe I've figured out how OutlookSpy does it.
The following code snippet, inserted after
```
printf("Created MAPI session\n");
```
in the example from [KB194627](http://support.microsoft.com/kb/194627), will show the *Server DN*.
```
LPPROFSECT lpProfSect;
hr = lpSess->OpenProfileSection((LPMAPIUID)pbGlobalProfileSectionGuid, NULL, 0, &lpProfSect);
if(SUCCEEDED(hr))
{
LPSPropValue lpPropValue;
hr = HrGetOneProp(lpProfSect, PR_PROFILE_HOME_SERVER_DN, &lpPropValue);
if(SUCCEEDED(hr))
{
printf("Server DN: %s\n", lpPropValue->Value.lpszA);
MAPIFreeBuffer(lpPropValue);
}
lpProfSect->Release();
}
```
**Update:**
There is the function *HrGetServerDN* in the [EDK 5.5 source code](http://www.microsoft.com/downloads/details.aspx?FamilyID=36a309c3-8c55-4476-8785-cafc59a2d075&DisplayLang=en), it extracts the *Server DN* from a given session's *PR\_EMS\_AB\_HOME\_MTA*. I'll try it if the other way turns out to be unreliable. |
80,846 | <p>I am trying to use Zend_Db_Select to write a select query that looks somewhat like this:</p>
<pre><code>SELECT * FROM bar WHERE a = 1 AND (b = 2 OR b = 3)
</code></pre>
<p>However, when using a combination of where() and orWhere(), it seems impossible to use condition grouping like the above.</p>
<p>Are there any native ways in Zend Framework to achieve the above (without writing the actual query?)</p>
| [
{
"answer_id": 80871,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>From <a href=\"http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.building.where\" rel=\"nofollow norefer... | 2008/09/17 | [
"https://Stackoverflow.com/questions/80846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11568/"
] | I am trying to use Zend\_Db\_Select to write a select query that looks somewhat like this:
```
SELECT * FROM bar WHERE a = 1 AND (b = 2 OR b = 3)
```
However, when using a combination of where() and orWhere(), it seems impossible to use condition grouping like the above.
Are there any native ways in Zend Framework to achieve the above (without writing the actual query?) | From [the manual](http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.building.where) (Example 11.61. Example of parenthesizing Boolean expressions)
```
// Build this query:
// SELECT product_id, product_name, price
// FROM "products"
// WHERE (price < 100.00 OR price > 500.00)
// AND (product_name = 'Apple')
$minimumPrice = 100;
$maximumPrice = 500;
$prod = 'Apple';
$select = $db->select()
->from('products',
array('product_id', 'product_name', 'price'))
->where("price < $minimumPrice OR price > $maximumPrice")
->where('product_name = ?', $prod);
``` |