Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have some very basic semaphore code that works great on Linux, but cannot for the life of me get it to run properly on OS X... It returns the oddest of results...
```
#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>
int main()
{
sem_t* test;
test = sem_open("test", O_CREAT, 0, 1);
int value;
sem_getvalue(test, &value);
printf("Semaphore initialized to %d\n", value);
}
```
Compiling this on OS X with g++ returns the following output:
```
iQudsi:Desktop mqudsi$ g++ test.cpp
iQudsi:Desktop mqudsi$ ./a.out
Semaphore initialized to -1881139893
```
Whereas on Ubuntu, I get the decidedly more-sane result:
```
iQudsi: Desktop mqudsi$ g++ test.cpp -lrt
iQudsi:Desktop mqudsi$ ./a.out
Semaphore initialized to 1
```
I've been at this for 3 hours straight, and cannot figure out why OS X is returning such bizarre results...
I've tried using file paths as the semaphore name, it didn't make a difference.
I'd appreciate any help I could get. | ```
$ g++ sem-testing.cc -Wall
$ ./a.out
sem_getvalue: Function not implemented
$ man sem_getvalue
No manual entry for sem_getvalue
```
You are using a function that is not currently implemented in Mac OS X, and the integer you are printing out contains the default data that the integer was initialised with which was probably random data that was still in memory. Had you zero'd it out, by setting it with `int value = 0;` you might have caught this mistake sooner.
This is the code I used (thanks to [bdonlan](https://stackoverflow.com/questions/871435/odd-incorrect-semaphore-behavior-on-os-x/871501#871501)):
```
#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>
int main()
{
sem_t* test;
test = sem_open("test", O_CREAT, 0, 1);
if (test == SEM_FAILED) {
perror("sem_open");
return 1;
}
int value;
if (sem_getvalue(test, &value)) {
perror("sem_getvalue");
return 1;
}
printf("Semaphore initialized to %d\n", value);
}
``` | Are you testing for errors? Try:
```
#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>
int main()
{
sem_t* test;
test = sem_open("test", O_CREAT, 0, 1);
if (test == SEM_FAILED) {
perror("sem_open");
return 1;
}
int value;
if (sem_getvalue(test, &value)) {
perror("sem_getvalue");
return 1;
}
printf("Semaphore initialized to %d\n", value);
}
``` | Odd/Incorrect sem_getvalue Semaphore Behavior on OS X | [
"",
"c++",
"macos",
"posix",
"mutex",
"semaphore",
""
] |
I'm starting to use Moq and I cannot figure out how to test the method **Execute** in the code below:
I have the following class:
```
public class MyObject {
private IDataReaderPlugin m_source;
private IDataWriterPlugin m_dest;
private string[] m_dummyTags = new string[] { "tag1", "tag2", "tag3"};
public void Execute(DateTime time)
{
DataCollection tags = m_source.SnapshotUtc(m_dummyTags, time);
//Doing some treatment on the values in tags
m_dest.Write(tags);
}
```
}
Another method is responsible to create and initialize IDataReaderPlugin and IDataWriterPlugin from information in a configuration file.
I want to test the method Execute. So, I need to mock **m\_source** and **m\_dest** and after I want to test the result sent to **m\_dest**.
How I can achieve this with Moq?
Thanks. | This should get you started:
```
DateTime myDate = DateTime.Now;
DataCollection tags = new DataCollection();
Mock<IDataReaderPlugin> dataReaderPlugin = new Mock<IDataWriterPlugin>();
dataReaderPlugin.Setup(drp => drp.SnapshotUtc(It.IsAny<string[]>(), myDate)).Returns(tags);
Mock<IDataWriterPlugin> dataWriterPlugin = new Mock<IDataWriterPlugin>();
dataWriterPlugin.Setup(dwp => dwp.Write(tags);
MyObject mo = new MyObject();
mo.Execute();
mock.Verify(foo => foo.Write(tags));
``` | ```
[Test]
public void ShouldWriteToMDest()
{
// Arrange
var mockDest = new Mock<IDataWriterPlugin>();
var mockSource = new Mock<IDataReaderPlugin>();
string[] m_dummyTags = new string[] { "tag1", "tag2", "tag3"};
mockSource.Setup(source => source.SnapshotUtc(m_dummyTags, It.IsAny<DateTime>()).Returns(/*whatever you need*/);
var myObj = new MyObject(mockSource.Object, mockDest.Object);
// Act
myObj.Execute(DateTime.Now);
// Assert
Assert.That(mockSource.Object.WhateverPropertyContainsOutput == /*Whatever you need */);
}
``` | Mocking a connection to a data source inside a function with Moq? | [
"",
"c#",
"unit-testing",
"moq",
""
] |
Which ORM will give me compile-tested queries?
Is linqtosql compile time tested?
---
### Edit:
Say I write a query that references a column named 'TotalSales'. I then rename the column in my database to `TotalSales2` (and any other config file like: Employee.cfg.xml in nHibernate).
When I compile the project, I want Visual Studio to tell me the column 'totalSales' doesn't exist and then I will go and change it. | There aren't any as far as I'm aware. They will often let you create a LINQ query that cannot be translated into SQL for example. Also, I am not aware of any compile time checking that your mappings map to your database correctly.
You can, and should in my opinion, perform all these checks within tests. Most ORMs make this easy to do. | I use [LLBLGen](http://www.llblgen.com) but it has to be "refreshed" when data model changes are made. I don't think you'll get an ORM that will AT COMPILE TIME check for modifications against the database. You're asking for quite a bit there. | Which ORM will give me compile-tested queries? | [
"",
"c#",
".net",
"orm",
""
] |
I have a dictionary of strings that i want the user to be able to add/remove info from then store it for them so it they can access it the next time the program restarts
I am unclear on how i can store a dictionary as a setting. I see that under system.collections.special there is a thing called a stringdictionary but ive read that SD are outdated and shouldn't be used.
also in the future i may have need to store a dictionary that is not strings only (int string)
how would you store a dictionary in the settings file for a .net application? | The simplest answer would be to use a row & column delimiter to convert your dictionary to a single string. Then you just need to store 1 string in the settings file. | You can use this class derived from StringDictionary. To be useful for application settings it implements IXmlSerializable.
Or you can use similar approach to implement your own XmlSerializable class.
```
public class SerializableStringDictionary : System.Collections.Specialized.StringDictionary, System.Xml.Serialization.IXmlSerializable
{
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
while (reader.Read() &&
!(reader.NodeType == System.Xml.XmlNodeType.EndElement && reader.LocalName == this.GetType().Name))
{
var name = reader["Name"];
if (name == null)
throw new FormatException();
var value = reader["Value"];
this[name] = value;
}
}
public void WriteXml(System.Xml.XmlWriter writer)
{
foreach (System.Collections.DictionaryEntry entry in this)
{
writer.WriteStartElement("Pair");
writer.WriteAttributeString("Name", (string)entry.Key);
writer.WriteAttributeString("Value", (string)entry.Value);
writer.WriteEndElement();
}
}
}
```
Resulting XML fragment will look similar to:
```
...
<setting name="PluginSettings" serializeAs="Xml">
<value>
<SerializableStringDictionary>
<Pair Name="property1" Value="True" />
<Pair Name="property2" Value="05/01/2011 0:00:00" />
</SerializableStringDictionary>
</value>
</setting>
...
``` | Store Dictionary<string,string> in application settings | [
"",
"c#",
".net-3.5",
"dictionary",
"settings",
""
] |
I've just installed VS2008 and have run into a problem that I'm sure can be solved with either lambda's or delegates (or a combination!).
```
private string ReadData(TcpClient s, string terminator)
{
// Reads a byte steam into a string builder until either data is unavailable or the terminator has not been reached
var sb = new StringBuilder();
do
{
var numBytesRead = s.GetStream().Read(byteBuff, 0, byteBuff.Length);
sb.AppendFormat("{0}", Encoding.ASCII.GetString(byteBuff, 0, numBytesRead));
} while (s.GetStream().DataAvailable && !sb.ToString().Contains(terminator));
return sb.ToString();
}
```
The problem is, sometimes I need to check if the string contains either of two different values. Sometimes I may need to check it for three values.
So what I propose, is to change " !sb.ToString().Contains(terminator)" to a function that is passed into the method.
I could write my different functions such as:
```
private bool compare1(string s, string t) {
return s.contains(t)
}
private bool compare2(string s, string t1, string t2) {
return (s.compare(t1) or s.compare(t2)
}
// etc...
```
Then when I want to compare with 3 different values, create a delegate to one of these functions, then pass that to the ReadData() method.
I'm very clueless when it comes to delegates, and I'm not sure if this seems like the right place for a lambda but something is telling me it is.
The calling code is this:
```
// Enter username .
if (HasData(s,"login:"))
SendData(s, switchUser + TelnetHelper.CRLF);
```
HasData is identical to ReadData, but returns a bool instead of a string (which I'd also like to factor out into one method using some trickery - but that's a secondary question - feel free to answer that though.
Just for reference:
```
private bool HasData(TcpClient s, string terminator)
{
// Reads a byte steam into a string builder until either data is unavailable or the terminator has not been reached
var sb = new StringBuilder();
do
{
var numBytesRead = s.GetStream().Read(byteBuff, 0, byteBuff.Length);
sb.AppendFormat("{0}", Encoding.ASCII.GetString(byteBuff, 0, numBytesRead));
} while (s.GetStream().DataAvailable && !sb.ToString().Contains(terminator));
return sb.ToString().Contains(terminator);
}
``` | It sounds like you're looking for a predicate function. Instead of hard coding the check, take a delegate as a parameter than can do the check
```
private string ReadData(TcpClient s, Func<string,bool> predicate)
{
// Reads a byte steam into a string builder until either data is unavailable or the terminator has not been reached
var sb = new StringBuilder();
do
{
var numBytesRead = s.GetStream().Read(byteBuff, 0, byteBuff.Length);
sb.AppendFormat("{0}", Encoding.ASCII.GetString(byteBuff, 0, numBytesRead));
} while (s.GetStream().DataAvailable && !predicate(sb));
return sb.ToString();
}
```
Then you can create several wrappers which just create the appropriate delegate and pass it down
```
public bool HasData(TcpClient c, string terminator) {
return HasData(c, (s) => s.Contains(terminator));
}
public bool HasData(TcpClient c, string t1, string t2) {
return HasData(c, (s) => s.Contains(t1) || s.Contains(t2));
}
```
You can even build a delegate on the fly based on arbitrary number of terminators
```
public bool HasData(TcpClient c, params string[] terminatorList) {
return HasData(c, (s) => terminatorList.Where(x => s.Contains(x)).Any());
}
``` | One option would be to overload the ReadData() method to take a string array containing the values that you are checking for. Using an [extension method](http://msdn.microsoft.com/en-us/library/bb383977.aspx), you could extend Contains() to take a string array.
Your ReadData() method could be:
```
private string ReadData(TcpClient s, string[] terminators) {
// Reads a byte steam into a string builder until either data is unavailable or the terminator has not been reached
var sb = new StringBuilder();
do
{
var numBytesRead = s.GetStream().Read(byteBuff, 0, byteBuff.Length);
sb.AppendFormat("{0}", Encoding.ASCII.GetString(byteBuff, 0, numBytesRead));
} while (s.GetStream().DataAvailable && !sb.ToString().Contains(terminators));
return sb.ToString();
}
```
The Contains() method extension could be:
```
public static bool Contains ( this String str , String[] testValues )
{
foreach ( var value in testValues )
{
if ( str.Contains( value ) )
return true;
}
return false;
}
```
This implementation eliminates the need to create a new predicate each time you have a different number of strings to test for. | Refactoring with Lambda's and Delegates | [
"",
"c#",
".net",
"refactoring",
"delegates",
"lambda",
""
] |
This is not working. Firebug is not throwing any error though.
HTML:
```
<table>
<tr><td>BookA</td><td><a href="javascript:deleteRow($(this));" class="red">Delete</a></td></tr>
<tr><td>BookB</td><td><a href="javascript:deleteRow($(this));" class="red">Delete</a></td></tr>
<tr><td>BookC</td><td><a href="javascript:deleteRow($(this));" class="red">Delete</a></td></tr>
<tr><td>BookD</td><td><a href="javascript:deleteRow($(this));" class="red">Delete</a></td></tr>
</table>
```
Javascript:
```
function deleteRow(ref) {
$(ref).parent().parent().remove();
}
```
**If possible, I would like to use a solution with inline javascript** | First of all, inline JavaScript (`href="javascript:x"` or `onclick="x"`) is generally bad. With inline JavaScript, you won't have access to the event object, and you can't really be sure what `this` references to.
jQuery (and almost every other JavaScript library/framework) has built-in event handling. So, your code would look like this with event handlers:
```
$('a.red').click(function(e) {
e.preventDefault(); // don't follow the link
$(this).closest('tr').remove(); // credits goes to MrKurt for use of closest()
});
```
And here's a demo: <http://jsbin.com/okaxu> | Try this:
```
// Bind all the td element a click event
$('table td.deleteRow').click(function(){
$(this).parent().remove();
});
```
By the way, it'll remove the javascript from your html code.
With this html code
```
<table>
<tr>
<td>BookA</td>
<td class="red deleteRow">Delete</td>
</tr>
<tr>
<td>BookB</td>
<td class="red deleteRow">Delete</td>
</tr>
<tr>
<td>BookC</td>
<td class="red deleteRow">Delete</td>
</tr>
<tr>
<td>BookD</td>
<td class="red deleteRow">Delete</td>
</tr>
</table>
``` | Delete a table row with javascript / jquery | [
"",
"javascript",
"jquery",
""
] |
The question might look subjective but considering Microsoft:
* Owns the Xbox 360 platform
* Owns the Windows platform
* Have their own game studio (MGS)
* Own other 3rd party developers
* Is a major publisher
makes me wonder why Microsoft doesn't push their flagship language to prove that not only you can cut down significant development time, and therefore money, but also show that you can release a next gen title where the real time interactivity doesn't suffer.
If Microsoft were to do this once, I am sure many AAA developers would jump on that wagon too. | First, XNA wouldn't be an option. It is made with the goal of abstracting away the differences between the PC and 360. A high-performance game can't do that. It has to exploit the differences. Where the 360 shines, the performance has to be leveraged. Where it sucks, workarounds have to be developed. And vice versa for the PC.
That's also why other DirectX wrappers exist (SlimDX comes to mind as a much more direct D3D wrapper).
As for managed code in general, several problems come to mind:
* They have a large codebase already that they'd like to keep using. The way to cut down on development time is **not** to throw everything out the window and start over from scratch in another language.
* Most game studios still have some autonomy, even if they're owned by Microsoft. If they prefer to write their game in C++, can Microsoft overrule it? Would it be a good idea to do so? It would certainly piss off the developers, and pissed off developers aren't usually a good thing.
* Performance: Yes, C# and .NET performs very well on PC, but on consoles, it's a different story. It uses the .NET CF which, among other things, has a terribly primitive garbage collector. Its JIT compiler frankly sucks. .NETCF is not designed to outperform well-tuned native code.
* Control: The way you usually write AAA console games is to exploit everything the console has to offer. Every byte of memory should be more or less accounted for, every CPU cycle used. Managed code is simply less predictable. When does the GC run? How much memory is in use at any given time? We don't know. Consoles only have very limited amounts of memory. (The 360 has 512MB iirc. That's not much for a modern game, and it is only possible to make games like Halo 3 if you know *exactly* who's using how much of that memory).
* Most features on the 360 are simply not exposed to .NET. Many hardware features require either C++ interop or assembler to exploit.
When that is said, using .NET for a high-profile PC game would work a lot better. The full .NET framework has much better performance characteristics, and the available hardware on a PC is going to vary anyway, so tight control over the exact memory usage is less critical.
But ultimately, why would they do this? It'd be a big risk, it'd require a lot of code rewriting, and what exactly are they trying to prove? Most studios make cross-platform games, and for them, .NET is not an option no matter how awesome it is. They want to be able to run their code on the PS3 as well, or the Wii, or.... | You need to ask a slightly different question.
> Why doesn't Microsoft rewrite it's existing highly tuned gaming engines in a completely different language.
This is hopefully a more self explanatory question.
I know virtually nothing about the gaming system code base but I certainly don't imagine it to be small. Converting anything other than a trivial application from C++ to any other managed language is a **huge** undertaking.
Forgetting all of the syntax differences and C++ features / hacks that can't be done in C#, with a gaming application one issue at the front of the conversation will be perf. C# is not slow but it has vastly different performance characteristics. It's almost certain that highly tuned C++ gaming code will not perform nearly as well if it's directly ported to C#. A whole new round of performance tuning would have to happen and would not be cheap. | Why is Microsoft not developing a Halo-like next gen title using C#? | [
"",
"c#",
".net",
""
] |
I want to do a functional like pattern match to get the first two elements, and then the rest of an array return value.
For example, assume that perms(x) returns a list of values, and I want to do this:
```
seq=perms(x)
a = seq[0]
b = seq[1]
rest = seq[2:]
```
Of course I can shorten to:
```
[a,b] = seq[0:2]
rest = seq[2:]
```
Can I use some notation to do this?
```
[a,b,more] = perms(x)
```
or conceptually:
```
[a,b,more..] = perms(x)
```
PROLOG & functional languages do list decomposition so nicely like this! | You can do it in Python 3 like this:
```
(a, b, *rest) = seq
```
See the [extended iterable unpacking PEP](http://www.python.org/dev/peps/pep-3132/) for more details. | In python 2, your question is very close to an answer already:
```
a, b, more = (seq[0], seq[1], seq[2:])
```
or:
```
(a, b), more = (seq[0:2], seq[2:])
``` | python - match on array return value | [
"",
"python",
"list",
""
] |
How can I use YUI to locate a text input by name and insert a div after it?
For example, this doesn't work:
```
<input name="some_name" type="text">
<script>
var el = new YAHOO.util.Element(document.createElement('div'));
var some_element = document.getElementsByName('some_name');
// doesn't work .... replacing 'some_element' with 'document.body' works
el.appendTo(some_element);
</script>
``` | As mentioned, document.getElementsByName returns an array. You may want to give your input an ID with the same name as the name attribute. (Aside: This is common and good practice for forms. Other js libraries provide helpful extensions when you do this.)
```
<input name="some_name" id="some_name" type="text">
<script>
(function () {
var el = new YAHOO.util.Element(document.createElement('div'));
// var some_element = document.getElementByName('some_name')[0];
var some_element = document.getElementsById('some_name'); // preferred, faster
// el.appendTo(some_element);
YAHOO.util.Dom.insertAfter(el,some_element);
})();
</script>
```
Also notice the use of **insertAfter rather than appendTo**. You do not want el to be a child of your input element. You want it to be the next sibling. Inputs do not have children. Also lastly, you're adding these variables to the global namespace. This may or may not be a problem, but it's generally a good idea to wrap your code in an anonymous function unless you intend for the variables to have global scope and reuse them later, but then you might want to provide a proper namespace for them.
Hope that helps (and not too much info.) ;) | document.getElementsByName('some\_name') always return a collection (an Array), if you are sure that the name is unique you can safely write this.
```
var some_element = document.getElementsByName('some_name')[0];
``` | How to use YUI to locate an Input by Name and insert content after | [
"",
"javascript",
"yui",
"append",
"element",
""
] |
Ideally, I am looking for something like JAX-RS (using annotations to describe the services I want to call), but allowing to call REST services implemented using other technologies (not JAX-RS). Any suggestion? | You wrote in a comment that you were "hoping for something more high level" than HttpClient. It sounds like [Restlet](http://restlet.org) would be perfect. It provides a high-level API for implementing *and using* RESTful web applications, with plug-and-play adapters for the lower-level implementations.
For example, to POST a webform to a resource using Restlet 1.1:
```
Client client = new Client(Protocol.HTTP);
Form form = new Form();
form.add("foo", "bar");
form.add("abc", "123");
Response response = client.post("http://host/path/to/resource", form.getWebRepresentation())
if (response.getStatus().isError()) {
// deal with the error
return;
}
if (response.isEntityAvailable()) {
System.out.println(response.getEntity().getText());
}
```
If you need to set more options on the request, you can use a Request object:
```
Form form = new Form();
form.add("foo", "bar");
form.add("abc", "123");
Request request = new Request(Method.POST, "http://host/path/to/resource");
request.setEntity(form.getWebRepresentation());
request.setReferrerRef("http://host/path/to/referrer");
Response response = client.handle(request);
```
HTH! | JAX-RS (JSR311) does not define a client API, but most JAX-RS implementations have one, like [Jersey](https://jersey.dev.java.net/nonav/apidocs/1.0.3/jersey/com/sun/jersey/api/client/package-summary.html), [RESTeasy](http://www.jboss.org/file-access/default/members/resteasy/freezone/docs/1.0.2.GA/javadocs/org/jboss/resteasy/client/package-summary.html) or [Apache CXF](http://cxf.apache.org/javadoc/latest/org/apache/cxf/jaxrs/client/package-summary.html).
The Restlet framework also has [client support](http://www.restlet.org/documentation/1.1/api/org/restlet/Client.html) as well as a seperate [HTTP Client extension](http://wiki.restlet.org/books/documentation_book_definition--20081027-003425/publications/html-chunked/output/dsy75-restlet.html#dsy75-restlet).
Since these are specialized libraries/frameworks for REST, I'd suggest you look into these. | JAX-RS is perfect for implementing REST. What do you use to call REST services in Java? | [
"",
"java",
"rest",
"client",
"jax-rs",
""
] |
How can I instantiate a class by throwing in a variable name?
Consider this method inside a class:
```
animate: function(el, build) {
console.log(build.effect);
var animationClass = new build.effect(el,build);
},
```
Build is an object containing lots of stuff, but most importantly an
"effect". This effect is the name of an independent animation class--
one is called "MarioKartMenu".
console.log(build.effect) prints out "MarioKartMenu".
But of course I get: TypeError: Result of expression 'build.effect' [MarioKartMenu] is not a constructor.
If I trash the dynamism and just make the code as such:
```
animate: function(el, build) {
var animationClass = new MarioKartMenu(el,build);
},
```
It works just fine. Is it possible to make it dynamic like I'm attempting to do? | If the function `MarioKartMenu` is defined in the global scope, you can access it by its string name using:
```
window["MarioKartMenu"]
```
This works because all global variables are properties of the `window` object.
Given the above, you can implement what you want by using:
```
var menuConstructor = window[build.effect];
var animationClass = new menuConstructor(el, build);
``` | Just assign the constructor to `build.effect` (not a string containing its name) and it should work:
```
animate = function(el, build) {
var animationClass = new build.effect(el,build);
}
// ...
b = ...;
b.effect = MarioKartMenu;
animate(e, b);
``` | Instantiate a Class dynamically via variable | [
"",
"javascript",
"mootools",
""
] |
Is there a way to send **multiple lines** of text to the clipboard using javascript?
IE, I want to send:
```
abc
def
ghi
```
and not
```
abcdefghi
```
*(and although right now i need to learn how to do it in Javascript, I would not mind hearing how it is done in other languages, like python)* | Send it as one string with carriage return and line feed characters in it, as Russ suggested.
You replied to Russ that, "it does not work": what's the symptom of it not working?
If you're copying from the clipboard into HTML, note that whitespace (especially including carriage return and line feed characters) is not necessarily preserved by the HTML DOM when you insert it into the DOM. | did you try 'abc\r\ndef\r\nghi\r\n' | Multiple lines of text to clipboard | [
"",
"javascript",
"clipboard",
""
] |
Is there any API for writing a C# program that could interface with Windows update, and use it to selectively install certain updates?
I'm thinking somewhere along the lines of storing a list in a central repository of approved updates. Then the client side applications (which would have to be installed once) would interface with Windows Update to determine what updates are available, then install the ones that are on the approved list. That way the updates are still applied automatically from a client-side perspective, but I can select which updates are being applied.
This is not my role in the company by the way, I was really just wondering if there is an API for windows update and how to use it. | Add a Reference to WUApiLib to your C# project.
```
using WUApiLib;
protected override void OnLoad(EventArgs e){
base.OnLoad(e);
UpdateSession uSession = new UpdateSession();
IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
uSearcher.Online = false;
try {
ISearchResult sResult = uSearcher.Search("IsInstalled=1 And IsHidden=0");
textBox1.Text = "Found " + sResult.Updates.Count + " updates" + Environment.NewLine;
foreach (IUpdate update in sResult.Updates) {
textBox1.AppendText(update.Title + Environment.NewLine);
}
}
catch (Exception ex) {
Console.WriteLine("Something went wrong: " + ex.Message);
}
}
```
Given you have a form with a TextBox this will give you a list of the currently installed updates. See <http://msdn.microsoft.com/en-us/library/aa387102(VS.85).aspx> for more documentation.
This will, however, not allow you to find KB hotfixes which are not distributed via Windows Update. | The easiest way to do what you want is using [WSUS](http://technet.microsoft.com/en-us/wsus/default.aspx). It's free and basically lets you setup your own local windows update server where you decide which updates are "approved" for your computers. Neither the WSUS server nor the clients need to be in a domain, though it makes it easier to configure the clients if they are. If you have different sets of machines that need different sets of updates approved, that's also supported.
Not only does this accomplish your stated goal, it saves your overall network bandwidth as well by only downloading the updates once from the WSUS server. | Use C# to interact with Windows Update | [
"",
"c#",
"windows-update",
""
] |
I'm developing a script that runs a program with other scripts over and over for testing purposes.
How it currently works is I have one Python script which I launch. That script calls the program and loads the other scripts. It kills the program after 60 seconds to launch the program again with the next script.
For some scripts, 60 seconds is too long, so I was wondering if I am able to set a FLAG variable (not in the main script), such that when the script finishes, it sets FLAG, so the main script and read FLAG and kill the process?
Thanks for the help, my writing may be confusing, so please let me know if you cannot fully understand. | You could use [atexit](http://docs.python.org/library/atexit.html) to write a small file (flag.txt) when script1.py exits. mainscript.py could regularly be checking for the existence of flag.txt and when it finds it, will kill program.exe and exit.
Edit:
I've set persistent environment variables using [this](http://code.activestate.com/recipes/416087/), but I only use it for python-based installation scripts. Usually I'm pretty shy about messing with the registry. (this is for windows btw) | This seems like a perfect use case for sockets, in particular [asyncore](http://docs.python.org/library/asyncore.html). | Python Environment Variables in Windows? | [
"",
"python",
"windows",
"testing",
"environment-variables",
""
] |
I'm having a hard time to make my Maven2 multi module project, with a deep project structure, appear as a single ear (with its dependencies - which includes 1 war, 2 ejbs and 1 jar) to be deployed in my JBOSS 5 server inside my Eclipse Ganymede (tab Servers).
I've been trying to use Maven Eclipse Plugin to turn my projects into a WTP project without success. Therefore they appear to be deployed in the server they appear as separated projets.
My project has 1 war, 2 ejbs and 1 jar that must be packaged inside an ear, each of the "subprojects" is a separate module.
Project's pom.xml (type pom):
...
```
<modules>
<module>ejb1</module>
<module>ejb2</module>
<module>war</module>
<module>jar</module>
<module>ear</module>
</modules>
```
...
The ear module is only responsable to pack the other modules together.
Is there a way to tell eclipse (ganymede) that all those projects (ejbs, war and jar) are inside the ear module so I can deploy the ear in the server? | What you want to do is have maven create the eclipse projects via mvn eclipse:eclipse [This](http://maven.apache.org/plugins/maven-eclipse-plugin/examples/multi-module-projects.html) might be helpful. | try m2eclipse (google it) and install the WTP integration tool, create a project using the maven wizard, change the type to pom in the pom xml editor, create a sub modules from the pom and that adds it as child, if its a web project it get the WTP behavior i.e it can be deployed to a j2ee container ( jboss / tomcat ), add a dep to the web module for ejb module in the web pom etc, deploy the web app to the container | Multi Module Maven2 Project with WTP | [
"",
"java",
"eclipse",
"maven-2",
"eclipse-wtp",
""
] |
I have a method that takes a list of entities (`Class`es) and does some computation. To describe my needs here is the simplest outline of the method (pseudo-code):
```
public void do(List<Class<?> entities) {
for (Class<?> entity : entities) {
List<?> list = session.createCriteria(entity).list();
for (Object o : list) {
System.out.println(o.getClass().getSimpleName() + " " + o.getId());
}
}
}
```
Is there a way that I can access/get the Id of **`o`**? | ```
session.getIdentifier(o)
``` | Well, maybe it'll get many critics but all your entity classes may implement this interface:
```
public interface EntityWithId {
Integer getId();
void setId(Integer id);
}
```
If your id's are not integers may be the interface could be:
```
public interface EntityWithId<T> {
T getId();
setId(T id);
}
public class Entity implements EntityWithId<String> {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
.
.
.
}
```
Anyway, I don't see why you'd want to get the IDs of all your entities, it's a strange solution for a strange requirement, hehe. | Hibernate getting Id from createCriteria() result | [
"",
"java",
"hibernate",
""
] |
I have a WinForms application that was going to use ClickOnce. But it turns out ClickOnce won't work for my application, so I'd like to remove it. Only...there doesn't seem to be an obvious way to do this. There's no "Un-ClickOnce" button. Does anybody know what steps I need to take to get my app to be like it was before ClickOnce integrated itself?
(I know I can create a new project and import stuff into it, but it seems silly to have to do that, so I'm hoping there's another way.) | Other responses here are not correct or helpful. It is incorrect to state that it never needs removing.
One such example I experienced recently was when the application had a need for administrative privileges. Any attempt to embed administrative requirements into the manifest will result in the application not even compiling while ClickOnce is still present in the solution.
The following two steps enabled me to turn off ClickOnce (in Visual Studio 2010):
In the project properties,
1. *Signing* tab: Untick "Sign the ClickOnce manifests"
2. *Security* tab: Untick "Enable ClickOnce security settings" | I believe the only thing that is left from ClickOnce once you stop deploying it is file `publish.xml` that tells you about what you have deployed thus far and what version you are at. Otherwise there is really nothing there that need concern you, just deploy from the `bin` folders as you would without ClickOnce. | Remove ClickOnce from a WinForms app | [
"",
"c#",
".net",
"winforms",
"clickonce",
""
] |
I'm writing a database view to sum up a bunch of records where the value in a date column is within the last 7 days. It looks something like this:
```
CREATE VIEW RecentRecordSum AS
SELECT t.ID,
SUM(t.SomeValue) AS ValueSum
FROM SomeTable t
WHERE t.RecordDate >= DATEADD(d,-7,GETDATE())
GROUP BY t.ID
```
Is there a way of doing this without having the GETDATE() directly in the where clause?
I'm using SQL Server 2000 and 2005.
Looking at the query plan shows that the cost of the getdate() call is only 0.03% of the entire query (which is considerably more complex than the one above), so performance is not an issue, however I like my queries to be deterministic.
Ideally I'd also like to expose the -7 parameter as a column so that it could be used in the where clause of something querying the view. Currently I'm contemplating a small number of views for 7, 14, 28 day windows. | One reason for your question might be to make the view more optimizable by removing the data transformation. Can't do it in a view, you'd need to make it a stored procedure and do the transform into a variable:
```
CREATE PROCEDURE RecentRecordSum AS
DECLARE @adate DATETIME
SELECT @adate = DATEADD(d, -7, GETDATE())
SELECT t.ID,
SUM(t.SomeValue) AS ValueSum
FROM SomeTable t
WHERE t.RecordDate >= @adate
GROUP BY t.ID
``` | Another shot in the dark, like everyone else...
Perhaps you are wishing to make this an indexed view, which you would not be able to do with getdate(), since it is an indeterminate function. I have circumvented this in the past by calling getdate() from within another view that just contains
```
select getdate()
```
This level of indirection was enough to fool SQL Server 2000 and allow me to use schemabinding, but I can not guarantee this will work with later versions. | How do I avoid the use of getdate() in a SQL view? | [
"",
"sql",
"sql-server",
"database",
"view",
""
] |
Is there a way of iterating through an array but performing an operation on every other element?
ie If I have an array with 13 elements how do I do something to only elements 2,4,6,8,10 and 12? | to fix cletuses answer for more speed and fix typos:
```
for ($i = 1, $j = count($array); $i < $j; $i += 2) {
// code
}
``` | ```
foreach($array as $val) {
if(($i++ % 2) == 0) {
...do stuff here...
}
}
``` | selective iteration of array in php | [
"",
"php",
"arrays",
"loops",
""
] |
I'm in the processes of changing my DAO layer from using Hibernate API to using a pure JPA API implementation. It looks like the recommended method is to use the createNamedQuery from the entity manager. The named queries are stored in annotations in the model/entity classes. This just not makes sense to me. Why would you define the JPA Queries in the model objects but use them in the DAOs. Wouldn't it make more sense to just use createQuery from within the DAO itself and define the queries in the DAO or even just define the named queries in the DAO itself?
For those of you that have implemented your DAO layer using the JPA API how have you defined your queries? | I use named queries.
There are two reasons to do so:
1. It puts them in a more central place rather than scattered in code with random createQuery() calls; and
2. Build processes can validate the queries (really useful). | You could take a look at [Spring Data JPA](http://www.springsource.org/spring-data/jpa). It allows you to simply define an interface and execute queries without the need to implement the execution manually.
Entity:
```
@Entity
@NamedQuery(id="User.findByLastname" query="from User u where u.lastname = ?1")
public class User implements Persistable<Long> {
@Id
private Long id;
private String username;
private String lastname;
private int age;
}
```
Repository:
```
public interface UserRepository extends CrudRepository<User, Long> {
// Will trigger the NamedQuery due to a naming convention
List<User> findByLastname(String lastname);
// Will create a query from the methodname
// from User u where u.username = ?
User findByUsername(String username);
// Uses query annotated to the finder method in case you
// don't want to pollute entity with query info
@Query("from User u where u.age > ?1")
List<User> findByAgeGreaterThan(int age);
}
```
Setup:
```
EntityManager em = Persistence.getEntityManagerFactory().createEntityManager();
JpaRepositoryFactory factory = new JpaRepositoryFactory(em);
UserRepository repository = factory.getRepository(UserRepository.class);
```
As you see you can choose between different ways to derive the query to be executed from the method. While deriving it directly from the method name is feasible for simple queries you'd probably choose between the `@NamedQuery` (JPA standard) or `@Query` (Spring Data JPA annotation) dependening on how much you like to stick with standards.
Spring Data JPA gives you support in various other corners of data access layer implementation, allows providing custom implementations for methods and nicely integrates with Spring. | JPA why use createNamedQuery | [
"",
"java",
"hibernate",
"jpa",
"data-access-layer",
""
] |
So I've got this audit table, looks like this:
```
USE [DatabaseName]
GO
/****** Object: Table [ERAUser].[Audit] Script Date: 05/20/2009 17:07:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [ERAUser].[Audit](
[AuditID] [int] IDENTITY(1,1) NOT NULL,
[Type] [char](1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[TableName] [varchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PrimaryKeyField] [varchar](1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PrimaryKeyValue] [varchar](1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[FieldName] [varchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[OldValue] [varchar](1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[NewValue] [varchar](1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[UpdateDate] [datetime] NULL DEFAULT (getdate()),
[UserName] [varchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
```
The problem is, for reasons out of my control, I need to return data to users (other developers that are the users of this system) as rowsets that replicate the source table. How can I turn this schema on its side and get the values in FieldName as the column headings for a rowset? I'm using SQL 2005. I will know the tablename and the UpdateDate. | This can be done using the PIVOT function. I'll try to work out an example:
```
SELECT *
FROM ERAUser.Audit
PIVOT (max(NewValue) FOR FieldName in (Field1, Field2, Field3)) as PivotTable
```
The max() is necessary to tell Sql Server what to do if it finds multiple rows with the same FieldName. You can use a WHERE statement to limit it to the right rows; if you ensure it finds only one, max(NewValue) is equal to NewValue.
You can generate the SQL for this, if you have a long list of columns:
```
declare @columnlist nvarchar(4000)
select @columnlist = IsNull(@columnlist + ', ', '') + FieldName
from (
select distinct FieldName from ERAUser.Audit
) sub
declare @query nvarchar(4000)
select @query = 'select *
from ERAUser.Audit
PIVOT (max(newValue) FOR FieldName in (' + @columnlist + ')) as PivotTable'
exec sp_executesql @query
```
Here's a basic example of PIVOT, to get the general idea:
```
create table #normalized (
colname varchar(12),
value varchar(12)
)
insert into #normalized values ('value1','A')
insert into #normalized values ('value2','B')
insert into #normalized values ('value3','C')
select *
from #normalized
PIVOT (max(value) FOR ColName in (value1,value2,value3)) as Y
```
This will result in:
```
value1 value2 value3
A B C
``` | It will be extremely difficult, not least because the type of the values for one combination of table name and column name will be different from other types. To create a whole record corresponding to one row of the table, you are going to have to combine multiple audit records. So, your rowset would have to be tailored to one table at a time. It isn't clear whether you record the unchanged columns - you probably don't - so dealing with a rowset containing the entire record will be tough, at best. | How can I retrieve the values from a generic audit table reconstituted as a rowset with meaningful column names in SQL? | [
"",
"sql",
""
] |
In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.
But after I ssh into another machine and start `python` there, I get sessions like:
```
>>> import os
>>> ^[[A
```
where the last character comes from arrow-up. Or, using arrow-left:
```
>>> impor^[[D
```
How can I fix this?
In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell. | Looks like readline is not enabled. Check if `PYTHONSTARTUP` variable is defined, for me it points to `/etc/pythonstart` and that file is executed by the python process before going interactive, which setups readline/history handling.
Thanks to @chown here is the docs on this: <http://docs.python.org/2/tutorial/interactive.html> | I've solved this issue by installing `readline` package:
```
pip install readline
``` | Seeing escape characters when pressing the arrow keys in python shell | [
"",
"python",
"shell",
"ssh",
"arrow-keys",
""
] |
I have had C++ experience but not MSVC.
What I am trying to do is incorporate a .dll from an open source project into my project. The code is available and I have built it. I have the .dll as well as the .lib which as I understand it is required for C++ projects.
Now unfortunately there is no simple "Add Reference", drop my .dll into an include directory and add that to my solution. I have edited the project property pages, the C/C++ Additional Include Directories option as well as adding the .lib as an additional linker dependency. I have created an include directory for the dll and lib inside my solution tree.
My problem is when I try to include the header files from the documentation, VS output spits out error messages. Now I realize that I am using the dll/lib combo and that the .h files are not present in my solution so how do I add the proper includes? I am using QT toolkit also which is working but how I add the other header / dll from the open source library eludes me.
Can someone please point me in the right direction. | You need to do a couple of things to use the library:
1. Make sure that you have both the \*.lib and the \*.dll from the library you want to use. If you don't have the \*.lib, skip #2
2. Put a reference to the \*.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.
3. You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.
After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: <http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx> for more info)
Cheers!
EDIT
Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files. | The additional include directories are relative to the project dir. This is normally the dir where your project file, \*.vcproj, is located. I guess that in your case you have to add just "include" to your include and library directories.
If you want to be sure what your project dir is, you can check the value of the $(ProjectDir) macro. To do that go to "C/C++ -> Additional Include Directories", press the "..." button and in the pop-up dialog press "Macros>>". | DLL References in Visual C++ | [
"",
"c++",
"visual-c++",
"dll",
""
] |
I use [`GetOpenFilename()`](http://msdn.microsoft.com/en-us/library/ms646927(VS.85).aspx) to let the user select a file. Here is the code:
```
wchar_t buffer[MAX_PATH] = { 0 };
OPENFILENAMEW open_filename = { sizeof (OPENFILENAMEW) };
open_filename.hwndOwner = handle_;
open_filename.lpstrFilter = L"Video Files\0*.avi;*.mpg;*.wmv;*.asf\0"
L"All Files\0*.*\0";
open_filename.lpstrFile = buffer;
open_filename.nMaxFile = MAX_PATH;
open_filename.lpstrTitle = L"Open media file...";
open_filename.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
::GetOpenFileNameW(&open_filename);
```
The file dialog shows up, but when I
* change the Filter or
* click on "*My Computer*"
the file list turns empty. Pressing `[F5]` does not help, but if I switch to the parent folder and return to the original folder (in the case of the Filter change) the filtering works fine and files show up in the list.
**EDIT:** My system is Windows XP (SP3) 32-bit - nothing special. It happens on other machines - with the same config - as well. | Okay, I have figured out the problem, or at least, I have a solution that is working for me.
Earlier in the code, I had the following call to initialize COM...
```
::CoInitializeEx(NULL, COINIT_MULTITHREADED);
```
Well, changing this to...
```
::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
```
...solves the problem for me! Now the file dialog is filtering again.
I searched the web for this and it seems that a very few people faces the same problem, but no one published the aforementioned solution. Can anyone verify my findings? | One thing you haven't done that might be causing problems is fully initialize the OPENFILENAMEW structure, especially the lStructSize element. I've seen this causing strange effects before. I'd suggest having something like
```
OPENFILENAMEW open_filename = { sizeof (OPENFILENAMEW) };
ZeroMemory(&open_filename, sizeof (OPENFILENAMEW));
open_filename.lStructSize = sizeof (OPENFILENAMEW);
``` | GetOpenFileName() does not refresh when changing filter | [
"",
"c++",
"c",
"winapi",
"dialog",
""
] |
We are making a Jabber client for our internal use in our company and somehow we need to catch the moment when the user tries to kill the program to actually restart it or just make impossible for the user to kill the client.
Is this possible?
Our Jabber client will be written in C#.
How would I go about accomplishing this? | What you are asking for has implications far beyond what you are being asked to accomplish. For example, if the process cannot be killed, how can Windows shut down normally?
I don't know your boss, so you will have to gauge their level of understanding for yourself. If a user/manager asked me for this, I would have to probe deeper to find what they really mean. My suspicion is that your users want the default close behavior to minimize to the system tray rather than exit the program, similar to most instant message clients, rather then not be able to ever close the program at all. | let me first say, this is a horrible idea.
but...if you must do it, the way I see malicious software and spam hounds do it is to create 3 running processes, one is the main process and the other two will monitor and restart any killed process. it's very difficult for the average user to kill 3 processes simultaneously. | How can I make a program that's impossible to be killed in Windows? | [
"",
"c#",
".net",
"windows",
"process",
""
] |
Is there any way to store the generic parameter type passed in at construction to a parameter. My goal:
```
class generic<T> {
Class<T> type;
public generic() {
super();
this.type = //Something that gets class from T
}
}
```
What I'm currently doing is this:
```
class generic<T> {
Class<T> type;
public generic(Class<T> type) {
super();
this.type = type;
}
}
```
It seems silly to have to specify the class twice, but I'm not sure of how else to do it. I think this might be possible with reflection, but I haven't investigated that yet. Is there a more straightforward way? If not (as an aside) why the information loss? | Because Java generics are implemented with [Type Erasure](http://java.sun.com/docs/books/tutorial/java/generics/erasure.html)
> When a generic type is instantiated,
> the compiler translates those types by
> a technique called type erasure — a
> process where the compiler removes all
> information related to type parameters
> and type arguments within a class or
> method. Type erasure enables Java
> applications that use generics to
> maintain binary compatibility with
> Java libraries and applications that
> were created before generics. | If you use a static creation method with type inference instead of the constructor, then the type does not need to be specified twice.
```
final class Generic<T> {
private final Class<T> type;
private Generic(Class<T> type) {
super();
if (type == null) {
throw new NullPointerException();
}
this.type = type;
}
public static <T> Generic<T> newInstance(Class<T> clazz) {
return new Generic<T>(clazz);
}
}
...
someFunction(Generic.newInstance(SomeType.class));
```
Of course, if you want to store the result in a variable, you are probably going to repeat the type anyway! | Store class generic in field in Java | [
"",
"java",
"generics",
""
] |
I have implemented a sort of `Repository` class and it has has `GetByID`, `DeleteByID` methods and so on, but I'm having trouble implementing the `UpdateByID` method.
I did something like this:
```
public virtual void UpdateByID(int id, T entity)
{
var dbcontext = DB;
var item = GetByID(dbcontext, id);
item = entity;
dbcontext.SubmitChanges();
}
protected MusicRepo_DBDataContext DB
{
get
{
return new MusicRepo_DBDataContext();
}
}
```
But it's not updating the passed entity.
Has anyone implemented such a method ?
---
*For reference, [here](http://pastebin.com/m1ef0c7c0) is the `GetByID` method*
---
**[Update]**
As Marc correctly suggested, I am merely changing the values of the local variable. So how do you think I should go about this method? Use reflection and copy the properties from `entity` to `item` ? | All you have updated is a local variable; for that to work you would have to copy the *member values* from `entity` to `item` - not quite so simple.
---
Something like below; the only reason I used `TKey` was that I tested on Northwind.Customer, which has a string key ;-p
The advantage of using the meta-model is that it works even if you are using POCO classes (and the xml-based mapping), and it doesn't try to update anything unrelated to the model.
For the purposes of the example, I have passed in the data-context, and you need to add a `SubmitChanges` at some point, but the rest should be directly comparable.
BTW - if you are happy to take the ID from the passed in object, that would be easy too - and then you could support composite identity tables.
```
static void Update<TEntity>(DataContext dataContext, int id, TEntity obj)
where TEntity : class
{
Update<TEntity, int>(dataContext, id, obj);
}
static void Update<TEntity, TKey>(DataContext dataContext, TKey id, TEntity obj)
where TEntity : class
{
// get the row from the database using the meta-model
MetaType meta = dataContext.Mapping.GetTable(typeof(TEntity)).RowType;
if(meta.IdentityMembers.Count != 1) throw new InvalidOperationException("Composite identity not supported");
string idName = meta.IdentityMembers[0].Member.Name;
var param = Expression.Parameter(typeof(TEntity), "row");
var lambda = Expression.Lambda<Func<TEntity,bool>>(
Expression.Equal(
Expression.PropertyOrField(param, idName),
Expression.Constant(id, typeof(TKey))), param);
object dbRow = dataContext.GetTable<TEntity>().Single(lambda);
foreach (MetaDataMember member in meta.DataMembers)
{
// don't copy ID
if (member.IsPrimaryKey) continue; // removed: || member.IsVersion
// (perhaps exclude associations and timestamp/rowversion? too)
// if you get problems, try using StorageAccessor instead -
// this will typically skip validation, etc
member.MemberAccessor.SetBoxedValue(
ref dbRow, member.MemberAccessor.GetBoxedValue(obj));
}
// submit changes here?
}
``` | *Taking a fresh look here, previous answers to question made various assumptions about the application.*
Concurrency within an application is something that needs to be thought about upfront and is something for which there isn't really a one-size-fits-all answer. Things to consider when making the choice for your application:
* LINQ to SQL / Entity Framework are very configurable because there isn't a one-size-fits-all.
* You aren't going to see the effect of concurrency until you have a certain load on your app (i.e. you, alone, at your own machine might *never* see it)
* How often does your application allow 2 (or more) users to edit the same entity?
* How do you want to handle the situation of when two edits overlap?
* Is your app serializing the data back and forth across another layer (e.g. Ajax)? If so then how do you know if the edited entity was modified between the read/update? Timestamp? Version field?
* Do you care if edits overlap? Pay special attention to FK relationships. Data integrity is where you can get bitten by last one wins.
Different solutions have very different performance implications! You won't notice as you're developing but your app may fall over when 25 people use it simultaneously. Watch for lots of copying back and forth and for many SQL reads:
* **Don't call SQL in a loop** (watch for this when you pass in a list of entities)
* Don't use reflection for this when you already have concurrency checking via LINQ
* Minimize the copying back and forth of fields (may be necessary when crossing N-Tier boundaries).
* Don't make a separate query to look up the old entity, (only use it if you have it lying around already) let LINQ do this as it is more optimized for doing it in SQL.
Here are some good links for deeper reading to decide your specific needs:
* [Optimistic Concurrency Overview (LINQ to SQL, MSDN)](http://msdn.microsoft.com/en-us/library/bb399373.aspx)
* [Anti-Pattern: Mishandled Concurrency (June 2009, MSDN Magazine)](http://msdn.microsoft.com/en-us/magazine/dd882522.aspx#id0420025)
My recommended solution:
```
public virtual void Update(T entity)
{
var DB = ...;
DB.GetTable<T>().Attach(entity, true);
try
{
// commit to database
DB.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException e)
{
Console.WriteLine(e.Message);
foreach (ObjectChangeConflict occ in DB.ChangeConflicts)
{
occ.Resolve(REFRESH_MODE);
}
}
}
```
Where `REFRESH_MODE` specifies one of the following:
* `RefreshMode.KeepChanges`
* `RefreshMode.KeepCurrentValues`
* `RefreshMode.OverwriteCurrentValues`
You will also need to make some considerations about your model:
Probably goes without saying but you will need to let LINQ know which field is your primary key to update the entities. You don't have to pass this in as another param (as in your original method) because LINQ already knows this is the PK.
You get to (*rather than "have to"*) decide which fields are actually checked. For instance a foreign key field is very important to have concurrency checking, whereas the description field probably deserves a last-one-wins. You control that via the `UpdateCheck` attribute. The default is `UpdateCheck.Always`. From MSDN:
> Only members mapped as `Always` or
> `WhenChanged` participate in optimistic
> concurrency checks. No check is
> performed for members marked `Never`.
> For more information, see [`UpdateCheck`](http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.updatecheck.aspx).
To enable optimistic concurrency, you need to specify a field to use as the concurrency token (e.g. timestamp or version) and this field always has to be present when serializing back and forth. [Mark this column with `IsVersion=true`.](http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.isversion.aspx)
If you don't want concurrency checking then you must mark all as UpdateCheck.Never. | C# Linq-SQL: An UpdateByID method for the Repository Pattern | [
"",
"c#",
"linq-to-sql",
"generics",
"repository-pattern",
""
] |
Basically I would like to store the address of a pointer in a buffer. Don't ask me why
```
char * buff = "myBuff";
char * myData = (char*)malloc(sizeof(char*));
int addressOfArgTwo = (unsigned int)buff;
memcpy(myData, &addressOfArgTwo, sizeof(char*));
cout << "Int Val: " << addressOfArgTwo << endl;
cout << "Address in buffer:" << (unsigned int)*myData << endl;
```
I can't see why the above code doesn't work. It outputs:
```
Int Val: 4472832
Address in buffer:0
```
When the Int Val & Address in Buffer should be the same. thanks | You dereference a char \*, resulting in a char, and then cast that 1-byte char to an int, not the entire 4 bytes of address (if this is a 32-bit machine, 8 bytes on 64-bit). 4472832 is 444000 in hexadecimal. On a little-endian machine, you grab that last 00.
```
*((unsigned int*)myData)
```
should result in the correct number being displayed. | This is generally dangerous:
```
*((unsigned int*)myData)
```
Intel IA-32 (that everyone's used to) supports unaligned accesses, but some other architectures don't. They require variables to be aligned (8-bit data on 1-byte boundaries, 16-bit data on 2-byte boundaries, and 32-bit data on 4-byte boundaries). On an architecture that requires alignment, an unaligned access will either return corrupt data or throw a CPU exception. I've seen it cause a bug in real life at a past job, a subtle bug that caused file system corruption because of the disk driver that came with a software package we were using (on an embedded platform).
In this isolated case, you can see the address of myData came from malloc(), which should mean it's suitably aligned for all types of pointers, but casting a smaller pointer to a larger pointer is generally a dangerous practice if you don't know where the pointer came from.
The safe way to extract a 32-bit integer from an arbitrary memory location is to declare a temporary 32-bit integer and perform a copy to it, treating the source memory as a raw character array:
```
unsigned int GetUnalignedLittleEndianUInt32(void *address)
{
unsigned char *uc_address = (unsigned char *)address;
return (
(uc_address[3] << 24) |
(uc_address[2] << 16) |
(uc_address[1] << 8) |
uc_address[0]
);
}
```
or more generally (with some function call overhead):
```
unsigned int GetUnalignedUInt32(void *address)
{
unsigned int value;
memcpy(&value, address, sizeof(value));
return value;
}
```
which is actually just the reverse of the memcpy() you did to get the pointer there in the first place.
Although, treating the pointer as an int:
```
int addressOfArgTwo = (unsigned int)buff;
```
is also dangerous, if you're moving between 32-bit and 64-bit architectures, as Michael pointed out. Pointers aren't always 32-bit integers. Consider using a typedef that you can later change. The convention on Linux is for a pointer to be the same size as a long. On Windows, there are typedefs INT\_PTR, UINT\_PTR, LONG\_PTR, and ULONG\_PTR.
So, I would finally suggest (on Windows anyway):
```
ULONG_PTR GetAddressAtAddress(void *address)
{
ULONG_PTR value;
memcpy(&value, address, sizeof(value));
return value;
}
``` | Copying an integer to a Buffer memcpy C++ | [
"",
"c++",
"pointers",
""
] |
I ran across the following snippet of code. Names have been changed to protect the innocent:
```
public void RunProgram()
{
System.IO.FileInfo fInfo = new System.IO.FileInfo(Application.StartupPath + "Program.exe");
if (!fInfo.Exists)
{
System.Windows.Forms.MessageBox.Show("Program could not be found, please verify your installation.\n\nDetails:\n" + fInfo.FullName);
return;
}
try
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo pStart = new System.Diagnostics.ProcessStartInfo();
pStart.FileName = fInfo.FullName;
pStart.UseShellExecute = true;
process.StartInfo = pStart;
process.Start();
}
catch
{
System.Windows.Forms.MessageBox.Show(string.Format("An error occurred trying to run the program:{0}", fInfo.FullName));
}
}
```
I know there are a few things wrong here:
* Exception types aren't being handled individually
* Error message isn't informative enough
Rest assured I'll be addressing those as well but my main question is about the check for the file's existence just before the try/catch block. This strikes me as a bit redundant.
The point of exception handling is to catch unexpected conditions. I fully expect the file to be there so removing the existence check and just letting the exception handling catch it if it isn't seams a reasonable solution to me.
What do you think? | It is redundant and may give a false sense of security. Please note that you could still get a FileNotFound exception due to concurrency.
Also see: [Is there a case where parameter validation may be considered redundant?](https://stackoverflow.com/questions/522238/is-there-a-case-where-parameter-validation-may-be-considered-redundant/522665#522665) | The file not being there is something that we can reasonably anticipate - and since we are at the UI level (I assume, since `MessageBox`), it makes reasonable sense to sanity check the request, and just tell the user directly and cancel.
If we were deep in the bowels of the code (a few levels removed from the UI), then an exception would be the right thing - but I'd still probably check for file existance first and give a sensible error. Of course, any file existance check is immediately a thread race condition ;-p | Guard Clause and Exception handling for the same condition | [
"",
"c#",
"exception",
"error-handling",
"guard-clause",
""
] |
I've got a WPF application.
On the left side there is a stackpanel full of buttons.
On the right side there is an empty dockpanel.
When user **clicks a button**, it **loads the corresponding UserControl** (View) into the dockpanel:
```
private void btnGeneralClick(object sender, System.Windows.RoutedEventArgs e)
{
PanelMainContent.Children.Clear();
Button button = (Button)e.OriginalSource;
Type type = this.GetType();
Assembly assembly = type.Assembly;
IBaseView userControl = UserControls[button.Tag.ToString()] as IBaseView;
userControl.SetDataContext();
PanelMainContent.Children.Add(userControl as UserControl);
}
```
**This pattern works well** since each UserControl is a View which has a ViewModel class which feeds it information which it gets from the Model, so the user can click from page to page and each page can carry out isolated functionality, such as editing all customers, saving to the database, etc.
## Problem:
However, now, on one of these pages I want to have a ListBox with a list of Customers in it, and each customer has an "edit" button, and when that edit button is clicked, I want to fill the DockPanel with the EditSingleCustomer UserControl and pass it the Customer that it needs to edit.
I can load the EditCustomer usercontrol, but how do I *pass it the customer to edit and set up its DataContext to edit that customer*?
* I can't pass it in the constructor since all the UserControls are already created and exist in a Dictionary in the MainWindow.xaml.cs.
* so I created a PrepareUserControl method on each UserControl and pass the Customer to it and can display it with a textbox from code behind with x:Name="..." but that is not the point, I need to DataBind an ItemsControl to a ObservableCollection to take advantage of WPF's databinding functionality of course.
* so I tried to bind the ListBox ItemSource in the View to its code behind like this:
---
```
<UserControl.Resources>
<local:ManageSingleCustomer x:Key="CustomersDataProvider"/>
</UserControl.Resources>
<DockPanel>
<ListBox ItemsSource="{Binding Path=CurrentCustomersBeingEdited, Source={StaticResource CustomersDataProvider}}"
ItemTemplate="{DynamicResource allCustomersDataTemplate}"
Style="{DynamicResource allCustomersListBox}">
</ListBox>
</DockPanel>
```
which gets a stackoverflow error caused by an endless loop in the IntializeComponent() in that view. **So I'm thinking I'm going about this in the wrong way, there must be some easier paradigm to simply pass commands from one UserControl to another UserControl in WPF** (and before someone says "use WPF commanding", I already am using commanding on my UserControl that allows the user to edit all customers, which works fine, but I have to handle it in my code behind of my view (instead of in my viewmodel) since I need the parent window context to be able to load another user control when its finished saving:
```
<Button Style="{StaticResource formButton}"
Content="Save"
Command="local:Commands.SaveCustomer"
CommandParameter="{Binding}"/>
private void OnSave(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
Customer customer = e.Parameter as Customer;
Customer.Save(customer);
MainWindow parentShell = Window.GetWindow(this) as MainWindow;
Button btnCustomers = parentShell.FindName("btnCustomers") as Button;
btnCustomers.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}
```
**So how in WPF can I simply have a UserControl loaded in a DockPanel, inside that UserControl a button with a command on it that loads another UserControl and *sends that UserControl a specific object to which it can bind its controls?***
I can imagine I just do not know enough about WPF commands at this point, if anyone can point me in the right direction from here, that would be great, or if you think this "loading UserControls in a DockPanel pattern is foreign to WPF and should be avoided and replaced with another way to structure applications", that would be helpful news as well. You can [download the current state of my application here](http://tanguay.info/web/index.php?pg=codeExamples&id=169) to get an idea of how it is structured. Thanks. | I've just finished a LOB application using WPF where this sort of problem/pattern appeared constantly, so here's how I would have solved your problem:
1) In the DataTemplate where you create each item in the ListBox, along with it's edit button, bind the Button's tag property to the Customer object underlying that list box item.
2) Create a Click event handler for the button, and set the Button's Click event to fire the handler.
3) In the event handler, set the Content property of the UserControl.
4) Set up a DataTemplate in scope of the User Control (perhaps in the resources of it's immediate container) which describes an editor for that single customer.
Another approach that will work is to declare a Customer dependency property on your EditCustomer class, then set that property (perhaps through a XAML Trigger) when the button is clicked.
I hope this isn't too vague. If nothing else, know that the problem you're facing is very solvable in WPF. | This is where you use the Mediator pattern. There's several blog posts on this topic (for [instance](http://joshsmithonwpf.wordpress.com/2009/04/06/a-mediator-prototype-for-wpf-apps/)), and there's implementations of the pattern in some WPF frameworks (such as [EventAggregator](http://msdn.microsoft.com/en-us/library/dd458915.aspx) in [Prism](http://www.codeplex.com/CompositeWPF)). | How to pass information from one WPF UserControl to another WPF UserControl? | [
"",
"c#",
"wpf",
"user-controls",
"application-design",
""
] |
I have a class like this:
```
class MyClass{
public:
MyClass(int Mode);
private:
std::map < int, std::string, CompFunc > data;
};
```
The data member must use different comparison function according to Mode argument.
```
if Mode == 1, then use CompFunc1.
if Mode == 2, then use CompFunc2.
etc.
```
but the CompFunc template argument is fixed there, how could I make it dynamically?
thanks. | ```
struct Cmp
{
explicit Cmp(int mode) : mode_(mode) {}
bool operator()(int lhs, int rhs) const
{
switch (mode_)
{
case 1: return CompFunc1(lhs, rhs); break;
case 2: return CompFunc2(lhs, rhs); break;
// etc.
}
}
private:
int mode_;
};
class MyClass
{
public:
explicit MyClass(int Mode) : cmp(mode), data(cmp) {}
private:
Cmp cmp;
std::map<int, std::string, Cmp> data;
};
``` | You can use the same compare predicate, as for map.
```
class MyClass
{
CompFunc cmp;
map<int, std::string, CompFunc> data;
public:
MyClass(int Mode) : cmp( get_cmpfunc(Mode) ), data(cmp) {...}
bool operator == (...)
{
cmp(...);
}
};
``` | comparison function of an associate container data member in class | [
"",
"c++",
"visual-c++",
""
] |
Just a simple question:
if I had a simple vector class:
```
class Vector
{
public:
float x;
float y;
float z;
};
```
Doesnt the RAII concept apply here as well? i.e. to provide a constructor to initialize all values to some values (to prevent uninitialized value being used).
**EDIT** or to provide a constructor that explicitly asks the user to initialize the member variables before the object can be obstantiated.
i.e.
```
class Vector
{
public:
float x;
float y;
float z;
public:
Vector( float x_, float y_, float z_ )
: x( x_ ), y( y_ ), z( z_ )
{ // Code to check pre-condition; }
};
```
Should RAII be used to help programmer forgetting to initialize the value before it's used, or is that the developer's responsibility?
Or is that the wrong way of looking at RAII?
I intentionally made this example ridiculously simple. My real question was to answer, for example, a composite class such as:
```
class VectorField
{
public:
Vector top;
Vector bottom;
Vector back;
// a lot more!
};
```
As you can see...if I had to write a constructor to initialize every single member, it's quite tedious.
Thoughts? | The "R" in RAII stands for Resource. Not everything is a resource.
Many classes, such as std::vector, are self-initializing. You don't need to worry about those.
POD types are *not* self initializing, so it makes sense to initialize them to some useful value. | Since the fields in your `Vector` class are built-in types, in order to ensure that they are initialized you'll have to do that in a constructor:
```
class Vector
{
public:
float x;
float y;
float z;
Vector() : x(0.0), y( 0.0), z( 0.0) {}
};
```
Now, if your fields were classes that were properly written, they should automatically initialize (and clean up, if necessary) by themselves.
In a way this is similar and related to RAII in that RAII means that resources (memory, handles, whatever) are acquired and cleaned up automatically by the object. | RAII and uninitalized values | [
"",
"c++",
"raii",
""
] |
In the interest of reusing some existing code that was defined as an instance method of a different class, I was tying to do something like the following:
```
class Foo(object):
def __init__(self):
self.name = "Foo"
def hello(self):
print "Hello, I am " + self.name + "."
class Bar(object):
def __init__(self):
self.name = "Bar"
bar = Bar()
Foo.hello(bar)
```
but that results in:
> TypeError: unbound method hello() must be called with Foo instance as first argument (got Bar instance instead)
Is something like this possible?
---
I should have been clear that I know this is a bad idea. Obviously the real solution is a bit of refactoring. I just figured there must be a way, and it turns out there is.
Thanks for the comments. | Looks like this works:
```
Foo.hello.im_func(bar)
```
> Hello, I am Bar.
I guess I need to read a [this](http://docs.python.org/reference/datamodel.html) little harder... | It happens because python wraps class functions as an "unbound method" which performs this type checking. There's some description of the decisions involved in this [here](http://python-history.blogspot.com/2009/02/first-class-everything.html).
Note that this type checking has actually been dropped in python 3 (see the note at the end of that article), so your approach will work there. | In Python, can you call an instance method of class A, but pass in an instance of class B? | [
"",
"python",
"oop",
"coding-style",
""
] |
I am declaring a SQL string that looks something similar to the following:
```
string SQL = "SELECT Column1, Column2, Column3, Date1, Date2 FROM Somewhere";
```
The number of columns can vary by circumstance and the dates can be called different names such as StartDate, InterestDate and so on.
What I would like to do is bind this to an ASP.NET Repeater and create a table as below for the example above:
```
<table>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Date1</th>
<th>Date2</th>
</tr>
<tr>
Rows of values...
</tr>
</table>
```
I am fine with binding the data to a Repeater and using Eval but that is dependent on a fixed number of columns and column names. Can this be done in a programmatic way? | If you use a GridView you can set the AutoGenerate columns property to true (it is true by default) and then bind the GridView to your data.
To make is super simple, you may want to use a [SQLDataSource](http://www.asp.net/LEARN/data-access/tutorial-47-cs.aspx) control.
The [asp.net site](http://www.asp.net/LEARN/data-access/tutorial-04-cs.aspx) has an overview of databinding in asp.net (uses the ObjectDataSource, but the concepts is exactly the same). This page also covers some of the ways to customize the GridView.
Update: Here is a sample of how you could handle the rowdatabound event to format the date columns (per comments on other answer). This could probably be done better, but this should get you started.
```
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView rowView = (DataRowView)e.Row.DataItem;
for (int i = 0; i < rowView.Row.ItemArray.Length; i++)
{
DateTime? tmpDate = rowView[i] as DateTime?;
if (tmpDate.HasValue)
{
if (tmpDate.Value.Second > 0)
e.Row.Cells[i].Text = tmpDate.Value.ToShortTimeString();
else
e.Row.Cells[i].Text = tmpDate.Value.ToShortDateString();
}
}
}
``` | Here's a link to an example of dynamically creating a repeater at runtime. The only requirement is that an ASP:Panel be on your form in order to inject it.
<http://programming.top54u.com/post/ASP-Net-Repeater-dynamically-using-C-sharp-code.aspx> | How to programmatically add an unknown number of columns using a repeater where some of the columns are declared at runtime in the SQL string? | [
"",
"c#",
"asp.net",
"repeater",
""
] |
Is there really a big difference between Eclipse 3.2 and 3.4? I am currently using 3.2. | Check out the 'New and Noteworthy' pages for a list of new features.
* [3.3 New and Noteworthy](http://giano.com.dist.unige.it/eclipseMirror/eclipse/downloads/drops/R-3.3-200706251500/whatsnew/eclipse-news.html)
* [3.4 New and Noteworthy](http://update.eclipse.org/downloads/drops/R-3.4-200806172000/whatsnew3.4/eclipse-news.html)
Personally, from using 3.4 day-to-day, the improvements are probably not hugely noticeable individually, but the overall experience is much better. If I have to go back to 3.3 or 3.2 I frequently find things that don't work as I expect, and think 'Ah yes, that didn't work in 3.2'. | Read
* [Eclipse 3.3 - New and Noteworthy](http://archive.eclipse.org/eclipse/downloads/drops/R-3.3-200706251500/whatsnew/eclipse-news-part1.html)
* [Eclipse 3.4 - New and Noteworthy](http://update.eclipse.org/downloads/drops/R-3.4-200806172000/whatsnew3.4/eclipse-news.html)
and for the upcoming Galieleo release
* [Eclipse 3.5 - Galileo - New and Noteworthy](http://www.bigsoft.co.uk/blog/index.php/2008/12/10/eclipse-3-5-galileo-new-and-noteworthy)
If you use CDT than there were **major** improvements (indexer, code completion, ...) that you definitely want to get. | Eclipse 3.2 or 3.4? | [
"",
"java",
"eclipse",
""
] |
I'm fairly new to C++ and don't quite understand function parameters with pointers and references. I have an array of Cards that I want to shuffle using the Fisher-Yates shuffle. The deck is declared as
```
Card *deck[deckSize];
```
where deckSize has been declared as 24. The array is then initialized.
I then call the shuffle function:
```
void shuffle (Card * deck[]) {
int deckSize = 24;
while (deckSize > 1) {
long int k = lrand48();
k = k %24;
deckSize--;
Card * temp = deck[deckSize];
deck[deckSize] = deck[k];
deck[k] = temp;
}
}
```
If I try to print the value of a card after calling the shuffle function I get a seg fault. Any pointers on how to do this properly? | It looks that your problem does not come from the code posted, which looks fine at a first glance, but from the code around it.
What about using a standard container of cards ? You must fill it, print it first to see if it's ok, shuffle, and then print it again.
```
#include <vector>
std::vector<Card> deck; // Empty for now. Must be filled with cards.
void shuffle (std::vector<Card> & deck)
{
int deckSize = 24;
while (deckSize > 1)
{
long int k = lrand48();
k = k %24;
deckSize--;
Card temp = deck[deckSize];
deck[deckSize] = deck[k];
deck[k] = temp;
}
}
``` | Just use `std::random_shuffle` found in `<algorithm>`, like this:
```
std::random_shuffle(deck, deck + deckSize);
```
and your deck with be shuffled. | C++ Array Shuffle | [
"",
"c++",
"arrays",
"pointers",
""
] |
I have a problem with a search query I am using my data contains names and information that has apostrophes in various forms (HTML encoded and actual).
So for example I would like an alternative to this:
```
SELECT * FROM Customers WHERE REPLACE(LastName,'''','')
LIKE Replace('O''Brien,'''','')
```
This is just an example, what I want is a way where if someone types OBrien or O'Brien this will still work, I need to replace three versions of the character and the data is feed sourced and cannot be changed - what can be done to a query to allow for this kind of search to work.
I have Items with names which work this way which currently have many nested REPLACE functions and cannot seem to find something that will work this way, which is more efficient.
I am using MS SQL 2000 with ASP if that helps.
---
**Edit**
Here is the query that needs to match O'Brien or OBrien, this query does this but is too inefficient - it is joined by another for Item Names and FirstName (optional) for matching.
```
SELECT * FROM Customers
WHERE
REPLACE(REPLACE(REPLACE(LastName,''',''),''',''),'''','')
LIKE
REPLACE(REPLACE(REPLACE('%O'Brien%',''',''),''',''),'''','')
``` | If you want to stay correct and do this in SQL this is probably the best you can do
```
SELECT * FROM Customers WHERE
LastName LIKE 'O%Brien' AND
REPLACE(LastName,'''','') LIKE 'O''Brien'
```
You will still get table scans sometimes, due to poor selectivity.
The reason for the first where is to try to use an existing index.
The reason for the second match is to ensure that last names like ObbBrien do not match.
Of course the best thing to do would be not to need the ugly replace. This could be achieved in the app by storing an additional clean lastname column. Or in a trigger. Or in an indexed view. | You could try this:
```
SELECT *
FROM Customers
WHERE LastName LIKE Replace('O''Brien,'''','%')
```
This *should* allow it to use an index as you are not modifying the original column. | How to search for matches with optional special characters in SQL? | [
"",
"sql",
"search",
"apostrophe",
""
] |
I have a DataGrid that is using a DataReader as its datasource. I want to hide the first column of the datagrid. I am using the .net compact framework 3.5. I can find examples for windows forms but the api is changed enough that they don't work. | You can set the column style width to `0` or `-1`.
```
DataGridTableStyle ts = new DataGridTableStyle();
ts.MappingName = "Order";
// Order date column style
DataGridColumnStyle cust_id = new DataGridTextBoxColumn();
cust_id.MappingName = "cust_id";
cust_id.HeaderText = "ID";
//Hide Customer ID
cust_id.Width = -1;
ts.GridColumnStyles.Add(cust_id);
// Shipping name column style
DataGridColumnStyle cust_name = new DataGridTextBoxColumn();
cust_name.MappingName = "cust_name";
cust_name.HeaderText = "Customer";
cust_name.Width = 500;
ts.GridColumnStyles.Add(cust_name);
GridView1.TableStyles.Add(ts);
``` | In any event, before you
assign the datasource, hide the columns you do not want to show:
```
ds.Tables("dtRecords").Columns("ID").ColumnMapping = MappingType.Hidden
Datagrid1.datasource = ds.Tables("dtRecords")
``` | How do you hide a column in a datagrid using the .net compact framework 3.5 | [
"",
"c#",
".net",
"datagrid",
"windows-mobile",
"compact-framework",
""
] |
This should be a common scenario, but could not find any relevant post yet..
I plan to deploy a Python library (I guess the same applies to regular applications) which makes use of some images and other resource files. What is the standard location for such items? I imagine, for project `Foo`, the choices would be
* Have `resources` directory in the source repository and then move files to `/usr/share/foo/`
* Place resources directly inside the python package that goes under `/usr/lib/python-<version>/foo/`
Any suggestions?
**Edit:** As suggested, clarifying that the main platform this will be running on is Linux. | This question is somewhat incomplete, because a proper answer would depend on the underlying operating system, as each has its own modus operandi. In linux (and most unix based OSs) for example /usr/share/foo or /usr/local/share/foo would be the standard. In OS X you can do the same, but I would think "/Library/Application Support/Foo" (although that's usually for storing settings and whatnot) would be the place to put such things, though if you're writing libraries following the "Framework" idea, all the resources would be included in the /Library/Frameworks/Foo.Framework" ... Apps on OS X on the other hand should keeps all there resources within the Resources directory inside Foo.app | We put non .py files in `/opt/foo/foo-1.2/...`
Except, of course, for static media that is served by Apache, that goes to `/var/www/html/foo/foo-1.1/media/...`
Except, of course, for customer-specific configuration files. They go to
`/var/opt/customer/foo/...`
Those follow the Linux standards as I understand them.
We try to stay away from `/usr/lib/` and `/lib` kinds of locations because those feel like they're part of the distribution. We lean toward `/opt` and `/var` because they're clearly separated from the linux distro directories. | Standard non-code resource location for python packages | [
"",
"python",
"resources",
"location",
"package",
"shared",
""
] |
I want to call a google service using javascript with a keyword and a website url, and get from google the position of this site while searching with this keyword.
This is possible? can be done just using javascript or will need a server side language? | This link looks promising: [Getting google page rank using javascript](http://abhinavsingh.com/blog/2009/04/getting-google-page-rank-using-javascript-for-adobe-air-apps/) | You're going to have security issues using JavaScript to query another domain that isn't the one that served the HTML.
If you can write your own service, your best bet (for scraping) would be to send a query to this page: <http://www.google.com/ie>. It provides clean HTML that can be parsed with a regular expression. This page is also nice in that you can pass in [a 'num' parameter](http://www.google.com/ie?q=lucky&hl=en&num=100) and get more than just 10 results at a time. (if you're looking for perfect results, when doing this you aren't going to get exactly the same results as going 10 at a time).
With a service like this running on your server, your JavaScript code won't have any problems, until Google notices too many queries coming from your server's IP address and decides to blacklist you. ;)
I'd also suggest using Google's AJAX Search API, if you can live with it being limited to 64 total results. | How to search google programatically with a keyword and get my website rank? | [
"",
".net",
"javascript",
"web-services",
""
] |
In C# ASP.Net, I would like to create and save a text file to a server. This will be happening daily (by a user action, not scheduled).
I would like the location to not be in the application path but in a separate folder (for this question, lets say the folder is off the root).
I am new to this site and if this question is too "open", feel free to let me know.
Thanks for your assistance. | I agree with [Dan Herbert](https://stackoverflow.com/a/922464/4251431). Put the path in web.config and make sure the permissions for the folder are correct.
Also, make sure that path is not on the C drive. That way, if something goes wrong, or if the site is attacked, the c drive won't fill up and crash the server.
Be careful with the permissions; even a simple text file can be dangerous if a hacker can muck with the path somehow. Think about someone overwriting the server's hosts file, for example. | One good practice to follow is to use a `web.config` app setting key to define the output path of your application.
You'd use the `ConfigurationManager.AppSettings` class for retrieving values from a `web.config`. You can read how to do this here:
<http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx> | Creating and saving a text file to the server | [
"",
"c#",
"asp.net",
""
] |
Well in a previous question I asked the same thing, but the answer that i doesn't prevent a submit when the user is in a text-box.
So basically what i need is the ability to keep a person from submitting a form unless the explicitly click the submit button.
edit:
basically the main reason for doing this is that this is an employer survey. the people on this won't be the most technically savvy, and the client i'm making this for has requested this. | i set the form to onsubmit="return false" and did this
```
<input type="button" value="Submit" onClick="document.Survey.submit()" style="font-size: 1.25em;">
``` | ```
$('input').keydown(function(e){
return e.keyCode !== 13;
});
```
... I don't recommend doing this, by the way. | Prevent Users from submitting form by hitting enter #2 | [
"",
"javascript",
"jquery",
"html",
""
] |
So I have an 'export' application that arrives the user at an end page with a textarea with lots of text. Now the workflow is to copy and paste that text from the textarea into a file.
The exported code is getting larger, and we want to encourage users to do this more often, so the copy/paste route is no longer desirable. (Not to mention that my xterm->ssh->screen->vi chain doesn't paste 250K characters so well)
**So the problem is this: I have a textarea that has exported code in it, and I want to provide a button that is 'Download this Code to a file'**
I'm fairly sure that I will have to hit the server again, but I just want to check all my bases. The ways I can think of doing this (sending generated textarea value as a file ot the browser)
* Create a script that receives said text as a POST and sends it back with the right Content Headers. This is no desirable because we would be POSTing 250k, which would be slower than:
* Create a script that regenerates the text area and provide a button the original page that hits the scripts and downloads the file. *This is the option I am leaning towards*
* Use Javascript somehow and perhaps beable to skip the server all together and just send the $('.exported').val() to the browser with the right headers? Not sure how to do this atm.
So if anyone has suggestions that'd be great, maybe I'm overlooking something. Thanks!
edit: [Download textarea contents as a file using only Javascript (no server-side)](https://stackoverflow.com/questions/609530/download-textarea-contents-as-a-file-using-only-javascript-no-server-side)
This question says the JS route is not possible (probable) | I would go with option 2. Simplest and fastest. The other ones are a bit contrived.
If you go with option 2, why even leave the textarea at all? | I would suggest the following: make your button replace the whole DOM of the page with your text. After that, user will be able to simply press `Ctrl`+`S` or ⌘S. Not exactly what you want, but still a shortcut.
I guess you can do it with the following (jQuery):
```
$ (document.body).html ($ ('#textarea-id').html)
```
(Not tested) | Download part of HTML page as text (PHP) | [
"",
"php",
""
] |
We have two zope servers running our company's internal site. One is the live site and one is the dev site. I'm working on writing a python script that moves everything from the dev server to the live server. Right now the process involves a bunch of steps that are done in the zope management interface. I need to make all that automatic so that running one script handles it all. One thing I need to do is export one folder from the live server so that I can reimport it back into the live site after the update. How can I do this from a python script?
We're using Zope 2.8 and python 2.3.4 | You can try to use the functions `manage_exportObject` and `manage_importObject` located in the file `$ZOPE_HOME/lib/python/OFS/ObjectManager.py`
Let say we install two Zope 2.8 instances located at:
* `/tmp/instance/dev` for the development server (port 8080)
* `/tmp/instance/prod` for the production server (port 9090)
In the ZMI of the development server, I have created two folders `/MyFolder1` and `/MyFolder2` containing some page templates. The following Python script exports each folder in .zexp files, and imports them in the ZMI of the production instance:
```
#!/usr/bin/python
import urllib
import shutil
ids_to_transfer = ['MyFolder1', 'MyFolder2']
for id in ids_to_transfer:
urllib.urlopen('http://admin:password_dev@localhost:8080/manage_exportObject?id=' + id)
shutil.move('/tmp/instance/dev/var/' + id + '.zexp', '/tmp/instance/prod/import/' + id + '.zexp')
urllib.urlopen('http://admin:password_prod@localhost:9090/manage_delObjects?ids=' + id)
urllib.urlopen('http://admin:password_prod@localhost:9090/manage_importObject?file=' + id + '.zexp')
``` | To make this more general and allow copying folders not in the root directory I would do something like this:
```
#!/usr/bin/python
import urllib
import shutil
username_dev = 'admin'
username_prod = 'admin'
password_dev = 'password_dev'
password_prod = 'password_prod'
url_dev = 'localhost:8080'
url_prod = 'localhost:9090'
paths_and_ids_to_transfer = [('level1/level2/','MyFolder1'), ('level1/','MyFolder2')]
for path, id in ids_to_transfer:
urllib.urlopen('http://%s:%s@%s/%smanage_exportObject?id=%s' % (username_dev, password_dev, url_dev, path, id))
shutil.move('/tmp/instance/dev/var/' + id + '.zexp', '/tmp/instance/prod/import/' + id + '.zexp')
urllib.urlopen('http://%s:%s@%s/%smanage_delObjects?ids=%s' % (username_prod, password_prod, url_prod, path, id))
urllib.urlopen('http://%s:%s@%s/%smanage_importObject?file=%s.zexp' % (username_prod, password_prod, url_prod, path, id))
```
If I had the rep I would add this to the other answer but alas...
If someone wants to merge them, please go ahead. | Exporting a zope folder with python | [
"",
"python",
"zope",
""
] |
I ran across a compilation issue today that baffled me. Consider these two container classes.
```
public class BaseContainer<T> : IEnumerable<T>
{
public void DoStuff(T item) { throw new NotImplementedException(); }
public IEnumerator<T> GetEnumerator() { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { }
}
public class Container<T> : BaseContainer<T>
{
public void DoStuff(IEnumerable<T> collection) { }
public void DoStuff <Tother>(IEnumerable<Tother> collection)
where Tother: T
{
}
}
```
The former defines `DoStuff(T item)` and the latter overloads it with `DoStuff <Tother>(IEnumerable<Tother>)` specifically to get around the absence of [covariance/contravariance](https://stackoverflow.com/questions/6557/in-c-why-cant-a-liststring-object-be-stored-in-a-listobject-variable/6574#6574) of C# (until 4 I hear).
This code
```
Container<string> c = new Container<string>();
c.DoStuff("Hello World");
```
hits a rather strange compilation error. Note the absence of `<char>` from the method call.
> The type 'char' cannot be used as type parameter 'Tother' in the generic type or method 'Container.DoStuff(System.Collections.Generic.IEnumerable)'. There is no boxing conversion from 'char' to 'string'.
Essentially, the compiler is trying to jam my call to `DoStuff(string)` into `Container.DoStuff<char>(IEnumerable<char>)` because `string` implements `IEnumerable<char>`, rather than use `BaseContainer.DoStuff(string)`.
The only way I've found to make this compile is to add `DoStuff(T)` to the derived class
```
public class Container<T> : BaseContainer<T>
{
public new void DoStuff(T item) { base.DoStuff(item); }
public void DoStuff(IEnumerable<T> collection) { }
public void DoStuff <Tother>(IEnumerable<Tother> collection)
where Tother: T
{
}
}
```
**Why is the compiler trying to jam a string as `IEnumerable<char>` when 1) it knows it can't (given the presence of a compilation error) and 2) it has a method in the base class that compiles fine?** Am I misunderstanding something about generics or virtual method stuff in C#? Is there another fix other than adding a `new DoStuff(T item)` to `Container`? | **Edit**
Ok... I think I see your confusion now. You would have expected DoStuff(string) to have kept the parameter as a string and walked the BaseClass Method List first looking for a suitable signature, and failing that fallback to trying to cast the parameter to some other type.
But it happened the other way around... Instead `Container.DoStuff(string)` went, meh "theres a base class method there that fits the bill, but I'm going to convert to an IEnumerable and have a heart attack about what's available in the current class instead...
Hmmm... I'm sure Jon or Marc would be able to chime in at this point with the specific C# Spec paragraph covering this particular corner case
**Original**
Both Methods expect an IEnumerable Collection
You're passing an individual string.
The compiler is taking that string and going,
> Ok, I have a string, Both methods
> expect an `IEnumerable<T>`, So I'll
> turn this string into an
> `IEnumerable<char>`... Done
>
> Right, Check the first method...
> hmmm... this class is a
> `Container<string>` but I have an
> `IEnumerable<char>` so that's not right.
>
> Check the second method, hmmm.... I
> have an `IEnumerable<char>` but char
> doesn't implement string so that's
> not right either.
**COMPILER ERROR**
So what#s the fix, well it completely depends what your trying to achieve... both of the following would be valid, essentially, your types usage is just incorrect in your incarnation.
```
Container<char> c1 = new Container<char>();
c1.DoStuff("Hello World");
Container<string> c2 = new Container<string>();
c2.DoStuff(new List<string>() { "Hello", "World" });
``` | As Eric Lippert explained, the compiler chooses the `DoStuff<Tother>(IEnumerable<Tother>) where Tother : T {}` method because it chooses methods before checking constraints. Since string can do `IEnumerable<>`, the compiler matches it to that child class method.
The **compiler is working correctly** as described in the C# specification.
The method resolution order you desire can be forced by implementing DoStuff as an [extension method](http://msdn.microsoft.com/en-us/library/bb383977.aspx).
Extension methods are checked *after* base class methods, so it will not try to match `string` against `DoStuff`'s `IEnumerable<Tother>` until *after* it has tried to match it against `DoStuff<T>`.
The following code demonstrates the desired method resolution order, covariance, and inheritance. Please copy/paste it into a new project.
This biggest **downside** I can think of so far is that you can not use `base` in the overriding methods, but I think there are ways around that (ask if you are interested).
```
using System;
using System.Collections.Generic;
namespace MethodResolutionExploit
{
public class BaseContainer<T> : IEnumerable<T>
{
public void DoStuff(T item) { Console.WriteLine("\tbase"); }
public IEnumerator<T> GetEnumerator() { return null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; }
}
public class Container<T> : BaseContainer<T> { }
public class ContainerChild<T> : Container<T> { }
public class ContainerChildWithOverride<T> : Container<T> { }
public static class ContainerExtension
{
public static void DoStuff<T, Tother>(this Container<T> container, IEnumerable<Tother> collection) where Tother : T
{
Console.WriteLine("\tContainer.DoStuff<Tother>()");
}
public static void DoStuff<T, Tother>(this ContainerChildWithOverride<T> container, IEnumerable<Tother> collection) where Tother : T
{
Console.WriteLine("\tContainerChildWithOverride.DoStuff<Tother>()");
}
}
class someBase { }
class someChild : someBase { }
class Program
{
static void Main(string[] args)
{
Console.WriteLine("BaseContainer:");
var baseContainer = new BaseContainer<string>();
baseContainer.DoStuff("");
Console.WriteLine("Container:");
var container = new Container<string>();
container.DoStuff("");
container.DoStuff(new List<string>());
Console.WriteLine("ContainerChild:");
var child = new ContainerChild<string>();
child.DoStuff("");
child.DoStuff(new List<string>());
Console.WriteLine("ContainerChildWithOverride:");
var childWithOverride = new ContainerChildWithOverride<string>();
childWithOverride.DoStuff("");
childWithOverride.DoStuff(new List<string>());
//note covariance
Console.WriteLine("Covariance Example:");
var covariantExample = new Container<someBase>();
var covariantParameter = new Container<someChild>();
covariantExample.DoStuff(covariantParameter);
// this won't work though :(
// var covariantExample = new Container<Container<someBase>>();
// var covariantParameter = new Container<Container<someChild>>();
// covariantExample.DoStuff(covariantParameter);
Console.ReadKey();
}
}
}
```
Here is the output:
```
BaseContainer:
base
Container:
base
Container.DoStuff<Tother>()
ContainerChild:
base
Container.DoStuff<Tother>()
ContainerChildWithOverride:
base
ContainerChildWithOverride.DoStuff<Tother>()
Covariance Example:
Container.DoStuff<Tother>()
```
**Can you see any problems with this work around?** | Generics, inheritance, and failed method resolution of C# compiler | [
"",
"c#",
"generics",
"compilation",
""
] |
I have downloaded the Phoenix SDK June 2008 (Tools for compilers) and when I'm reading the code of the Hello sample, I really feel lost.
```
public
ref class Hello
{
//--------------------------------------------------------------------------
//
// Description:
//
// Class Variables.
//
// Remarks:
//
// A normal compiler would have more flexible means for holding
// on to all this information, but in our case it's simplest (if
// somewhat inelegant) if we just keep references to all the
// structures we'll need to access as classstatic variables.
//
//--------------------------------------------------------------------------
static Phx::ModuleUnit ^ module;
static Phx::Targets::Runtimes::Runtime ^ runtime;
static Phx::Targets::Architectures::Architecture ^ architecture;
static Phx::Lifetime ^ lifetime;
static Phx::Types::Table ^ typeTable;
static Phx::Symbols::Table ^ symbolTable;
static Phx::Phases::PhaseConfiguration ^ phaseConfiguration;
```
2 Questions : What's that ref keyword?
What is that sign ^ ? What is it doing
protected:
```
virtual void
Execute
(
Phx::Unit ^ unit
) override;
```
};
override is a C++ keyword too? It's colored as such in my Visual Studio.
I really want to play with this framework, but this advanced C++ is really an obstacle right now. Thank you. | It's not standard C++, it's [C++/CLI](http://en.wikipedia.org/wiki/C%2B%2B/CLI). | It's a Microsoft extension for use with .NET. The caret indicates a handle to an object stored on the managed heap. See [Bran Bray's](http://blogs.msdn.com/branbray/archive/2003/11/17/51016.aspx) blog for a nice description. | Some questions about special operators i've never seen in C++ code | [
"",
"c++",
"syntax",
"c++-cli",
""
] |
I am curious as how to how much trouble / money it would be for me to be able to accept incoming text messages to a number, which I would then pass to a server side application in PHP. I'd ultimately send SMS messages back out via email addresses.
Does anyone know any good Canadian providers to accept incoming SMS messages? How much do these cost generally? Is the cost and effort worth it for personal projects?
Thank you, | I am looking for the same thing. Found www . smsgateway . ca so far. Spoke to them and they sound good with reasonable prices. Haven't tried it yet though. | Clickatell seems to offer incoming SMS support in Canada:
[www.clickatell.com](http://www.clickatell.com/pricing/standard_mo_coverage.php?country=45)
Edit: I'm sorry I think I may have misread that page. Looks like it's showing costs for messages sent from Canada but the possible number ranges are +44 (UK), +61 (Australia), +45 (Denmark) and +46 (Sweden). So the sender will pay international SMS rates for sending to your number.
For personal projects it might be easier to get hold of a cheap phone and prepaid SIM and plug that onto a computer somewhere and write a script to pull the SMSes, usually by sending AT commands to a virtual COM port.
For a hosted solution there is usually a monthly cost to rent the number (higher for a "short code" number). Then there is the charge for each incoming message.
Edit: Clickatell do seem to offer a shortcode service in Canada. $1000 setup and $1200 monthly rental. | Advice on a Canadian SMS Gateway provider | [
"",
"php",
"mobile",
"scripting",
"sms",
"sms-gateway",
""
] |
I am looking for a way to generate pseudo random number sequences that will yield identical sequence results for a given seed across any platform. I am assuming that `rand()` / `srand()` is not going to be consistent (I could easily be wrong about this assumption). | Something like a [Mersenne Twister (from Boost.Random)](http://www.boost.org/doc/libs/1_39_0/libs/random/random-generators.html#mt19937) is deterministic. | Knuth has [released into the public domain C (and FORTRAN) source code](http://www-cs-faculty.stanford.edu/~knuth/news02.html#rng) for the pseudo-random number generator described in section 3.6 of *The Art of Computer Programming*. | Consistent pseudo-random numbers across platforms | [
"",
"c++",
"c",
"random",
""
] |
Does anyone know how to pass a several bytes into a Binary (or varbinary) field using SQL and ideally in ADO (classic) & VBScript (or Visual Basic 6)?
I wish to encode 10-20 (maybe more) bytes of data and have this data stored in a SQL db field. (Its not MS-SQLSVR, but I'm hoping that a standard SQL supported format will work!)
The bytes are available as either a string of bytes obtained via AscB/ChrB, OR, an array of 'bytes' (actually variants of type byte obtained via 'cbyte') and stored in the array.
**First option: using the string format**
I have had some (limited) success creating the SQL insert as:
```
x = ".>?hD-&91k[=" '<psuedo string of chars, some unprintable
Insert Into rawtest (byt) Values (CAST('" & x & "' as SQL_BINARY(12)))
```
But I am concerned that string nulls will truncate the data in the field and other non-printing control characters will get in the way of handling the data. Is there a way to avoid this?
**Second Option: Byte Array**
I can put the data in a array easily enough, but cannot see how to pass to the SQL Insert statement. If I attempt to pass in 12 bytes, the insert fails due to the CAST attempting to store the data into a Integer (4bytes). If I pass in a single byte, it works, eg:
```
x = a(0)
```
And continues to work for 4 bytes, but fails when the Integer overflows. Also, it reorders the data
I've attempted to use various workarounds:
```
Insert Into rawtest (byt) Values (CAST('12,34,45' as SQL_BINARY(12)))
Insert Into rawtest (byt) Values (CAST(&h12&h34 as SQL_BINARY(12)))
Insert Into rawtest (byt) Values (CAST(0x123456789012 as SQL_BINARY(12)))
```
I've also tried similar combinations with:
```
Insert Into rawtest (byt) Values (CONVERT('" & x & "', SQL_BINARY)
```
But these all fail!
Ideally, I want a method, any method, that takes a small binary-array of upto 20 bytes(ideally full byte range 0-255, but could take less) and passes them thru to a plain, raw, binary SQL field.
Ideally I need to do this in VBScript/ADO, but can take a VB6 based solution if available. I want this as 'raw' binary, I don't want to use an ascii-encoding, like Base64.
I've googled till I'm numb and havn't not found much atall relevant to binary fields in SQL.
Can you help? Any answers appreciated. Many thx. | Classic ADO can manipulate very large (>8000) varbinary and image (blob) fields directly without chunking. Below is a sample against MS SQL Server that inserts binary data into a table with an INT ID field and a varbinary(100) field. In this example a parameterized SQL query is inserting the binary data from a Variant. The Variant just needs to be populated with the binary data.
```
Dim vntBlobData As Variant
vntBlobData = "ReplaceThisWithBinaryData - A byte array will work"
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.ConnectionString = "Provider = sqloledb; Data Source = DBServerName; Initial Catalog = DBName; User ID = UserID; Password = Password; Persist Security Info = False"
cn.Open
Dim strQry As String
strQry = "INSERT INTO TestBinaryTable (ID, BlobData) VALUES (?, ?)"
Dim cm As ADODB.Command
Set cm = New ADODB.Command
cm.ActiveConnection = cn
cm.CommandText = strQry
cm.Parameters.Append cm.CreateParameter("@ID", adInteger, adParamInput, , 1)
cm.Parameters.Append cm.CreateParameter("@BlobData", adVarBinary, adParamInput, 100, vntBlobData)
cm.CommandType = adCmdText
cm.Execute
``` | VB6 can access binary columns with the GetChunk and AppendChunk methods of the ADO field class. See this [KB article](http://support.microsoft.com/kb/258038).
This [blog post](http://blogs.msdn.com/rextang/archive/2008/01/13/7091118.aspx) has a function to convert a hex string to a varbinary:
```
CREATE FUNCTION dbo.HexStrToVarBinary(@hexstr varchar(8000))
RETURNS varbinary(8000)
AS
BEGIN
DECLARE @hex char(1), @i int, @place bigint, @a bigint
SET @i = LEN(@hexstr)
set @place = convert(bigint,1)
SET @a = convert(bigint, 0)
WHILE (@i > 0 AND (substring(@hexstr, @i, 1) like '[0-9A-Fa-f]'))
BEGIN
SET @hex = SUBSTRING(@hexstr, @i, 1)
SET @a = @a +
convert(bigint, CASE WHEN @hex LIKE '[0-9]'
THEN CAST(@hex as int)
ELSE CAST(ASCII(UPPER(@hex))-55 as int) end * @place)
set @place = @place * convert(bigint,16)
SET @i = @i - 1
END
RETURN convert(varbinary(8000),@a)
END
``` | How to SQL insert a raw/Binary field value from bytes/integer array using VBScript (or VB6)? | [
"",
"sql",
"vb6",
"vbscript",
"binary",
"ado",
""
] |
I'll keep this brief.
I am trying to keep a map between strings and object pointers, and as such, I use std::map. I have a manager that's a global class that keeps track of the map, and whenever an object's destructor is called, it tells the manager that it has been deleted.
The only way I can think of is to search through the map for the object. Is there an efficient STL solution to this problem? Does a map that is efficient at searching by key as well exist? | No there is not an efficient way of doing this with std::map other than iterating through comparing the values.
However most of the time the key for a value is computable from the value itself. For example using the Name property of a Person object as the key. Is it possible for the manager to store a list of key / value pairs as opposed to the value itself. This would solve your problem without having to rewrite a new algorithm.
Or alternatively you could keep a reverse map on the manager class. Essentially value to key. That way you could use it to compute the key to remove later on. | Looking at [SGI's documentation for the STL](http://www.sgi.com/tech/stl/Map.html),
> Map has the important property that
> inserting a new element into a map
> does not invalidate iterators that
> point to existing elements. Erasing an
> element from a map also does not
> invalidate any iterators, except, of
> course, for iterators that actually
> point to the element that is being
> erased.
So you can store an iterator into the map inside your object, and use that as a constant-time lookup key when you need to go delete its entry. | Removing map element by value | [
"",
"c++",
"stl",
"dictionary",
""
] |
I am setting the value of a textbox via javascript client-side. When I refresh the page the value is lost.
The textbox is not disabled or set to read-only.
I have read suggestions to put the value in a hidden field, I'd prefer not to do this. It seems like a hack.
The textbox is in a user control as such:
```
<div id="Row" class="RaidRow" runat="server">
<asp:Button ID="RaidRowButton" runat="server" CssClass="RaidRowButton" OnClick="RaidRowButton_Click" />
<asp:TextBox ID="CharacterNameTextBox" runat="server" CssClass="RaidRowControl SlotTextBox" MaxLength="12" />
<asp:Label ID="ClassNameLabel" runat="server" CssClass="RaidRowControl ClassLabel" />
</div>
```
This control is on the .aspx page.
When the user double-clicks the textbox, presses enter while the textbox has focus, or changes the text, the following javascript function is called:
```
function VerifyCharacter(slotNumber, event)
{
var enterWasPressed = false;
if (event && event.which == 13)
{
enterWasPressed = true;
}
else if (window.event && window.event.keyCode == 13)
{
enterWasPressed = true;
}
if (event == null || enterWasPressed)
{
var realmName = 'Lightninghoof';
var characterNameTextBox = GetCharacterNameTextBox(slotNumber);
characterNameTextBox.style.color = '#CCCCCC';
var classLabel = GetClassNameLabel(slotNumber);
classLabel.style.color = '#CCCCCC';
classLabel.innerHTML = 'Unknown';
WoW_Stats.CharacterInformation.GetCharacterInformation(realmName, characterNameTextBox.value, slotNumber, GetCharacterInformation_Success, GetCharacterInformation_Failed);
}
}
```
Once the web-service call is complete, the following javascript function is called:
```
function GetCharacterInformation_Success(characterInformationResult)
{
var characterInfo = Sys.Serialization.JavaScriptSerializer.deserialize(characterInformationResult, true);
var classLabel = GetClassNameLabel(characterInfo.SlotNumber);
classLabel.style.color = characterInfo.ClassColor;
classLabel.innerHTML = characterInfo.ClassName;
var characterNameTextBox = GetCharacterNameTextBox(characterInfo.SlotNumber);
characterNameTextBox.style.color = characterInfo.ClassColor;
}
```
The only problem is that when I refresh the page, the text in the CharacterNameTextBox and ClassNameLabel, which were set client-side via javascript, are lost.
How can I make sure the controls retain their value between postbacks? | Refreshing the page (pressing F5) is different than a postback. I don't believe the value in your text box is going to be posted back to the server on a refresh. The value in the text box will get posted back to the server on a postback though (as long as the ReadOnly attribute of the TextBox is not set to true, but that's a different story). | I think if the textbox is not editable : Enabled = False or ReadOnly= false.
Asp.net "for security reasones" takes the value from this textbox from its ViewState.
That's why when you use something like a HiddenField or Input, you can get the value. | ASP.NET textbox losing value after postback when value is changed client-side via javascript | [
"",
"asp.net",
"javascript",
""
] |
Using PHP, I am trying to delete a record, but I want to check if it was successful or not. Is anything returned from a successful `DELETE FROM foo where bar = 'stuff'`?
Alternatively, do you know any other ways to check if a DELETE was successful? Or am I better off just making sure the row exists before I delete it? I am trying to avoid another query if possible. | Assuming you are using [mysql\_query](http://www.php.net/mysql_query):
> For other type of SQL statements, INSERT, UPDATE, **DELETE**, DROP, etc, mysql\_query() returns TRUE on success or FALSE on error.
If you are using [PDO::exec](http://www.php.net/manual/en/pdo.exec.php), then the manual says this:
> PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0.
Don't want to answer snipe, but since this was selected as the answer, I should note that mysql\_query will return `TRUE` even if the query did not actually remove anything. You should use [`mysql_affected_rows`](http://www.php.net/mysql_affected_rows) to check for that. | Additionally, if you care about the number of rows that were affected:
> [Use] [mysql\_affected\_rows()](http://us.php.net/manual/en/function.mysql-affected-rows.php) to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement. | What does a successful MySQL DELETE return? How to check if DELETE was successful? | [
"",
"php",
"mysql",
""
] |
We use the ExpressionEngine CMS (php) to create websites. For each site, we set up a subversion repository and commit the EE installation as well as any custom templates, images, javascript, etc. that are used. Included in the repository is the file containing all of the environment variables and the .htaccess file.
We have a development server with a working copy of the repository updated via post-commit that we use to develop. When we are ready to release we create a branch in subversion, make any changes required for the production environment, tag the release number, export the repository, upload it to a new directory on the live server, and symlink the files into place. A rollback is as simple as symlinking back to the previous release.
The problem is that step where we have to modify the environment variables that need to be different for the dev and production servers. This is stuff like (un)commenting htaccess rules that would redirect to the wrong places, swapping out google map API keys because the domains are different, running scripts that minimize the javascript into one obfuscated file to keep the size and http connections down, etc.
The question is how could this be more automated? We would love to get the release procedure down to the bare minimum. I'm familiar with the existence of tools such as Capistrano and Make but I'm not sure how I could get them to modify all the files necessary... how would you organize such a thing? Is this worth spending time automating when it happens maybe once every couple of weeks? | A lot of the configuration options could be dealt with by switching on $\_SERVER['HTTP\_HOST'].
For example
```
switch ($_SERVER['HTTP_HOST']) {
case 'developement.domain.com':
$api_key = "dev environment api key";
break;
default:
$api_key = "live environment api key";
}
```
Then for .htaccess issues you can set an alternate .htaccess file in your vhost definition using the AccessFileName directive:
```
<VirtualHost *:80>
ServerName sitename
AccessFileName .htaccess-dev
</VirtualHost>
``` | I deal with this problem by adding configuration file to **Subversion ignore list**. It was already addressed here on Stackoverflow: [see question #149485](https://stackoverflow.com/questions/149485/how-to-store-configuration-parameters-in-svn/149590#149590)
Basically, I only keep `setup.default.php` in SVN, and in every installation I manually copy it to `setup.php` which is on ignore list. This prevents the file to be checked back in to the repo. There are rarely changes to this file and can be handled as the requirement occurs. | maintaining configuration differences between dev and live environments during deployment from SVN | [
"",
"php",
"svn",
"configuration",
"makefile",
"release-management",
""
] |
I know how to run a single target in ANT, but it also checks the "depends" attribute and runs those before the target. Is there a way to prevent this or a way to structure my ANT file so that I can do this more easily? | Create a "withoutdeps" version of the target. If you had
```
<target name="A" depends="B">
...
</target>
```
Change to
```
<target name="A" depends="B,AwithoutDeps"/>
<target name="AwithoutDeps">
...
</target>
```
Now you can call A as normal (which will fire off B then AwithoutDeps) or just call AwithoutDeps explicitly and no deps fired. [Note that "depends" calls the dependencies in order]
Of course, choose some better names than these ;) | I think your only simple choice here would be to just make a copy of the target in question and make it not have dependencies. | ANT - Run a single target but without dependencies | [
"",
"java",
"ant",
"build",
""
] |
I am crunching through many gigabytes of text data and I was wondering if there is a way to improve performance. For example when going through 10 gigabytes of data and not processing it at all, just iterating line by line, it takes about 3 minutes.
Basically I have a dataIterator wrapper that contains a BufferedReader. I continuously call this iterator, which returns the next line.
Is the problem the number of strings being created? Or perhaps the number of function calls. I don't really know how to profile this application because it get compiled as a jar and used as a STAF service.
Any and all ideas appreciated? | Lets start from the basis: **your application is I/O-bound**. You are not suffering bad performance due to object allocation, or memory, or CPU limits. Your application is running slowly because of disk access.
If you think you can improve file access, you might need to resort to lower-level programming using the JNI. File access can be improved if you handle it more efficiently by yourself, and that will need to be done on a lower level.
I am not sure that using `java.nio` will give you better performance by magnitude which you are looking for, although it might give you some more freedom in doing CPU/memory intensive operations while I/O is running.
The reason being is that basically, `java.nio` wraps the file reading with a selector, letting you be notified when a buffer is read for use, indeed giving you the asynchronous behavior which might help your performance a bit. But *reading the file itself* is your bottleneck, and `java.nio` doesn't give you anything in that area.
So try it out first, but I wouldn't keep my hopes too high for it. | I think the [Java's NIO package](http://java.sun.com/javase/6/docs/api/java/nio/package-summary.html) would be immensely useful for your needs.
[This Wikipedia article](http://en.wikipedia.org/wiki/New_I/O) has some great background info on the specific improvements over "old" Java I/O. | Improve BufferedReader Speed | [
"",
"java",
"performance",
""
] |
I would appreciate any help as C++ is not my primary language.
I have a template class that is derived in multiple libraries. I am trying to figure out a way to uniquely assign an id int to each derived class. I need to be able to do it from a static method though, ie.
```
template < class DERIVED >
class Foo
{
public:
static int s_id()
{
// return id unique for DERIVED
}
// ...
};
```
Thank you! | Here's what I ended up doing. If you have any feedback (pros, cons) please let me know.
```
template < class DERIVED >
class Foo
{
public:
static const char* name(); // Derived classes will implement, simply
// returning their class name
static int s_id()
{
static const int id = Id_factory::get_instance()->get_id(name());
return id;
}
// ...
};
```
Essentially the id will be assigned after doing a string comparison rather than a pointer comparison. This is not ideal in terms of speed, but I made the id static const so it will only have to calculate once for each DERIVED. | This can be done with very little code:
```
template < class DERIVED >
class Foo
{
public:
static int s_id()
{
return reinterpret_cast<int>(&s_id);
}
};
``` | Unique class type Id that is safe and holds across library boundaries | [
"",
"c++",
"class",
"templates",
"unique",
""
] |
can any one tell me the best way to learn spring.
i have sound work experience in struts. and little experience in jsp and hibernate
thanks in advance | The best way is to use it!
Write a simple app using Spring (use the standard docs) and then go back and rewrite it. Write lots of code.
Spring Recipes is also a good book. | I found [Spring in Action](http://www.amazon.co.uk/Spring-Action-Craig-Walls/dp/1933988134/ref=sr_1_1?ie=UTF8&s=books&qid=1243325673&sr=8-1) to be an excellent guide | can any one tell me which is the best way to learn spring | [
"",
"java",
"spring",
""
] |
I'm somewhat new to OOP programming so it's very likely I'm making some stupid mistake. Here is my problem. When running my code I get the following error:
> **Fatal error:** Call to a member function checkLogin() on a non-object in **/application/libraries/Session.php** on line **30**
Below is the Session.php file (I've commented line 30 to make it easier to find):
```
<?php
require_once(LIBPATH . 'MySQLDB.php');
require_once(LIBPATH . 'Authentication.php');
class Session {
public $url;
public $referrer;
public $redirect;
function Session() {
$this->startSession();
}
function startSession() {
global $auth;
session_start();
if (isset($_SESSION['url'])) {
$this->referrer = $_SESSION['url'];
} else {
$this->referrer = '/';
}
$this->url = $_SESSION['url'] = $_SERVER['PHP_SELF'];
if (isset($_SESSION['redirect'])) {
$this->redirect = $_SESSION['redirect'];
} else {
$this->redirect = $_SESSION['redirect'] = '/';
}
$auth->checkLogin(); // LINE 30
}
function setRedirect($page) {
$this->redirect = $_SESSION['redirect'] = $page;
}
}
```
In my attempts to troubleshoot the problem I put echo gettype($auth) between the includes and class declaration. The resulting output was "Object." I then tried putting echo gettype($auth) right after I declare global $auth in the startSession function. The resulting output was "NULL." Any idea as to what my problem may be? Thanks.
**EDIT:** $auth is declared in Authentication.php | Without seeing how `$auth` is defined in `Authentication.php`, it's hard to help.
Also, since you're new to OOP let me be the first to tell you that **globals are bad**. Just don't use them. If you feel you have to, most likely it's because you have a bad design. You should rethink that instead of using globals to quick-fix your problem. Instead, instantiate a new instance of your `Authentication` class by doing something like
```
$auth = new Authentication;
```
Make sure `Authentication` is actually setup properly as a class and everything. PHP's online docs has a good [OOP introduction](http://us.php.net/oop) you may want to take a look at, too. | The problem isn't in the code that you're actually showing. I'm quite confident that the real issue lies somewhere after the declaration of Session but before you actually create an instance of it. Try inserting var\_dump($auth); right before you invoke `new Session` and see if it's actually set there. Then you can probe the code backwards and locate the point where it's unset.
Also, as have already been mentioned: Globals should be avoided. A better solution would be to pass `$auth` as a parameter to the constructor of `Session` and store it as a member variable of the class. | Problem with Global Variables | [
"",
"global-variables",
"php",
""
] |
How can I read the client's machine/computer name from the browser?
Is it possible using JavaScript and/or ASP.NET? | You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:
```
function GetComputerName() {
try {
var network = new ActiveXObject('WScript.Network');
// Show a pop up if it works
alert(network.computerName);
}
catch (e) { }
}
```
It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.
Here is a link to some more info on WScript: [More Information](http://www.pctools.com/guides/scripting/id/3/?act=reference) | Browser, Operating System, Screen Colors, Screen Resolution, Flash version, and Java Support should all be detectable from JavaScript (and maybe a few more). However, computer name is not possible.
EDIT: Not possible across all browser at least. | How can I read the client's machine/computer name from the browser? | [
"",
"javascript",
"asp.net",
"computer-name",
""
] |
I have a crystal report that I have to add a Bar Code to. I have downloaded some free and demo TrueType fonts Code 39, Code 128 and UPC from various sources. When I print out the report I can see the bar code but it will not scan with my scanner(the scanner works as I have tested it on multiple other bar codes). Do I need to use something special with Crystal Reports to create a bar code that a scanner can read?
(I have tried printing it on a label printer designed for printing labels so I don't think it is an issue with the paper/resolution) | Indeed most barcodes have checksums and/or leading & trailing characters.
The most simple one is Code 3 of 9. To use it you need to start and end the code with an \*.
Examples:
* to print **ABCD** you need to use **\*ABCD\***
Some characters require to be escaped as well:
* to print **#123**! you need to use **\*/C123/A\***
More info on [Code 3 of 9](http://en.wikipedia.org/wiki/Code_39). | Barcodes have check digits embedded in them, and you need to reproduce that in addition to using the font. I believe there are third party libraries for Crystal that properly format barcodes so they are scannable. | Print Bar code using Crystal Reports | [
"",
"c#",
".net",
"asp.net",
"crystal-reports",
""
] |
I have a query where I join a table on itself to find mismatches between a parts height or width. The only problem is that because of this join it will return each miss-match twice for each part. I only want to return one row for each miss-match, not two.
Here's the table:
```
tblTagGlass
JobID varchar
UnitCode varchar
PartCode varchar
PartQty int
TagHeight float
TagWidth float
```
and the query:
```
select *
from tblTagGlass ttg
inner join tblTagGlass ttgC ON
ttg.JobID = ttgC.JobID
AND ttg.PartCode = ttgC.PartCode
where ttg.TagHeight != ttgC.TagHeight
or ttg.TagWidth != ttgC.TagWidth
order by ttg.PartCode
```
and the results:
```
INC375 U2-052 VT2-011 1 2013 1444.5 INC375 U2-028 VT2-011 1 2012.5 1444.5
INC375 U2-028 VT2-011 1 2012.5 1444.5 INC375 U2-052 VT2-011 1 2013 1444.5
```
I hope this makes sense... | Try
```
select *
from tblTagGlass ttg
inner join tblTagGlass ttgC ON
ttg.JobID = ttgC.JobID
AND ttg.PartCode = ttgC.PartCode
where (ttg.TagHeight != ttgC.TagHeight OR ttg.TagWidth != ttgC.TagWidth)
AND ((ttg.TagHeight >= ttgC.TagHeight AND ttg.TagWidth >= ttgC.TagWidth)
OR (ttg.TagHeight > ttgC.TagHeight AND ttg.TagWidth < ttgC.TagWidth))
order by ttg.PartCode
```
The difference is using > to compare them instead of != | Let's make an assumption:
* PRIMARY KEY(JobCode, UnitCode, PartCode)
What you are looking for is items with the same JobCode and PartCode but with different UnitCode values - and with a difference in either the TagHeight or TagWidth (or both). So, use the '>' trick on UnitCode to distinguish between rows and prevent duplicates, but '!=' to detect the differences in TagHeight or TagWidth:
```
SELECT *
FROM tblTagGlass ttg JOIN tblTagGlass ttgC
ON ttg.JobID = ttgC.JobID
AND ttg.PartCode = ttgC.PartCode
AND ttg.UnitCode > ttgC.UnitCode
WHERE (ttg.TagHeight != ttgC.TagHeight
OR ttg.TagWidth != ttgC.TagWidth)
ORDER BY ttg.PartCode
``` | Remove double join results from query | [
"",
"sql",
"t-sql",
""
] |
I'm trying to receive and potentially send complex values through TWebBrowser (using TEmbeddedWB) with the provided external object.
For example; in javascript I would try to use the exposed method with an array as a parameter:
```
var test = [123, 'abc'];
external.someFunction(test);
//Or something more complex
var complexObject = {
someMethod : function(){ return 1; },
someProperty : 123,
someArray : ['xyz', 3.14]
}
external.someFunction(complexObject);
```
Checking the VarType of both of these examples tells me it's a IDispatch.
```
function TSomeClass.someFunction(var Param : OleVariant) : OleVariant;
var
vType : Integer;
begin
vType := (VarType(Param) and VarTypeMask); //Says 9 (varDispatch)
Result := true;
end;
```
I'm not completely familiar with COM and I'm not sure how to work with this.
Any help would be appreciated. | You can treat the JScript object just as any other OleVariant COM object. There are a few gotchas in terms of arrays (and just about any JScript object is essentially a sparse array).
After getting the JScript object into an OleVariant you can simply call it as you would any normal code (without compile time checking of course).
Here is some code for dealing with arrays:
```
type
TJScriptArray = class
private
FArray: IDispatchEx;
FCount: Integer;
function GetProperty( const AName: String ): OleVariant;
function GetItem(Index: Integer): OleVariant;
public
constructor Create( AObj: OleVariant );
destructor Destroy; override;
public
property Count: Integer read FCount;
property Item[Index: Integer]: OleVariant read GetItem; default;
end;
function VarToDispatchEx( const AObject: OleVariant ): IDispatchEx;
begin
Result := nil;
if VarType( AObject ) <> varDispatch then
Exit;
Supports( IDispatch(AObject), IDispatchEx, Result );
end;
function IsJScriptArray( const AObject: OleVariant ): Boolean;
var
temp: IDispatchEx;
begin
temp := VarToDispatchEx( AObject );
Result := temp <> nil;
end;
constructor TJScriptArray.Create(AObj: OleVariant);
begin
inherited Create;
FArray := VarToDispatchEx( AObj );
if FArray = nil then
raise Exception.Create( 'TJscriptArray called with invalid parameters.' );
FCount := GetProperty( 'length' );
end;
destructor TJScriptArray.Destroy;
begin
inherited Destroy;
end;
function TJScriptArray.GetItem(Index: Integer): OleVariant;
begin
if Index > FCount then
raise Exception.Create( 'Index out of bounds.' );
Result := GetProperty( IntToStr( Index ) );
end;
function TJScriptArray.GetProperty(const AName: String): OleVariant;
var
sz: WideString;
id: Integer;
res: Variant;
ei: TExcepInfo;
params: TDispParams;
hr: HResult;
begin
{
ACTION: return the specified property from the jscript array
NOTE: since a jscript array is a sparse array there may be
gaps. In that case a null variant is returned. This is
signalled by the name (id) not existing.
}
sz := AName;
hr := FArray.GetDispID( PWideChar(sz), 0, id );
if hr = disp_e_UnknownName then begin
Result := Null;
Exit;
end
else
OleCheck( hr );
VarClear( res );
FillChar( ei, sizeof(ei), 0 );
FillChar( params, sizeof(params), 0 );
OleCheck( FArray.InvokeEx( id, 0, dispatch_PropertyGet, @params, @res, @ei, nil ) );
Result := res;
end;
``` | Although I have not directly done what you you are trying.
with a Variant you can you actually Access methods and properties dynamically.
Basically I suspect you should be able to access everything directly.
```
Param.Someproperty
Param.SomeArray[1]
Param.SomeMethod();
```
You will not get compile time errors if you get things wrong so be careful.
For example the following code compiles, but will give a runtime error of invalid variant operation as there is nothing dynamically assigned to that variable.
```
var
vo : OleVariant;
v : Variant;
begin
v.DoThis;
vo.DoThat;
end;
``` | Receiving complex javascript values through external interface | [
"",
"javascript",
"delphi",
"com",
"browser",
"external",
""
] |
If I need to search on Date of birth which is stored without the hours and minutes but the date I have to search with includes hours and minutes what is the best way to return all rows where date is matched on only day, month and year
i.e.
Stored as 01-JAN-50 10.22.06.000000000
date selected 01-JAN-50 10.22.06.010101120
If I use the date with the hours and minutes the SQL will only return rows with the exact timestamp and not those for just the day, month and year.
The SQL needs to work on Oracle, SQLServer, MySQL and DB2. | Oracle's DATE type pre-dates the SQL standard version (as does Informix's), which makes this extremely difficult - if not impossible - to do in a DBMS-neutral fashion. Of course, there is a question of "why does the data representation chosen include time".
In standard SQL, the obvious technique would be to cast the TIMESTAMP to a DATE. We also don't have a clear explanation of the data you have to search with.
```
SELECT CAST(DateOfBirth AS DATE), ...other columns...
FROM TheMysteryTable -- Why do people hate giving tables names?
WHERE CAST(DateOfBirth AS DATE) =
CAST(TIMESTAMP '1950-01-01 10.22.06.010101120' AS DATE)
```
But that assumes that you write the 'date to search with' as a literal. If it is a host variable, then the type of the host variable should be DATE, not TIMESTAMP. And the DateOfBirth column should probably be a DATE, not a TIMESTAMP. You should not use TIMESTAMP unless the time part is relevant - it wastes storage and it wastes computation time.
Note that because of the casts, it is unlikely that the DBMS will be able to use any indexes or anything. If the types were sane, then the query would be simply:
```
SELECT DateOfBirth, ...other columns...
FROM TheMysteryTable
WHERE DateOfBirth = DATE '1950-01-01'
``` | As any solution is going to require manipulation of date and datetime objects, then there will be no system-agnostic solution - each will have different functions for those objects.
The best solution, other than database abstraction, would be to round off the datetime object being used first, then only a generic SQL comparison clause is required which will be functional in all the listed DBs. | Database agnostic SQL for returning list for Date of birth stored as a Timestamp | [
"",
"sql",
"date",
"timestamp",
"where-clause",
"database-agnostic",
""
] |
I'd like to inject jQuery into a page using the Google AJAX Libraries API, I've come up with the following solution:
**<http://my-domain.com/inject-jquery.js>:**
```
;((function(){
// Call this function once jQuery is available
var func = function() {
jQuery("body").prepend('<div>jQuery Rocks!</div>');
};
// Detect if page is already using jQuery
if (!window.jQuery) {
var done = false;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement("script");
script.src = "http://www.google.com/jsapi";
script.onload = script.onreadystatechange = function(){
// Once Google AJAX Libraries API is loaded ...
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
// ... load jQuery ...
window.google.load("jquery", "1", {callback:function(){
jQuery.noConflict();
// ... jQuery available, fire function.
func();
}});
// Prevent IE memory leaking
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
}
// Load Google AJAX Libraries API
head.appendChild(script);
// Page already using jQuery, fire function
} else {
func();
}
})());
```
The script would then be included in a page on a separate domain:
**<http://some-other-domain.com/page.html>:**
```
<html>
<head>
<title>This is my page</title>
</head>
<body>
<h1>This is my page.</h1>
<script src="http://my-domain.com/inject-jquery.js"></script>
</body>
</html>
```
In Firefox 3 I get the following error:
```
Module: 'jquery' must be loaded before DOM onLoad! jsapi (line 16)
```
The error appears to be specific to the Google AJAX Libraries API, as I've seen others use a jQuery bookmarklet to inject jQuery into the current page. My question:
* Is there a method for injecting the Google AJAX Libraries API / jQuery into a page regardless of the onload/onready state? | If you're injecting, it's probably easier to request the script without using the google loader:
```
(function() {
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
script.onload = script.onreadystatechange = function(){ /* your callback here */ };
document.body.appendChild( script );
})()
``` | I found this post after we figured out a different solution. So for some reason, if you can't use the accepted solution, this one seem to work fine:
```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
// jQuery hasn't been loaded... so let's write it into the head immediately.
document.write('<script type="text/javascript" src="/jquery-1.3.2.min.js"><\/script>')
}
</script>
```
One issue with the accepted solution is that you're forced to put all your code that you want to run on the page into your callback function. So anything that needs jQuery (like plugins) need to be called from that function. AND, all your other included JS files that require jQuery are dependent upon jQuery being loaded BEFORE all the other scripts fire. | Injecting jQuery into a page fails when using Google AJAX Libraries API | [
"",
"javascript",
"jquery",
"google-ajax-libraries",
""
] |
In our project we have requirement that, after receiving sms message from third party
service provider exactly after 3 minutes i need to execute a sql query to update database.
how should i do this , any suggestions are accepted.
\*\* is it possible using stored procedures...
Exactly the scenario is , we are having mediator service application consider it has webservice. from my application when i send a SMS to webservice application via to SMS service provider , this system will push to embedded device , this will make the system to ON. and after 2 min device will send SMS message to pur application thru SMS service provider to say that checking is going on... after receiving this message exactly i need to update database saying that chekcing done succefully. why 3 minutes because exactly after this time device will go Off.
regards,
Mahesh | How exactly are you receiving the SMS Messages. What service is picking them up.
Theres a couple of ways you could do it.
In your Application Code on the SMSReceived Event you could kick off a separate thread to sleep for 180 seconds, and then call your SQL Code.
If you want to do it in the database, you'll need some sort of polling thread.
Record the "TimeReceived" and have a bit flag "PostProcessed"
Then you could just have a job that runs every 60 seconds that goes
```
SELECT *
FROM ReceivedSMS
WHERE TimeRecieved < dateadd(second, -180, getdatE()) AND
PostProcessed = 0
FOREACH Record - Execute SPROC & Update PostProcessed = 1.
``` | You can use "SQL jobs"
Look at these articles:
<http://msdn.microsoft.com/en-us/library/ms187910.aspx>
<http://dacosta9.wordpress.com/2008/10/22/how-to-disable-or-enable-a-sql-server-job-programatically/>
Hope this helps. | Executing SQL Query after particular point iof Time | [
"",
"sql",
""
] |
I have often encountered an error such as "cannot convert from 'method group' to 'string'" in cases like:
```
var list = new List<string>();
// ... snip
list.Add(someObject.ToString);
```
of course there was a typo in the last line because I forgot the invocation parentheses after `ToString`. The correct form would be:
```
var list = new List<string>();
// ... snip
list.Add(someObject.ToString()); // <- notice the parentheses
```
However I came to wonder what is a method group. [Google](http://www.google.com/search?hl=ro&client=opera&rls=en&hs=yqM&num=100&newwindow=1&q=what+is+a+method+group+.net&btnG=C%C4%83utare&lr=) isn't much of a help nor [MSDN](http://social.msdn.microsoft.com/search/en-us/?query=method+group). | A method group is the name for a *set of methods* (that might be just one) - i.e. in theory the `ToString` method may have multiple overloads (plus any extension methods): `ToString()`, `ToString(string format)`, etc - hence `ToString` by itself is a "method group".
It can usually convert a method group to a (typed) delegate by using overload resolution - but not to a string etc; it doesn't make sense.
Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call. | Also, if you are using LINQ, you can apparently do something like `myList.Select(methodGroup)`.
So, for example, I have:
```
private string DoSomethingToMyString(string input)
{
// blah
}
```
Instead of explicitly stating the variable to be used like this:
```
public List<string> GetStringStuff()
{
return something.getStringsFromSomewhere.Select(str => DoSomethingToMyString(str));
}
```
I can just omit the name of the var:
```
public List<string> GetStringStuff()
{
return something.getStringsFromSomewhere.Select(DoSomethingToMyString);
}
``` | What is a method group in C#? | [
"",
"c#",
".net",
"method-group",
""
] |
I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically:
I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So:
```
>>> type(myDict)
<type 'dict'>
>>> type(myDict[u'myKey'])
<type 'dict'>
>>> type(myDict[u'myKey'][u'myKey2'])
<type 'list'>
>>> type(myDict[u'myKey'][u'myKey2'][0])
<type 'unicode'>
```
I want to go through and make every string in it lowercase, i.e. every key and every string in every list.
How would you do this? | Really simple way, though I'm not sure you'd call it Pythonic:
```
newDict = eval(repr(myDict).lower())
```
Saner way:
```
newDict = dict((k1.lower(),
dict((k2.lower(),
[s.lower() for s in v2]) for k2, v2 in v1.iteritems()))
for k1, v1 in myDict.iteritems())
``` | A recursive variant:
```
def make_lowercase(obj):
if hasattr(obj,'iteritems'):
# dictionary
ret = {}
for k,v in obj.iteritems():
ret[make_lowercase(k)] = make_lowercase(v)
return ret
elif isinstance(obj,basestring):
# string
return obj.lower()
elif hasattr(obj,'__iter__'):
# list (or the like)
ret = []
for item in obj:
ret.append(make_lowercase(item))
return ret
else:
# anything else
return obj
```
Example:
```
>>> make_lowercase({'Foo': [{1: 'Baz', 'Bar': 2}]})
{'foo': [{1: 'baz', 'bar': 2}]}
``` | Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings? | [
"",
"python",
""
] |
I'm fairly new to C#, and trying to figure out string insertions (i.e. `"some {0} string", toInsert`), and ran across a problem I wasn't expecting...
In the case where you have two constructors:
```
public MyClass(String arg1) { ... }
public MyClass(String arg1, String arg2) { ... }
```
Is it possible for me to use the first constructor with a string insertion?
```
...
toInsert = "def"
myClass = new MyClass("abc{0}ghi", toInsert)
...
```
Or will C# interpret this as the second constructor and pass a literal `"abc{0}ghi"` as the first argument? | Yes, this will be interpreted as just a second parameter.
The behavior you describe is called string formatting and everything that accepts strings in this style uses string.Format() in the background. See the documentation of that method for details.
To get the desired behavior, use this code:
```
myClass = new MyClass(string.Format("abc{0}ghi", toInsert));
``` | Just do:
```
public MyClass(string format, params object[] args)
{
this.FormattedValue = string.Format(format, args);
}
``` | C# string insertions confused with optional parameters | [
"",
"c#",
"string-formatting",
"multiple-constructors",
""
] |
Hey, I'm a fresh out of college graduate. I'm working on a project that I expect will be ultimately maintained by somebody else. I keep encountering an annoying situation on this project, and that is objects that require many private variables and as a result very long constructors.
Apart from variable naming, there isn't any coding standard enforced. I'm wondering how to deal with the likes of this. Sometimes I fear I will see some of my own code on dailywtf in the future!
I tought about trying to enclose some of these arguements in other classes, but in this situation it doesnt really make sense.
Is this a total non-issue or is it something that should and is easily correctable?
```
public function __construct($uCode = '', $uName = '', $uTime = '', $uArea = '', $uDomain = '', $uText = '', $uId = '', $uNum = '', $uVideo = 0, $uAudio = 0, $uImage = 0){
``` | Generally speaking, if you have more than about 4 arguments, you are better off using a temporary object or array instead. Often many of the parameters because optional and this can get pretty awkward and error prone pretty fast. So:
```
class MyClass {
public function __construct($options) { ... }
...
}
$o = new MyClass(array(
'uCode' => 'some value',
'uText' => 'another value',
));
```
Compare that to:
```
$o = new MyClass('some value', '', '', '', '', 'another value');
```
Notice how the array version only includes what you want to pass. | I tend to lean towards cletus's solution, but the other alternative is to use set() functions for any values that aren't absolutely necessary to have in the constructor.
e.g., if $uCode and $uName are required, but the rest are optional...
```
public function __construct($uCode = '', $uName = '') {}
public function setUTime($uTime) {}
public function setUArea($uArea) {}
...
```
It can sometimes be useful to have your setters return $this, so you can chain commands, like so:
```
$object = new MyObject($code, $name);
$object->setUTime($time)->setUArea($area)->...;
``` | Coding standards: Large amount of arguments | [
"",
"php",
"oop",
""
] |
The code:
```
function updateDashboardData() {
$.getJSON("includes/system/ajaxDataInterface.php", {recordcount:1}, function(data) {
$('.stationContainer').each(function(data) {
var bsID = $(this).attr("id");
var bsStatus = $(this).children('.stationStatus');
alert(data[bsID][0].time);
bsStatus.find('.bs_maxHandsets').text(data[bsID][0].maxHandsets);
bsStatus.find('.bs_time').text(data[bsID][0].time);
});
});
}
```
The object data:
```
{
"A5A50000": [{
"bsid": "A5A50000",
"chanCount": 17,
"time": "2009-05-27 16:36:45",
"avgInterference": 1.711765,
"maxInterference": 4.97,
"avgHandsets": 205.1176,
"maxHandsets": 315,
"avgCalls": 6.4118,
"maxCalls": 13,
"avgCBA": 3868.98059,
"maxCBA": 7463,
"sumSuccessCBA": 197318,
"sumTimeoutHandoff": 133,
"sumAttemptHandoff": 1028,
"sumDeniedHandoff": 216,
"sumConfirmHandoff": 679,
"sumHandoffNetwork": 61873,
"sumJoinNetwork": 96888,
"sumLeaveNetwork": 93754,
"sumRcvdKeepalive": 98773,
"sumTimeoutKeepalive": 19748,
"sumAttemptUplink": 93689,
"sumBlockedUplink": 62453
}]
}
```
The problem:
`alert(data.A5A50000[0].time);` properly displays "2009-05-27 16:36:45".
`alert(bsID);` properly displays "A5A50000".
`alert(data.bsID[0].time);` reports "data.bsID is undefined".
`alert(data[bsID][0].time);` reports "data[bsID] is undefined".
I'm a little unclear when a variable is/isn't evaluated. Maybe I'm overlooking something silly, but I can't figure out my problem here. | You can access object properties by dot notation or by bracket notation.
```
var x = {'test': 'hi'};
alert(x.test); // alerts hi
alert(x['test']); // alerts hi
```
When you have a dynamic value, you have to use the latter:
```
var property = 'test';
alert(x.property); // looks for x.property, undefined if it doesn't exist
alert(x[property]); // looks for x['test'], alerts hi
```
So what you actually want is:
```
alert(data[bsID][0].time);
```
**EDIT**:
Not sure what you're doing wrong, but this is working for me on Firebug's console:
```
var data = {"A5A50000":[{"bsid":"A5A50000","chanCount":17,"time":"2009-05-27 16:36:45","avgInterference":1.711765,"maxInterference":4.97,"avgHandsets":205.1176,"maxHandsets":315,"avgCalls":6.4118,"maxCalls":13,"avgCBA":3868.98059,"maxCBA":7463,"sumSuccessCBA":197318,"sumTimeoutHandoff":133,"sumAttemptHandoff":1028,"sumDeniedHandoff":216,"sumConfirmHandoff":679,"sumHandoffNetwork":61873,"sumJoinNetwork":96888,"sumLeaveNetwork":93754,"sumRcvdKeepalive":98773,"sumTimeoutKeepalive":19748,"sumAttemptUplink":93689,"sumBlockedUplink":62453}]};
var bsID = 'A5A50000';
alert(data[bsID][0].time);
``` | In Javascript, you can use either object or array-style notation to look up an attribute. The following are equivalent:
```
data.A5A50000
data['A5A50000']
```
With the second syntax, you can use a variable in place of an object string:
```
data[bsID][0]
``` | Using variable keys to access values in JavaScript objects | [
"",
"javascript",
"language-design",
""
] |
Say I want to have a method that takes any kind of number, is there a base class (or some other concept) that I can use?
As far as I know I have to make overloads for all the different numeric types (`Int32`, `Int16`, `Byte`, `UInt32`, `Double`, `Float`, `Decimal`, etc). This seems awfully tedious. Either that or use the type `object` and throw exceptions if they are not convertible or assignable to a `double` - which is pretty bad as it means no compile time checking.
**UPDATE:**
OK thanks for the comments, you are right Scarecrow and Marc, in fact declaring it as `Double` actually works for all except `Decimal`.
So the answer I was looking for is `Double` - it acts like a base class here since most numeric types are assignable to it. (I guess `Decimal` is not assignable to `Double`, as it could get too big.)
```
public void TestFormatDollars() {
int i = 5;
string str = FormatDollars(i); // this is OK
byte b = 5;
str = FormatDollars(b); // this is OK
decimal d = 5;
str = FormatDollars(d); // this does not compile - decimal is not assignable to double
}
public static string FormatDollars(double num) {
return "$" + num;
}
``` | The answer is: you don't need to provide overloads for ALL the numeric types, just for **Double** and **Decimal**. All others (except maybe some very unusually large ones) will be automatically converted to these.
Not a *base class* but in fact that was the red herring. The base class System.ValueType doesn't help much as it includes types that are not numerics. The language reference i was reading was what got me confused in the first place :)
(I was just looking for who to attribute the answer to and it was a combination of Scarecrow and Marc Gravell, but since they were comments i have put the answer here) | There isn't one (or at least, not one that *just* means "numbers"). You could use:
```
void Foo<T>(T value) where T : struct {...}
```
But that allows *any* struct - not just numbers. If you want to do arithmetic, [generic operators](https://web.archive.org/web/20090225170037/https://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html) may be of use. Other than that; overloads it the most viable option. | What is the "base class" for numeric value types? | [
"",
"c#",
".net",
"types",
""
] |
Does it make sense to create a constant for the value of a penny? For example, if I needed to decrement an amount by a penny. Do you think it is more readable if the code said:
```
amount -= Constants.StandardAmounts.Penny
```
Or should I not even bother and just use .01. | In your specific example, that particular constant does not really make sense. The two likeliest scenarios to subtract a penny are:
* Fulfill some very specific business/domain logic requirement:
If so, the constant should not be `Penny = .01`, but `StandardDeduction = .01`
* Handle more arbitrary/fluid maths:
If so, just use numbers.
In either case, "Penny" is pointless. It does not add any useful information. That's like declaring `constant HelloWorld = "HelloWorld"`. Every programmer who has even a vague idea of what your application is doing (financial calculations) understands what .01 is. Constants should be driven by purpose. | I would use the constant. Not because the value of a penny will change, but simply for clarity to future maintainers of the application.
EDIT: I guess I would also consider the number of places that this value will be used. | Constants in a C# Web Application | [
"",
"c#",
".net",
"constants",
""
] |
I have and old(ish) C# method I wrote that takes a number and converts it to any base:
```
string ConvertToBase(int number, char[] baseChars);
```
It's not all that super speedy and neat. Is there a good, known way of achieving this in .NET?
I'm looking for something that allows me to use **any** base with an arbitrary string of characters to use.
This only allows bases 16, 10, 8 and 2:
```
Convert.ToString(1, x);
```
I want to use this to achieve a massively high base taking advantage of numbers, all lower case and all upper case letters. Like in [this thread](https://stackoverflow.com/questions/656941/converting-decimals-to-sexagesimal-base-sixty-in-javascript), but for C# not JavaScript.
Does anyone know of a good and efficient way of doing this in C#? | [`Convert.ToString`](http://msdn.microsoft.com/en-us/library/14kwkz77.aspx) can be used to convert a number to its equivalent string representation in a specified base.
Example:
```
string binary = Convert.ToString(5, 2); // convert 5 to its binary representation
Console.WriteLine(binary); // prints 101
```
However, as pointed out by the comments, `Convert.ToString` only supports the following limited - but typically sufficient - set of bases: 2, 8, 10, or 16.
### Update (to meet the requirement to convert to any base):
I'm not aware of any method in the BCL which is capable to convert numbers to any base so you would have to write your own small utility function. A simple sample would look like that (note that this surely can be made faster by replacing the string concatenation):
```
class Program
{
static void Main(string[] args)
{
// convert to binary
string binary = IntToString(42, new char[] { '0', '1' });
// convert to hexadecimal
string hex = IntToString(42,
new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'});
// convert to hexavigesimal (base 26, A-Z)
string hexavigesimal = IntToString(42,
Enumerable.Range('A', 26).Select(x => (char)x).ToArray());
// convert to sexagesimal
string xx = IntToString(42,
new char[] { '0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x'});
}
public static string IntToString(int value, char[] baseChars)
{
string result = string.Empty;
int targetBase = baseChars.Length;
do
{
result = baseChars[value % targetBase] + result;
value = value / targetBase;
}
while (value > 0);
return result;
}
/// <summary>
/// An optimized method using an array as buffer instead of
/// string concatenation. This is faster for return values having
/// a length > 1.
/// </summary>
public static string IntToStringFast(int value, char[] baseChars)
{
// 32 is the worst cast buffer size for base 2 and int.MaxValue
int i = 32;
char[] buffer = new char[i];
int targetBase= baseChars.Length;
do
{
buffer[--i] = baseChars[value % targetBase];
value = value / targetBase;
}
while (value > 0);
char[] result = new char[32 - i];
Array.Copy(buffer, i, result, 0, 32 - i);
return new string(result);
}
}
```
### Update 2 (Performance Improvement)
Using an array buffer instead of string concatenation to build the result string gives a performance improvement especially on large number (see method `IntToStringFast`). In the best case (i.e. the longest possible input) this method is roughly three times faster. However, for 1-digit numbers (i.e. 1-digit in the target base), `IntToString` will be faster. | [**I recently blogged about this**](http://www.pvladov.com/2012/05/decimal-to-arbitrary-numeral-system.html). My implementation does not use any string operations during the calculations, which makes it **very fast**. Conversion to any numeral system with base from 2 to 36 is supported:
```
/// <summary>
/// Converts the given decimal number to the numeral system with the
/// specified radix (in the range [2, 36]).
/// </summary>
/// <param name="decimalNumber">The number to convert.</param>
/// <param name="radix">The radix of the destination numeral system (in the range [2, 36]).</param>
/// <returns></returns>
public static string DecimalToArbitrarySystem(long decimalNumber, int radix)
{
const int BitsInLong = 64;
const string Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (radix < 2 || radix > Digits.Length)
throw new ArgumentException("The radix must be >= 2 and <= " + Digits.Length.ToString());
if (decimalNumber == 0)
return "0";
int index = BitsInLong - 1;
long currentNumber = Math.Abs(decimalNumber);
char[] charArray = new char[BitsInLong];
while (currentNumber != 0)
{
int remainder = (int)(currentNumber % radix);
charArray[index--] = Digits[remainder];
currentNumber = currentNumber / radix;
}
string result = new String(charArray, index + 1, BitsInLong - index - 1);
if (decimalNumber < 0)
{
result = "-" + result;
}
return result;
}
```
I've also implemented a fast inverse function in case anyone needs it too:
[**Arbitrary to Decimal Numeral System**](http://www.pvladov.com/2012/07/arbitrary-to-decimal-numeral-system.html). | Quickest way to convert a base 10 number to any base in .NET? | [
"",
"c#",
".net",
"int",
"radix",
"number-systems",
""
] |
I am trying to figure out PyObjC on Mac OS X, and I have written a simple program to print out the names in my Address Book. However, I am having some trouble with the encoding of the output.
```
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
from AddressBook import *
ab = ABAddressBook.sharedAddressBook()
people = ab.people()
for person in people:
name = person.valueForProperty_("First") + ' ' + person.valueForProperty_("Last")
name
```
when I run this program, the output looks something like this:
```
...snip...
u'Jacob \xc5berg'
u'Fernando Gonzales'
...snip...
```
Could someone please explain why the strings are in unicode, but the content looks like that?
I have also noticed that when I try to print the name I get the error
```
UnicodeEncodeError: 'ascii' codec can't encode character u'\xc5' in position 6: ordinal not in range(128)
``` | If you run the code in your question in the interactive console the interpreter will print the repr of "name" because of the last statement of the loop.
If you change the last line of the loop from just "name" to "print name" the output should be fine. I've tested this with Terminal.app on a 10.5.7 system. | ```
# -*- coding: UTF-8 -*-
```
only affects the way Python decodes comments and string literals in your source, **not** the way standard output is configured, etc, etc. If you set your Mac's Terminal to UTF-8 (Terminal, Preferences, Settings, Advanced, International dropdown) and emit Unicode text to it after encoding it in UTF-8 (`print name.encode("utf-8")`), you should be fine. | Unicode problems in PyObjC | [
"",
"python",
"macos",
"unicode",
"pyobjc",
""
] |
i have several classes with members called 'Id'. Originally i wanted to store these as ints, but i would like some layer of protection, to make sure i don't accidentally assign a room id to a person etc.
one solution would be typedef (using RoomId = System.Int32;) but then i need that line of code in all files using these. i would prefer e.g. a RoomId class derived from int32, but i can't figure out how to set it up to allow explicit conversion (for initilisation)
or should i do this in some other way? | If I understand correctly, the only operation you really need is comparison for equality. You can create a RoomId class (or struct, whichever suits you)
```
class RoomId
{
private int Value {get; set;}
public RoomId(int value)
{
this.Value = value;
}
public bool Equals(RoomId other)
{
return this.Value == other.Value;
}
}
RoomId room1 = new RoomId(1);
RoomId room2 = new RoomId(2);
// To compare for equality
bool isItTheSameRoom = room1.Equals(room2);
// Or if you have overloaded the equality operator (==)
bool isItTheSameRoom = room1 == room2;
```
You can implement IEquatable, overload the equality and inequality operators if you want. If you need persistence, you could implement the ISerializable interface to make sure that the integer value only "escapes" the class if it is really needed. | You can't derive from `Int32`, but you can specify implicit conversions, which might give you the behaviour you need:
```
public struct RoomId
{
private int _Value;
public static implicit operator RoomId(int value)
{
return new RoomId { _Value = value };
}
public static implicit operator int(RoomId value)
{
return value._Value;
}
}
// ...
RoomId id = 42;
Console.WriteLine(id == 41); // False
Console.WriteLine(id == 42); // True
Console.WriteLine(id < 42); // False
Console.WriteLine(id > 41); // True
Console.WriteLine(id * 2); // 84
``` | c# deriving from int32 | [
"",
"c#",
""
] |
This came up at the office today. I have no plans of doing such a thing, but theoretically could you write a compiler in SQL? At first glance it appears to me to be turing complete, though extremely cumbersome for many classes of problems.
If it is not turing complete, what would it require to become so?
Note: I have no desire to do anything like write a compiler in SQL, I know it would be a silly thing to do, so if we can avoid that discussion I would appreciate it. | It turns out that SQL can be Turing Complete even without a true 'scripting' extension such as PL/SQL or PSM (which are designed to be true programming languages, so that's kinda cheating).
In [this set of slides](http://assets.en.oreilly.com/1/event/27/High%20Performance%20SQL%20with%20PostgreSQL%20Presentation.pdf) Andrew Gierth proves that with CTE and Windowing SQL is Turing Complete, by constructing a [cyclic tag system](http://mathworld.wolfram.com/CyclicTagSystem.html), which has been proved to be Turing Complete. The CTE feature is the important part however -- it allows you to create named sub-expressions that can refer to themselves, and thereby recursively solve problems.
The interesting thing to note is that CTE was not really added to turn SQL into a programming language -- just to turn a declarative querying language into a more powerful declarative querying language. Sort of like in C++, whose templates turned out to be Turing complete even though they weren't intended to create a meta programming language.
Oh, the [Mandelbrot set in SQL](http://wiki.postgresql.org/wiki/Mandelbrot_set) example is very impressive, as well :) | > A given programming language is said to be Turing-complete if it can be shown that it is computationally equivalent to a Turing machine.
The TSQL is Turing Complete because we can make a [BrainFuck](https://en.wikipedia.org/wiki/Brainfuck) interpreter in TSQL.
[BrainFuck interpreter in SQL - GitHub](https://github.com/PopovMP/BrainFuck-SQL)
The provided code works in-memory and doesn't modify a database.
```
-- Brain Fuck interpreter in SQL
DECLARE @Code VARCHAR(MAX) = ', [>,] < [.<]'
DECLARE @Input VARCHAR(MAX) = '!dlroW olleH';
-- Creates a "BrainFuck" DataBase.
-- CREATE DATABASE BrainFuck;
-- Creates the Source code table
DECLARE @CodeTable TABLE (
[Id] INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Command] CHAR(1) NOT NULL
);
-- Populate the source code into CodeTable
DECLARE @CodeLen INT = LEN(@Code);
DECLARE @CodePos INT = 0;
DECLARE @CodeChar CHAR(1);
WHILE @CodePos < @CodeLen
BEGIN
SET @CodePos = @CodePos + 1;
SET @CodeChar = SUBSTRING(@Code, @CodePos, 1);
IF @CodeChar IN ('+', '-', '>', '<', ',', '.', '[', ']')
INSERT INTO @CodeTable ([Command]) VALUES (@CodeChar)
END
-- Creates the Input table
DECLARE @InputTable TABLE (
[Id] INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Char] CHAR(1) NOT NULL
);
-- Populate the input text into InputTable
DECLARE @InputLen INT = LEN(@Input);
DECLARE @InputPos INT = 0;
WHILE @InputPos < @InputLen
BEGIN
SET @InputPos = @InputPos + 1;
INSERT INTO @InputTable ([Char])
VALUES (SUBSTRING(@Input, @InputPos, 1))
END
-- Creates the Output table
DECLARE @OutputTable TABLE (
[Id] INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Char] CHAR(1) NOT NULL
);
-- Creates the Buffer table
DECLARE @BufferTable TABLE (
[Id] INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Memory] INT DEFAULT 0 NOT NULL
);
INSERT INTO @BufferTable ([Memory])
VALUES (0);
-- Initialization of temporary variables
DECLARE @CodeLength INT = (SELECT COUNT(*) FROM @CodeTable);
DECLARE @CodeIndex INT = 0;
DECLARE @Pointer INT = 1;
DECLARE @InputIndex INT = 0;
DECLARE @Command CHAR(1);
DECLARE @Depth INT;
-- Main calculation cycle
WHILE @CodeIndex < @CodeLength
BEGIN
-- Read the next command.
SET @CodeIndex = @CodeIndex + 1;
SET @Command = (SELECT [Command] FROM @CodeTable WHERE [Id] = @CodeIndex);
-- Increment the pointer.
IF @Command = '>'
BEGIN
SET @Pointer = @Pointer + 1;
IF (SELECT [Id] FROM @BufferTable WHERE [Id] = @Pointer) IS NULL
INSERT INTO @BufferTable ([Memory]) VALUES (0);
END
-- Decrement the pointer.
ELSE IF @Command = '<'
SET @Pointer = @Pointer - 1;
-- Increment the byte at the pointer.
ELSE IF @Command = '+'
UPDATE @BufferTable SET [Memory] = [Memory] + 1 WHERE [Id] = @Pointer;
-- Decrement the byte at the pointer.
ELSE IF @Command = '-'
UPDATE @BufferTable SET [Memory] = [Memory] - 1 WHERE [Id] = @Pointer;
-- Output the byte at the pointer.
ELSE IF @Command = '.'
INSERT INTO @OutputTable ([Char]) (SELECT CHAR([Memory]) FROM @BufferTable WHERE [Id] = @Pointer);
-- Input a byte and store it in the byte at the pointer.
ELSE IF @Command = ','
BEGIN
SET @InputIndex = @InputIndex + 1;
UPDATE @BufferTable SET [Memory] = COALESCE((SELECT ASCII([Char]) FROM @InputTable WHERE [Id] = @InputIndex), 0) WHERE [Id] = @Pointer;
END
-- Jump forward past the matching ] if the byte at the pointer is zero.
ELSE IF @Command = '[' AND COALESCE((SELECT [Memory] FROM @BufferTable WHERE [Id] = @Pointer), 0) = 0
BEGIN
SET @Depth = 1;
WHILE @Depth > 0
BEGIN
SET @CodeIndex = @CodeIndex + 1;
SET @Command = (SELECT [Command] FROM @CodeTable WHERE [Id] = @CodeIndex);
IF @Command = '[' SET @Depth = @Depth + 1;
ELSE IF @Command = ']' SET @Depth = @Depth - 1;
END
END
-- Jump backwards to the matching [ unless the byte at the pointer is zero.
ELSE IF @Command = ']' AND COALESCE((SELECT [Memory] FROM @BufferTable WHERE [Id] = @Pointer), 0) != 0
BEGIN
SET @Depth = 1;
WHILE @Depth > 0
BEGIN
SET @CodeIndex = @CodeIndex - 1;
SET @Command = (SELECT [Command] FROM @CodeTable WHERE [Id] = @CodeIndex);
IF @Command = ']' SET @Depth = @Depth + 1;
ELSE IF @Command = '[' SET @Depth = @Depth - 1;
END
END
END;
-- Collects and prints the output
DECLARE @Output VARCHAR(MAX);
SELECT @Output = COALESCE(@Output, '') + [Char]
FROM @OutputTable;
PRINT @Output;
Go
```
[](https://i.stack.imgur.com/2AhiW.png) | Is SQL or even TSQL Turing Complete? | [
"",
"sql",
"t-sql",
"programming-languages",
"language-features",
""
] |
I'm developing a Windows application in VS2005 using C#. In my project, I generate dlls and store them in a directory. The dlls will be named as TestAssembly1, TestAssembly2, TestAssembly3 etc.
So consider if the above three dlls are in the directory. The next time the user uses my project, I need to generate dlls like TestAssembly4, TestAssembly5 etc.
So how can I store the count of the dlls in the folder and increment them when the project is used the next time?
The directory can even contain files other than dlls. So how can I do this? | You would just use Directory.GetFiles, passing in a pattern for the files you want to return:
<http://msdn.microsoft.com/en-us/library/wz42302f.aspx>
```
string[] files = Directory.GetFiles(@"C:\My Directory\", "TestAssembly*.dll");
``` | Personally I'd use a binary search to find the next assembly...
* start n=1
* does TestAssembly1.dll exist? (yes)
* does TestAssembly2.dll exist? (yes)
* does TestAssembly4.dll exist? (yes)
* does TestAssembly8.dll exist? (yes)
* does TestAssembly16.dll exist? (yes)
* does TestAssembly32.dll exist? (no)
and no use binary search between 16 and 32:
* does TestAssembly24.dll exist? (yes)
* does TestAssembly28.dll exist? (yes)
* does TestAssembly30.dll exist? (no)
* does TestAssembly29.dll exist? (yes)
so use TestAssembly30.dll
This avoids the need to keep the count separately, so it'll work even if you delete all the files - and the binary search means you don't have too bad performance.
Untested, but something like below; also note that *anything* based on file existence is immediately a race condition (although usually a very slim one):
```
static string GetNextFilename(string pattern) {
string tmp = string.Format(pattern, 1);
if (tmp == pattern) {
throw new ArgumentException(
"The pattern must include an index place-holder", "pattern");
}
if (!File.Exists(tmp)) return tmp; // short-circuit if no matches
int min = 1, max = 2; // min is inclusive, max is exclusive/untested
while (File.Exists(string.Format(pattern, max))) {
min = max;
max *= 2;
}
while (max != min + 1) {
int pivot = (max + min) / 2;
if (File.Exists(string.Format(pattern, pivot))) {
min = pivot;
}
else {
max = pivot;
}
}
return string.Format(pattern, max);
}
``` | How to store values persistenly of files in a directory? | [
"",
"c#",
""
] |
```
// a beautiful multidimensional array
public $form = array (
array(
'field' => 'email',
array(
'params' =>
array(
'rule' => 'email',
'on' => 'create',
'required' => true,
),
),
array(
'params' =>
array(
'rule' => 'email',
'on' => 'update',
'required' => false,
)
)
)
);
// beautiful foreach loops
public function validate($form) {
foreach ($form as $valueA) {
$field = $valueA['field'];
foreach ($valueA as $valueB) {
$params = $valueB['params'];
foreach ($valueB as $valueC) {
$rule = $valueC['on'];
$on = $valueC['on'];
$required = $valueC['required'];
$this->isValid($field, $rule, $on, $required);
}
}
}
}
// they do not work together!!!
``` | It looks to me like you're going to generate errors in your second loop:
```
foreach ($ValueA as $ValueB) {
```
This is going to include `field` in the loop and will encounter problems when it tries to access it as an array.
Also, I think you mean for your third loop to be:
```
foreach ($params as $ValueC) {
```
Otherwise, it runs into the same problems as the middle loop.
I think that, if you intend to keep using this as an array rather than refactor it into a class as others have suggested, you should restructure it so that the named data is all at the same level. Notice that this reduces the complexity of both the array (a little) and the loops (a lot).
```
public $form = array (
array(
'field' => 'email',
'params' => array(
array(
'rule' => 'email',
'on' => 'create',
'required' => true,
),
array(
'rule' => 'email',
'on' => 'update',
'required' => false,
)
)
)
);
public function validate($form) {
foreach ($form as $field_params) {
$field = $field_params['field'];
foreach ($field_params['params'] as $param) {
$this->isValid($field, $param['rule'], $param['on'], $param['required']);
}
}
}
``` | This page has some examples of using for loops to access elements of a multidimensional array: <http://www.webcheatsheet.com/PHP/multidimensional_arrays.php> | How can I make this multidimensional array and these foreach loops work together? | [
"",
"php",
"foreach",
"multidimensional-array",
""
] |
Ok I have done enough research on it but cant find the solution. Its from one page of a application to another page of application. Since I would be sending in username and password i cant send it as "getT" so i need to do a "post". I will be using ssl though - not sure if that helps..
so i cant use sessions as its on different apps and using those shared sessions like databsae is performance killing
Also once the user clicks the link on the source page, i need to do some post processing and then want to post to the other page so using the form and stuff wont work..
any help
fyi: What I am trying to achieve is that a person when logs in app A, they click some link, i dont some processing and want to transfer them to app B where they dont have to relogin in app B but instead automatically get logged in.. | I think you're looking for a [Single Site Login](http://aspalliance.com/1545_Understanding_Single_SignOn_in_ASPNET_20.all) solution. | We use Global.asax to do much the same thing you are describing. Assuming both web apps use the same business domain. You can use the following to set a logged in user in our business domain. You can then use the presence of that property to know not to ask for login again on your second Web App.
```
/// <summary>
/// Event fires when an HTTP request is made to the application.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
// If we don't have a logged in user.
if (<BusinessDomain>.Constants.LoggedInUserID == null)
{
// Ensure that Context.Handler for this particular HTTP request implements an interface that uses a Session State.
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
{
if (Session != null)
{
// Set the currently logged in user in our Business Domain.
if ((Guid)Session["UserID"] != Guid.Empty)
{
<BusinessDomain>.Constants.LoggedInUserID = Session["UserID"];
}
}
}
}
}
``` | Posting data from one asp.net page to another | [
"",
"c#",
"asp.net",
"forms",
"post",
""
] |
I've got some code like this:
```
letters = [('a', 'A'), ('b', 'B')]
i = 0
for (lowercase, uppercase) in letters:
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
i += 1
```
I've been told that there's an enumerate() function that can take care of the "i" variable for me:
```
for i, l in enumerate(['a', 'b', 'c']):
print "%d: %s" % (i, l)
```
However, I can't figure out how to combine the two: How do I use enumerate when the list in question is made of tuples? Do i have to do this?
```
letters = [('a', 'A'), ('b', 'B')]
for i, tuple in enumerate(letters):
(lowercase, uppercase) = tuple
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
```
Or is there a more elegant way? | This is a neat way to do it:
```
letters = [('a', 'A'), ('b', 'B')]
for i, (lowercase, uppercase) in enumerate(letters):
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
``` | This is how I'd do it:
```
import itertools
letters = [('a', 'A'), ('b', 'B')]
for i, lower, upper in zip(itertools.count(),*zip(*letters)):
print "Letter #%d is %s/%s" % (i, lower, upper)
```
EDIT: unpacking becomes redundant. This is a more compact way, which might work or not depending on your use case:
```
import itertools
letters = [('a', 'A'), ('b', 'B')]
for i in zip(itertools.count(),*zip(*letters)):
print "Letter #%d is %s/%s" % i
``` | How do I enumerate() over a list of tuples in Python? | [
"",
"python",
"list",
"enumerate",
""
] |
I'm working in J2ME, I have my gameloop doing the following:
```
public void run() {
Graphics g = this.getGraphics();
while (running) {
long diff = System.currentTimeMillis() - lastLoop;
lastLoop = System.currentTimeMillis();
input();
this.level.doLogic();
render(g, diff);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
stop(e);
}
}
}
```
So it's just a basic gameloop, the `doLogic()` function calls for all the logic functions of the characters in the scene and `render(g, diff)` calls the `animateChar` function of every character on scene, following this, the `animChar` function in the Character class sets up everything in the screen as this:
```
protected void animChar(long diff) {
this.checkGravity();
this.move((int) ((diff * this.dx) / 1000), (int) ((diff * this.dy) / 1000));
if (this.acumFrame > this.framerate) {
this.nextFrame();
this.acumFrame = 0;
} else {
this.acumFrame += diff;
}
}
```
This ensures me that everything must to move according to the time that the machine takes to go from cycle to cycle (remember it's a phone, not a gaming rig). I'm sure it's not the most efficient way to achieve this behavior so I'm totally open for criticism of my programming skills in the comments, but here my problem: When I make I character jump, what I do is that I put his *dy* to a negative value, say -200 and I set the boolean *jumping* to true, that makes the character go up, and then I have this function called `checkGravity()` that ensure that everything that goes up has to go down, `checkGravity` also checks for the character being over platforms so I will strip it down a little for the sake of your time:
```
public void checkGravity() {
if (this.jumping) {
this.jumpSpeed += 10;
if (this.jumpSpeed > 0) {
this.jumping = false;
this.falling = true;
}
this.dy = this.jumpSpeed;
}
if (this.falling) {
this.jumpSpeed += 10;
if (this.jumpSpeed > 200) this.jumpSpeed = 200;
this.dy = this.jumpSpeed;
if (this.collidesWithPlatform()) {
this.falling = false;
this.standing = true;
this.jumping = false;
this.jumpSpeed = 0;
this.dy = this.jumpSpeed;
}
}
}
```
So, the problem is, that this function updates the *dy* regardless of the *diff*, making the characters fly like Superman in slow machines, and I have no idea how to implement the *diff* factor so that when a character is jumping, his speed decrement in a proportional way to the game speed. Can anyone help me fix this issue? Or give me pointers on how to **make a 2D Jump in J2ME the right way**. | Shouldn't you be adjusting the jumpSpeed based on the elapsed time? That is, perhaps the speed changes by -75/sec, so your diff should be a weight for the amount of change applied to the jumpSpeed.
So pass in diff to checkGrav and do something like... jumpSpeed += (diff \* (rate\_per\_second)) / 1000;
(assuming diff in milliseconds)
(Ideally, this would make it just like real gravity :D) | Why not just scale all constants by diff?
By the way, I'm embarrassed to say this, but I worked on a commercial game where gravity was twice as strong on characters going down as going up. For some reason, people preferred this. | The Math of a Jump in a 2D game | [
"",
"java",
"math",
"2d",
"physics",
""
] |
I have an ownerdrawn ListView that "smears" when I scroll. It only affects the last displayed item as it moves into the visible are of the list...
It looks like:
> Blah
> Blah
> Blah
...have all been drawn on top of each other 1 pixel apart.
The code in the DrawItem event is of the form
```
Rectangle rect = new Rectangle(e.Bounds.X + mIconSize.Width,
e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
e.Graphics.DrawString(episode.ToString(), this.Font, mBlackBrush, rect);
```
I'm completely stumped.
Any ideas gratefully appreciated!
Dave | You can enable double buffering for ListView by deriving from it and setting `DoubleBuffered = true`. There's a noticeable reduction in flicker, especially in Tile view, once you turn Double Buffering on. | In detail view drawing do all of your drawing in DrawSubItem(...). The problem is drawItem is getting called for the first item and DrawSubitem is also for the same item ... with slightly different bounds. | Owner Draw ListView "smearing" when scrolling | [
"",
"c#",
"graphics",
"listview",
"ownerdrawn",
""
] |
In one o f my projects using ASP.NET + C# I want to be able to dynamically create 30 seconds clip of MP3 files and add a fade in/out.
What library would you recommend?
I saw there are a lot, including:
> <http://www.alvas.net/alvas.audio.aspx>
>
> <http://www.audiosoundeditor.com/>
>
> <http://www.mitov.com/html/audiolab.html>
Have you ever had to deal this? What library worked the best for you?
Anything will help including free/priced software that I could call from my C# application or any kind of C# compatible library. | I ended up using [ffmpeg](http://ffmpeg.org/) | You could try [NAudio](http://naudio.codeplex.com) - There would be a bit of programming required to do this but basically it would be along the lines of using NAudio to decode the MP3 first. Then passing the wave file to fade in (turn up the volume) at the time required and fade out (turn down the volume) when required. If your going to pass this to a client in a format other than wave you would then need to re-encode this file. | Audio Libraries for MP3 editing | [
"",
"c#",
"asp.net",
"audio",
"mp3",
""
] |
I have a list of e-mails from one database which I want to check against a list of unsubscribed e-mails from another database. If they exist in both lists, then I don't want them returned.
```
SELECT distinct `payer_email` as `email`
FROM `database1`.`paypal_table`
WHERE `payer_email` !=
(SELECT `email`
FROM `database2`.`Unsubscribers`
WHERE `email`
LIKE `database1`.`paypal_table`.`payer_email`)
``` | Try:
```
`payer_email` NOT IN (SELECT `email` FROM `database2`.`Unsubscribers`)
``` | I would use:
WHERE NOT EXISTS (SELECT.....)
I have come to learn that EXISTS is better performing than IN when using larger data sets. | Two tables of emails addresses, return where one is not in the other | [
"",
"sql",
"mysql",
""
] |
I was reading the [Maximum Capacity Specifications for SQL Server](http://msdn.microsoft.com/en-us/library/ms143432.aspx) and I came across the designation of a wide table. It's different from a standard table in that is can have as many as 30,000 columns as opposed to a normal (narrow) table that is limited to the more familiar 1024 columns. I googled for wide table, but nothing seem to come up relevant. Does this new table type have a more formal name???
So why do we have two different types of tables, how do you create this special table and what are the limitations of using this table that can seemingly hold more data ? anhyone know ? | A wide table is a table that uses column sets and sparse columns. It still follows the same width restrictions per row (8019 bytes) - so you'd typically only use it when your columns are mostly all nulls.
See here for more info on...
* [special table types in SQL 2008](http://msdn.microsoft.com/en-us/library/ms186986.aspx)
* [column sets](http://msdn.microsoft.com/en-us/library/cc280521.aspx)
* [sparse columns](http://msdn.microsoft.com/en-us/library/cc280604.aspx) | "To create or change a table into a wide table, you add a [column set](http://msdn.microsoft.com/en-us/library/cc280521.aspx) to the table definition."
From [here](http://msdn.microsoft.com/en-us/library/ms186986.aspx) | How do you create a wide table in SQL Server 2008? and what are its limitations on use? | [
"",
"sql",
"t-sql",
"sql-server-2008",
"ddl",
""
] |
Is it possible to capture or print what's displayed in an HTML canvas as an image or PDF?
I'd like to generate an image via canvas and be able to generate a PNG from that image. | Original answer was specific to a similar question. This has been revised:
```
const canvas = document.getElementById('mycanvas')
const img = canvas.toDataURL('image/png')
```
With the value in `img` you can write it out as a new image like so:
```
document.getElementById('existing-image-id').src = img
```
or
```
document.write('<img src="'+img+'"/>');
``` | HTML5 provides Canvas.toDataURL(mimetype) which is implemented in Opera, Firefox, and Safari 4 beta. There are a number of security restrictions, however (mostly to do with drawing content from another origin onto the canvas).
So you don't need an additional library.
e.g.
```
<canvas id=canvas width=200 height=200></canvas>
<script>
window.onload = function() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "green";
context.fillRect(50, 50, 100, 100);
// no argument defaults to image/png; image/jpeg, etc also work on some
// implementations -- image/png is the only one that must be supported per spec.
window.location = canvas.toDataURL("image/png");
}
</script>
```
Theoretically this should create and then navigate to an image with a green square in the middle of it, but I haven't tested. | Capture HTML canvas as GIF/JPG/PNG/PDF? | [
"",
"javascript",
"html",
"canvas",
"export",
"png",
""
] |
I'm capturing data from an external url using php and throwing it back to my page via ajax to load images. My problem is the external url have some images that are relative("images/example.jpg") so I have to prepend their base domain("<http://www.example.com>) so I can load it in my page. Problem is some of the images includes a base domain url yet some are in their relative form. Im guessing maybe use regex in my javascript to the determines the string if it have a base("<http://example.domain.com>") or just a relative("images/") to it. How can I achieve that through regex? | If you can parse it in PHP - I'd do what alanhaggai suggested: [`parse_url`](http://php.net/parse_url). If you need to go this in javascript: just check if there's a protocol at the start (eg: http:// https:// ftp://). Basically check for `://` in the first dozen or so characters of the url. | You won't be able to distinguish between a relative url like "images/blank.gif" and a relative url that has "www.theirdomain.com/images/blank.gif". Who is to say that "www.theirdomain.com" isn't a directory?
If the url does not start with http://, https:// or // it is relative to the url of the page where you scraped them from. | How do I determine an image url string is without a base domain through javascript? | [
"",
"javascript",
"regex",
"image",
"url",
"relative-path",
""
] |
Is there any way in Win32 to programmatically determine the bandwidth of a given network interface without actually transferring any data? I only want to distinguish between different types of interface (e.g. dialup vs DSL vs LAN), so a rough order of magnitude is fine, I don't need to actually measure the bandwidth.
Background to the problem is that my application is very bandwidth-hungry, and I want to display a warning to the user if they try and run it over a low-bandwidth interface, e.g. dialup modem or GPRS modem.
I've looked at some other [related questions](https://stackoverflow.com/questions/729146/how-to-programmatically-check-internet-bandwidth-in-vc) but if possible I'd like to avoid measuring throughput. GPRS modems in particular may have usage caps and I don't want to eat into a user's allowance - I'd rather detect the poor connection some other way and not actually send any data at all.
I'm most interested in Win32/C++ answers, but any ideas would be gratefully received. | You can use [InternetGetConnectedState](http://msdn.microsoft.com/en-us/library/aa384702(VS.85).aspx) to determine the type of connection (LAN/Modem/etc). This will tell you if they have a somewhat decent (non-modem) connection without bandwidth transfer.
Unfortunately, you can't really go much beyond that without connecting and transferring data. There is no way for the system to know the bandwidth limitations outside of it's LAN connection - ie: you could connect to your gateway on a LAN directly, and it may have a crappy connection to the outside world. As far as your computer would be concerned, though, it's on a full speed lan connection... | You could use a WMI query, there are of course Win32 functions calls as well, but this query:
```
Select * from Win32_PerfFormattedData_Tcpip_NetworkInterface
``` | Determine network interface bandwidth/type without transferring data | [
"",
"c++",
"winapi",
"networking",
"bandwidth",
""
] |
I would like to create a class whose methods can be called from multiple threads. but instead of executing the method in the thread from which it was called, it should perform them all in it's own thread. No result needs to be returned and It shouldn't block the calling thread.
A first attempt Implementation I have included below. The public methods insert a function pointer and data into a job Queue, which the worker thread then picks up. However it's not particularily nice code and adding new methods is cumbersome.
Ideally I would like to use this as a base class which I can easy add methods (with a variable number of arguments) with minimum hastle and code duplication.
What is a better way to do this? Is there any existing code available which does something similar? Thanks
```
#include <queue>
using namespace std;
class GThreadObject
{
class event
{
public:
void (GThreadObject::*funcPtr)(void *);
void * data;
};
public:
void functionOne(char * argOne, int argTwo);
private:
void workerThread();
queue<GThreadObject::event*> jobQueue;
void functionOneProxy(void * buffer);
void functionOneInternal(char * argOne, int argTwo);
};
#include <iostream>
#include "GThreadObject.h"
using namespace std;
/* On a continuous loop, reading tasks from queue
* When a new event is received it executes the attached function pointer
* It should block on a condition, but Thread code removed to decrease clutter
*/
void GThreadObject::workerThread()
{
//New Event added, process it
GThreadObject::event * receivedEvent = jobQueue.front();
//Execute the function pointer with the attached data
(*this.*receivedEvent->funcPtr)(receivedEvent->data);
}
/*
* This is the public interface, Can be called from child threads
* Instead of executing the event directly it adds it to a job queue
* Then the workerThread picks it up and executes all tasks on the same thread
*/
void GThreadObject::functionOne(char * argOne, int argTwo)
{
//Malloc an object the size of the function arguments
int argumentSize = sizeof(char*)+sizeof(int);
void * myData = malloc(argumentSize);
//Copy the data passed to this function into the buffer
memcpy(myData, &argOne, argumentSize);
//Create the event and push it on to the queue
GThreadObject::event * myEvent = new event;
myEvent->data = myData;
myEvent->funcPtr = >hreadObject::functionOneProxy;
jobQueue.push(myEvent);
//This would be send a thread condition signal, replaced with a simple call here
this->workerThread();
}
/*
* This handles the actual event
*/
void GThreadObject::functionOneInternal(char * argOne, int argTwo)
{
cout << "We've made it to functionTwo char*:" << argOne << " int:" << argTwo << endl;
//Now do the work
}
/*
* This is the function I would like to remove if possible
* Split the void * buffer into arguments for the internal Function
*/
void GThreadObject::functionOneProxy(void * buffer)
{
char * cBuff = (char*)buffer;
functionOneInternal((char*)*((unsigned int*)cBuff), (int)*(cBuff+sizeof(char*)));
};
int main()
{
GThreadObject myObj;
myObj.functionOne("My Message", 23);
return 0;
}
``` | There's [Futures](http://www.justsoftwaresolutions.co.uk/files/designing_mt_programs.pdf) library making its way into [Boost](http://www.boost.org) and the C++ standard library. There's also something of the same sort in ACE, but I would hate to recommend it to anyone (as @lothar already pointed out, it's Active Object.) | Below is an implementation which doesn't require a "functionProxy" method. Even though it is easier to add new methods, it's still messy.
Boost::Bind and "Futures" do seem like they would tidy a lot of this up. I guess I'll have a look at the boost code and see how it works. Thanks for your suggestions everyone.
GThreadObject.h
```
#include <queue>
using namespace std;
class GThreadObject
{
template <int size>
class VariableSizeContainter
{
char data[size];
};
class event
{
public:
void (GThreadObject::*funcPtr)(void *);
int dataSize;
char * data;
};
public:
void functionOne(char * argOne, int argTwo);
void functionTwo(int argTwo, int arg2);
private:
void newEvent(void (GThreadObject::*)(void*), unsigned int argStart, int argSize);
void workerThread();
queue<GThreadObject::event*> jobQueue;
void functionTwoInternal(int argTwo, int arg2);
void functionOneInternal(char * argOne, int argTwo);
};
```
GThreadObject.cpp
```
#include <iostream>
#include "GThreadObject.h"
using namespace std;
/* On a continuous loop, reading tasks from queue
* When a new event is received it executes the attached function pointer
* Thread code removed to decrease clutter
*/
void GThreadObject::workerThread()
{
//New Event added, process it
GThreadObject::event * receivedEvent = jobQueue.front();
/* Create an object the size of the stack the function is expecting, then cast the function to accept this object as an argument.
* This is the bit i would like to remove
* Only supports 8 byte argument size e.g 2 int's OR pointer + int OR myObject8bytesSize
* Subsequent data sizes would need to be added with an else if
* */
if (receivedEvent->dataSize == 8)
{
const int size = 8;
void (GThreadObject::*newFuncPtr)(VariableSizeContainter<size>);
newFuncPtr = (void (GThreadObject::*)(VariableSizeContainter<size>))receivedEvent->funcPtr;
//Execute the function
(*this.*newFuncPtr)(*((VariableSizeContainter<size>*)receivedEvent->data));
}
//Clean up
free(receivedEvent->data);
delete receivedEvent;
}
void GThreadObject::newEvent(void (GThreadObject::*funcPtr)(void*), unsigned int argStart, int argSize)
{
//Malloc an object the size of the function arguments
void * myData = malloc(argSize);
//Copy the data passed to this function into the buffer
memcpy(myData, (char*)argStart, argSize);
//Create the event and push it on to the queue
GThreadObject::event * myEvent = new event;
myEvent->data = (char*)myData;
myEvent->dataSize = argSize;
myEvent->funcPtr = funcPtr;
jobQueue.push(myEvent);
//This would be send a thread condition signal, replaced with a simple call here
this->workerThread();
}
/*
* This is the public interface, Can be called from child threads
* Instead of executing the event directly it adds it to a job queue
* Then the workerThread picks it up and executes all tasks on the same thread
*/
void GThreadObject::functionOne(char * argOne, int argTwo)
{
newEvent((void (GThreadObject::*)(void*))>hreadObject::functionOneInternal, (unsigned int)&argOne, sizeof(char*)+sizeof(int));
}
/*
* This handles the actual event
*/
void GThreadObject::functionOneInternal(char * argOne, int argTwo)
{
cout << "We've made it to functionOne Internal char*:" << argOne << " int:" << argTwo << endl;
//Now do the work
}
void GThreadObject::functionTwo(int argOne, int argTwo)
{
newEvent((void (GThreadObject::*)(void*))>hreadObject::functionTwoInternal, (unsigned int)&argOne, sizeof(int)+sizeof(int));
}
/*
* This handles the actual event
*/
void GThreadObject::functionTwoInternal(int argOne, int argTwo)
{
cout << "We've made it to functionTwo Internal arg1:" << argOne << " int:" << argTwo << endl;
}
```
main.cpp
```
#include <iostream>
#include "GThreadObject.h"
int main()
{
GThreadObject myObj;
myObj.functionOne("My Message", 23);
myObj.functionTwo(456, 23);
return 0;
}
```
Edit: Just for completeness I did an implementation with Boost::bind. Key Differences:
```
queue<boost::function<void ()> > jobQueue;
void GThreadObjectBoost::functionOne(char * argOne, int argTwo)
{
jobQueue.push(boost::bind(>hreadObjectBoost::functionOneInternal, this, argOne, argTwo));
workerThread();
}
void GThreadObjectBoost::workerThread()
{
boost::function<void ()> func = jobQueue.front();
func();
}
```
Using the boost implementation for 10,000,000 Iterations of functionOne() it took ~19sec. However the non boost implementation took only ~6.5 sec. So Approx 3x slower. I'm guessing finding a good non-locking queue will be the biggest performance bottle neck here. But it's still quite a big difference. | Event / Task Queue Multithreading C++ | [
"",
"c++",
"multithreading",
"queue",
"pthreads",
""
] |
I'm trying to get the week range using Sunday as the start date, and a reference date, say `$date`, but I just can't seem to figure it out.
For example, if I had $date as 2009-05-01, I would get 2009-04-26 and 2009-05-02. 2009-05-10 would yield 2009-05-10 and 2009-05-16. My current code looks like this (I can't remember where I lifted it from, as I forgot to put down the url in my comments):
```
function x_week_range(&$start_date, &$end_date, $date)
{
$start_date = '';
$end_date = '';
$week = date('W', strtotime($date));
$week = $week;
$start_date = $date;
$i = 0;
while(date('W', strtotime("-$i day")) >= $week) {
$start_date = date('Y-m-d', strtotime("-$i day"));
$i++;
}
list($yr, $mo, $da) = explode('-', $start_date);
$end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $da + 6, $yr));
}
```
I realized all it did was add 7 days to the current date. How would you do this? | I would take advantange of PHP's [strtotime](http://www.php.net/strtotime) awesomeness:
```
function x_week_range(&$start_date, &$end_date, $date) {
$ts = strtotime($date);
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
$start_date = date('Y-m-d', $start);
$end_date = date('Y-m-d', strtotime('next saturday', $start));
}
```
Tested on the data you provided and it works. I don't particularly like the whole reference thing you have going on, though. If this was my function, I'd have it be like this:
```
function x_week_range($date) {
$ts = strtotime($date);
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
return array(date('Y-m-d', $start),
date('Y-m-d', strtotime('next saturday', $start)));
}
```
And call it like this:
```
list($start_date, $end_date) = x_week_range('2009-05-10');
```
I'm not a big fan of doing math for things like this. Dates are tricky and I prefer to have PHP figure it out. | To everyone still using mktime(), strtotime() and other PHP functions... give the PHP5 [DateTime](http://php.net/manual/en/class.datetime.php) Class a try. I was hesitant at first, but it's really easy to use. Don't forget about using clone() to copy your objects.
Edit: This code was recently edited to handle the case where the current day is Sunday. In that case, we have to get the past Saturday and then add one day to get Sunday.
```
$dt_min = new DateTime("last saturday"); // Edit
$dt_min->modify('+1 day'); // Edit
$dt_max = clone($dt_min);
$dt_max->modify('+6 days');
```
Then format as you need it.
```
echo 'This Week ('.$dt_min->format('m/d/Y').'-'.$dt_max->format('m/d/Y').')';
```
Make sure to set your timezone early in your code.
```
date_default_timezone_set('America/New_York');
``` | Get Start and End Days for a Given Week in PHP | [
"",
"php",
"datetime",
""
] |
I am trying to install cvs2svn on a Solaris 10 machine. It has Python 2.4.4 on it. I don't have root access. When I downloaded cvs2svn and tried to run it, it said
> ERROR: cvs2svn uses the anydbm package, which depends on lower level dbm libraries. Your system has dbm, with which cvs2svn is known to have problems. To use cvs2svn, you must install a Python dbm library other than dumbdbm or dbm. See <http://python.org/doc/current/lib/module-anydbm.html> for more information.
I downloaded gdbm, compiled, and installed it in my home directory. How do I get a Python gdbm module installed that works with anydbm? Google isn't helping... | I downloaded Python 2.5.1 and compiled it from the source. I made sure my gdbm libraries were in the appropriate paths and used the altinstall into my home directory. I can now run cvs2svn with my private copy of python. | Set the `$PYTHONPATH` environment variable to point to the location where you installed `gdbm`. Then when you run `cvs2svn`, the anybdm module should find `gdbm` successfully. | Installing/configuring gdbm Python module for cvs2svn? | [
"",
"python",
"solaris",
"cvs2svn",
"gdbm",
""
] |
I have developed a Jersey Resource class.
Can someone please tell me how can I deploy it on a Web App server. Preferably Tomcat or JBoss.
Or a better question still, can Jersey applications with only a resource class be deployed on a Web App server? If yes, How? | by using web.xml:
```
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.foo.resources;org.bar.resources</param-value>
</init-param>
</servlet>
```
or in Java (without a servlet container):
```
public class MyConfig extends PackagesResourceConfig {
public MyApplication() {
super("com.foo.resources;org.bar.resources");
}
}
```
or subclassing Application:
```
public class MyApplicaton extends Application {
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(com.foo.resources.MyResource.class);
return s;
}
}
``` | Deploying in a servlet container will certainly work if you need the servlet container. Simpler and recommended by Jersey is with Grizzly - <http://jersey.java.net/nonav/documentation/latest/user-guide.html#d4e60> | jersey deployment | [
"",
"java",
"deployment",
"jersey",
""
] |
In Java, the attribute field of a HttpServletRequest object can be retrieved using the getAttribute method:
```
String myAttribute = request.getAttribute("[parameter name]");
```
Where the HttpServletRequest attribute data is stored in a raw HTTP request? Is it in the body of the request?
For example, I'm trying to create a raw GET HTTP request that will be sent to my servlet using some client program. My servlet.doGet() method would be something like this:
```
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
String myAttribute = request.getAttribute("my.username");
...
}
```
Where should I put the 'my.username' data in the raw HTTP request so that the 'myAttribute' String receives the value "John Doe" after the attribution? | To add to @gid's answer, attributes are not present in any way in the HTTP request as it travels over the wire. They are created (by your code) when processing the request. A very common use is to have a server set (aka create) some attributes and then forward to a JSP that will make use of those attributes. That is, an HTTP request arrives and is sent to a Servlet. The Servlet attaches some attributes. Additional server-side processing is done, eventually sending the page to a JSP, where the attributes are used. The response is generated in the JSP. The HTTP request and the HTTP response do not contain any attributes. Attributes are 100% purely server-side information.
When a single given HTTP request has completed, the attributes become available for garbage collection (unless they are persisted in some other location, such as a session). Attributes are only associated with a single request object. | Just to be clear as I think @Jon's answer doesn't make it perfectly clear. The values for getAttribute and setAttribute on HttpServletRequest are not present on what is actually sent over the wire, they are server side only.
```
// only visible in this request and on the server
request.getAttribute("myAttribute");
// value of the User-Agent header sent by the client
request.getHeader("User-Agent");
// value of param1 either from the query string or form post body
request.getParameter("param1");
``` | How the attribute field of a HttpServletRequest maps to a raw HTTP request? | [
"",
"java",
"http",
"servlets",
""
] |
I understand that only one instance of any object according to .equals() is allowed in a Set and that you shouldn't "need to" get an object from the Set if you already have an equivalent object, but I would still like to have a .get() method that returns the actual instance of the object in the Set (or null) given an equivalent object as a parameter.
Any ideas/theories as to why it was designed like this?
I usually have to hack around this by using a Map and making the key and the value same, or something like that.
EDIT: I don't think people understand my question so far. I want the exact object instance that is already in the set, not a possibly different object instance where .equals() returns true.
As to why I would want this behavior, typically .equals() does not take into account all the properties of the object. I want to provide some dummy lookup object and get back the actual object instance in the Set. | While the purity argument does make the method `get(Object)` suspect, the underlying intent is not moot.
There are various class and interface families that slightly redefine `equals(Object)`. One need look no further than the collections interfaces. For example, an ArrayList and a LinkedList can be equal; their respective contents merely need to be the same and in the same order.
Consequently, there are very good reasons for finding the *matching* element in a set. Perhaps a clearer way of indicating intent is to have a method like
```
public interface Collection<E> extends ... {
...
public E findMatch(Object o) throws UnsupportedOperationException;
...
}
```
Note that this API has value broader that within Set.
As to the question itself, I don't have any theory as to why such an operation was omitted. I will say that the *minimal spanning set argument* does not hold, because many operations defined in the collections APIs are motivated by convenience and efficiency. | The problem is: Set is not for "getting" objects, is for adding and test for presence.
I understand what are you looking for, I had a similar situation and ended using a map of the same object in key and value.
EDIT: Just to clarify: <http://en.wikipedia.org/wiki/Set_(abstract_data_type)> | Why does the java.util.Set<V> interface not provide a get(Object o) method? | [
"",
"java",
"generics",
"collections",
""
] |
I know it's possible to create a friend function in C++:
```
class box
{
friend void add(int num);
private:
int contents;
};
void add(int num)
{
box::contents = num;
return;
}
```
But is there a way to create friend classes?
NB: I know there are probably a lot of errors in this code, I don't use friend functions and am still pretty new to the language; if there are any, please tell me. | Yup - inside the declaration of `class Box`, do
```
friend class SomeOtherClass;
```
All member functions of `SomeOtherClass` will be able to access the `contents` member (and any other private members) of any `Box`. | By the way, a design guideline is that, if a class is close enough to be declared a friend, then it's close enough to be declared as a nested class in the same header file, for example:
```
class Box
{
class SomeOtherClass
{
//some implementation that might want to access private members of box
};
friend class SomeOtherClass;
private:
int contents;
};
```
If you don't want to declare the other class as a nested class in the same header file, then perhaps you shouldn't (although you are able to) declare it a friend. | Is it possible to create a "friend class" in C++? | [
"",
"c++",
"class",
""
] |
I've recently needed to write a script that performs an **os.fork()** to split into two processes. The child process becomes a server process and passes data back to the parent process using a pipe created with **os.pipe()**. The child closes the `'r'` end of the pipe and the parent closes the `'w'` end of the pipe, as usual. I convert the returns from pipe() into file objects with **os.fdopen**.
The problem I'm having is this: The process successfully forks, and the child becomes a server. Everything works great and the child dutifully writes data to the open `'w'` end of the pipe. Unfortunately the parent end of the pipe does two strange things:
A) It blocks on the `read()` operation on the `'r'` end of the pipe.
Secondly, it fails to read any data that was put on the pipe unless the `'w'` end is entirely closed.
I immediately thought that buffering was the problem and added **pipe.flush()** calls, but these didn't help.
Can anyone shed some light on why the data doesn't appear until the writing end is fully closed? And is there a strategy to make the `read()` call non blocking?
This is my first Python program that forked or used pipes, so forgive me if I've made a simple mistake. | Are you using read() without specifying a size, or treating the pipe as an iterator (`for line in f`)? If so, that's probably the source of your problem - read() is defined to read until the end of the file before returning, rather than just read what is available for reading. That will mean it will block until the child calls close().
In the example code linked to, this is OK - the parent is acting in a blocking manner, and just using the child for isolation purposes. If you want to continue, then either use non-blocking IO as in the code you posted (but be prepared to deal with half-complete data), or read in chunks (eg r.read(size) or r.readline()) which will block only until a specific size / line has been read. (you'll still need to call flush on the child)
It looks like treating the pipe as an iterator is using some further buffer as well, for "`for line in r:`" may not give you what you want if you need each line to be immediately consumed. It may be possible to disable this, but just specifying 0 for the buffer size in fdopen doesn't seem sufficient.
Heres some sample code that should work:
```
import os, sys, time
r,w=os.pipe()
r,w=os.fdopen(r,'r',0), os.fdopen(w,'w',0)
pid = os.fork()
if pid: # Parent
w.close()
while 1:
data=r.readline()
if not data: break
print "parent read: " + data.strip()
else: # Child
r.close()
for i in range(10):
print >>w, "line %s" % i
w.flush()
time.sleep(1)
``` | Using
`fcntl.fcntl(readPipe, fcntl.F_SETFL, os.O_NONBLOCK)`
Before invoking the read() solved both problems. The read() call is no longer blocking and the data is appearing after just a flush() on the writing end. | Python program using os.pipe and os.fork() issue | [
"",
"python",
"pipe",
"fork",
""
] |
I have a Visual Studio 2005/[C#](http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29) ClickOnce application that gets all its data from a [Web service](https://en.wikipedia.org/wiki/Web_service). I've gotten the application tuned where it feels pretty snappy to the users, even though it has to go and fetch data from the Web service for almost everything.
However, the startup is still pretty sluggish. It seems like it takes a while to generate the first web service call. After that, it's fine.
What can I do to speed up the startup of this type of an application? Do I need to generate a serialization assembly? | Spend some time analyzing the assemblies loaded by your application. That's going to have the greatest effect on the load time of your application. If you have types that are only used on occasion, move them to another assembly. ClickOnce can optimize the download of assemblies on demand so reducing the required number of assemblies at load time will make it load faster.
You can also have a sort of "stub" launcher with bare minimum assembly dependencies that loads the other assemblies dynamically (Assembly.Load) and invokes the real processing after they are loaded. | You can use ClickOnce file groups to split your application into manageable pieces and then use the ClickOnce API to download groups when needed. The article *[ClickOnce File Groups](http://www.thejoyofcode.com/ClickOnce_File_Groups.aspx)* explains how to do this. | Ways to speed up the startup of a ClickOnce application | [
"",
"c#",
"clickonce",
""
] |
Does anyone know of a syntax highlight for Mako templates for Eclipse or for TextMate?
I know that there is a `.mako` syntax highlighter for the default text editor in Ubuntu. | I just did some [googlin'](https://www.google.com/search?q=mako+bundle+textmate). There is a Mako bundle (among other syntax highlighters [listed here](https://github.com/sqlalchemy/mako/wiki#mako-syntax-highlighters)).
I installed it under `~/Library/Application Support/TextMate/Bundles/` like so:
```
cd ~/Library/Application\ Support/TextMate/Bundles/
svn co http://svn.makotemplates.org/contrib/textmate/Mako.tmbundle
```
In TextMate, I did `Bundles | Bundle Editor | Reload Bundles`, and `Mako` showed up in the menu.
It adds new HTML language variant: `HTML (Mako)`, snippets and stuff like that.
Hope this helps. | Claudio,
I don't use mako templates, but a quick google search turned up [this article](http://groups.google.com/group/mako-discuss/browse_thread/thread/796926337af30cf0) from the mako-discuss google group, which refers to a Colorer library syntax highlighter. This sounds like it might be a decent lead for you.
-matt | Syntax Highlight for Mako in Eclipse or TextMate? | [
"",
"python",
"templates",
"mako",
""
] |
How is it possible to parse command-line arguments that are to be interpreted as paths? args[] contains strings that are automatically joined if they are quoted, e.g.:
example.exe one two "three four"
```
args[0] = one
args[1] = two
args[2] = three four
```
However, args[] will not property parse "C:\Example\" as an argument. Rather, it will supply the argument as "C:\Example"" (with the extra quote included.) This is due to the backslash in the path being treated as an escape character and thus the end quotation that the user supplied on the command-line becomes part of the argument.
.e.g:
example.exe one "C:\InputFolder" "C:\OutuptFolder\"
```
args[0] = one
args[1] = C:\InputFolder"
args[2] = C:\OutputFolder"
```
An easy kludge might be:
```
_path = args[i].Replace("\"", @"\");
```
However, I'm sure there is a best-practice for this. How might one correctly parse a command line that inlcudes paths, preventing the args[] array from improperly being populated with stings that have been parsed for escape characters?
NOTE: I would not like to include an entire command-line parsing library in my project! I need only to handle quoted paths and wish to do so in a "manual" fashion. Please do not reccomend NConsoler, Mono, or any other large "kitchen sink" command-line parsing library.
ALSO NOTE: As far as I can tell, this is not a duplicate question. While other questions focus on generic command-line parsing, this question is specific to the problem that paths introduce when parts of them are interpreted as escape sequences. | Not an answer, but here's some [background and explanation](http://www.eggheadcafe.com/conversation.aspx?messageid=31268633&threadid=31268617) from Jeffrey Tan, Microsoft Online Community Support (12/7/2006):
> Note: this is not not a code defeat
> but by design, since backslashe are
> normally used to escape certain
> special character. Also, this
> algorithm is the same as Win32 command
> line arguments parsing function
> CommandLineToArgvW. See the Remarks
> section below:
> <http://msdn2.microsoft.com/en-us/library/bb776391.aspx>
Also makes reference to the FX method [Environment.GetCommandLineArgs](http://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs.aspx) for further explanation of the slash handling behavior.
Personally I think this is a drag, and I'm surprised I haven't been bit by it before. Or maybe I have and don't know it? Blind replacement of quotes with slashes doesn't strike me as a solution, though. I'm voting the question up, because it was an eye opener. | I like your idea:
```
_path = args[i].Replace("\"", @"\");
```
It is clean, and will have no effect unless the problem exists. | C# Command-Line Parsing of Quoted Paths and Avoiding Escape Characters | [
"",
"c#",
"command-line",
"escaping",
""
] |
I've tried to make a regex expression to match a piece of code, but no success.
The expression doesn't work in vs2008.
I've created this one:
```
/\*<parameters>\*/(?<value>[\r\n]*.*)/\*</parameters>\*/
```
the source to match is:
```
/*<parameters>*/
@parameter blue
,@parameter2 red
,@parameter3 green
,@parameter4 yellow /*</parameters>*/
```
Or better:
```
/*<parameters>*/ \r\n @parameter blue \r\n ,@parameter2 red \r\n ,@parameter3 green \r\n ,@parameter4 yellow /*</parameters>*/
```
Can anybody help me?
thanks,
Rodrigo Lobo | Try this Regex out: `/\*<parameters>\*/(?<value>[^/]*)/\*</parameters>\*/`
A good tool for fooling around with real c# Regex patterns is regex-freetool on code.google.com | `RegexOptions.Multiline` only changes the semantics of `^` and `$` -- you need `RegexOptions.Singleline` to let `.` match line-ends as well (a confusion I've been caught in myself;-). | How can i match this text with a regex? | [
"",
"c#",
"regex",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.