Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Actually, it's gotten so messy that I'm not even sure curl is the culprit. So, here's the php:
```
$creds = array(
'pw' => "xxxx",
'login' => "user"
);
$login_url = "https://www.example.net/login-form"; //action value in real form.
$loginpage = curl_init();
curl_setopt($loginpage, CURLOPT_HEADER, 1);
curl_setopt($loginpage, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($loginpage, CURLOPT_URL, $login_url);
curl_setopt($loginpage, CURLOPT_POST, 1);
curl_setopt($loginpage, CURLOPT_POSTFIELDS, $creds);
$response = curl_exec($loginpage);
echo $response;
```
I get the headers (which match the headers of a normal, successful request), followed by the login page (I'm guessing curl captured this due to a redirect) which has an error to the effect of "Bad contact type".
I thought the problem was that the request had the host set to the requesting server, not the remote server, but then I noticed (in Firebug), that the request is sent as GET, not POST.
If I copy the login site's form, strip it down to just the form elements with values, and put the full URL for the action, it works just great. So I would think this isn't a security issue where the login request has to originate on the same server, etc. (I even get rid of the empty hidden values and all of the JS which set some of the other cookies).
Then again, I get confused pretty quickly.
Any ideas why it's showing up as GET, or why it's not working, for that matter? | When troubleshooting the entire class of PHP-cURL-related problems, you simply have to turn on CURLOPT\_VERBOSE and give CURLOPT\_STDERR a file handle.
`tail -f` your file, compare the headers and response to the ones you see in Firebug, and the problem should become clear. | The shown code does a multipart formpost (since you pass a hash array to the POSTFIELDS option), which probably is not what the target server expects. | curl sending GET instead of POST | [
"",
"php",
"forms",
"curl",
"server-side",
"http-post",
""
] |
I have to mock quite complicated java web service and I'm searching for the right solution. One way to do it would be to use Soap UI, but I need something that would be able to modify server state ie. one request would affect future requests.
In this particular case it could be done quickly by saving serialized objects to disk and sometimes spawning asynchronous responses to the originating client webservice.
Those two requirements are preventing me from using SoapUI - the groovy logic would become quite complicated and probably hard to mantain.
My questions:
1) Are there any other SoapUI advantages in this context (eg. easy migration to new version of wsdl) over custom java mock implementation?
2) What would be most appropriate way to generate the webservice from wsdl and still be able too hook up with some custom functionality, ie. by attaching some hooks that would be editable in seperate files (to facilitate further ws code regeneration from updated wsdl)? | For simple mocks I use soapUI, while for more complicated when state must change between request I use simple web service emulator written in Python. Such emulator use reply templates created from real web service or responses I created in soapUI. This way I can control all logic.
Emulator for my last project has 300+ lines of Python code, but for previous, much simplier, it was ~150 lines of Python code. | You should look at [EasyMock](http://easymock.org/ "EasyMock"), which allows to build mocks programatically. It is possible to specify very complex behaviors for your mocks. | Best way to mock java web service | [
"",
"java",
"web-services",
"mocking",
""
] |
i am using a stored procedure to run some queries in my database. The value is taken from a query string then passed to the stored procedure. the thing is, the user may select more than 1 option that generates 3 or more query string.
e.g. <http://localhost.com/test.aspx?param=76¶m2=79>
i know how to take the values from the query but i do i make the stored procedure accepts either 1 or 2 or 3 values kinda like overloading
e.g.
```
setValue (int val)
{
this.value = val;
}
setValue (double val)
{
this.value = (int) val
}
setValue (string val)
{
try
{
this.value = Integer.parseInt(val)
}
catch (Exception e)
{
System.out.println(e.getMessage());
return 0;
}
}
```
this is a copy of the stored procedure..
```
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[getSealRecordID] (@TRANSFER_ID int)
AS
-- Declare variables
SELECT DISTINCT "FGFSTRANSFERS"."CONSIDERATION", "FGFSTRANSFERS"."AMOUNT_TRANSFER", "FGFSTRANSFERS"."DATE",
"FGFSTRANSFERS"."TRANSFER_ID",
CURR = CASE "FGFSTransferDetails"."CURR"
WHEN 'USD' THEN 'United States Dollars'
WHEN 'JMD' THEN 'Jamaican Dollars'
WHEN 'CAD' THEN 'Canadian Dollars'
WHEN 'GBP' THEN 'POUNDS'
WHEN 'EUR' THEN 'EUROS'
END
,"FGFSCUSTOMERS"."CMF_NAME_1", "FGFSCUSTOMERS"."CMF_NAME_2" , "FGFSTransferDetails"."AMOUNT",
Cons_Curr = CASE "FGFSTransferDetails"."CURR" -- As Cons_Curr,
WHEN 'USD' THEN 'United States Dollars'
WHEN 'JMD' THEN 'Jamaican Dollars'
WHEN 'CAD' THEN 'Canadian Dollars'
WHEN 'GBP' THEN 'POUNDS'
WHEN 'EUR' THEN 'EUROS'
END
,"FGFSTransferDetails"."DESCRIPTION", "FGFSTransferDetails"."IMID"
FROM ("FGFSInvestment"."dbo"."FGFSTransferDetails" "FGFSTransferDetails" INNER JOIN "FGFSInvestment"."dbo"."FGFSTRANSFERS" "FGFSTRANSFERS" ON "FGFSTransferDetails"."TRANSFER_ID"="FGFSTRANSFERS"."TRANSFER_ID") INNER JOIN "FGFSInvestment"."dbo"."FGFSCUSTOMERS" "FGFSCUSTOMERS" ON "FGFSTRANSFERS"."CUSTODIAN"="FGFSCUSTOMERS"."CMF_ACCOUNT"
WHERE "FGFSTRANSFERS"."TRANSFER_ID"= @TRANSFER_ID AND "FGFSTransferDetails"."TRANSFER_ID"=@TRANSFER_ID
``` | You can use default parameters in your stored procedure:
```
CREATE PROCEDURE [dbo].[getSealRecordID]
( @PARAM int = -1,
@PARAM2 int = -1,
@PARAM3 int = -1
)
AS
...
```
of course you'll have to handle those values in your where clause:
```
...
WHERE (@PARAM = -1 OR (condition with @PARAM))
AND (@PARAM1 = -1 OR (condition with @PARAM1))
AND (@PARAM2 = -1 OR (condition with @PARAM2))
``` | you can put defaults on the parameters for your stored proc, then you can call it with 1, 2, or 3 values.
```
CREATE PROC MyProc
(@Param1 int,
@Param2 int = null,
@Param3 int = null)
AS
-- body of proc here
``` | Stored Procedure that handles 1 or 2 or 3 value | [
"",
"c#",
"stored-procedures",
"parameters",
"query-string",
"overloading",
""
] |
See subject. What were they thinking?
UPDATE: Changed from "static" to "internal linkage" to save confusion.
To give an example... Putting the following in a file:
```
const int var_a = 1;
int var_b = 1;
```
...and compiling with `g++ -c test.cpp` only exports `var_b`. | I believe you mean
> Why does const imply internal linkage in C++
It's true that if you declare a const object at namespace scope, then it has internal linkage.
Appendix C (**C++11, C.1.2**) gives the rationale
> **Change:** A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage
>
> **Rationale:** Because const objects can be used as compile-time values in C++, this feature urges programmers to provide explicit initializer values for each const. This feature allows the user to put const objects in header files that are included in many compilation units. | As litb said, `const` objects have internal linkage in C++. This is because they are intended to be used like this:
```
// a.cpp
const int BUFSIZE = 100;
char abuf[BUFSIZE];
// b.cpp
const int BUFSIZE = 256
int bbuf[BUFSIZE];
``` | Why does const imply internal linkage in C++, when it doesn't in C? | [
"",
"c++",
""
] |
There's a question about [converting from a SID to an account name](https://stackoverflow.com/questions/499053/how-can-i-convert-from-a-sid-to-an-account-name-in-c); there isn't one for the other way around.
How do you convert a username to a SID string, for example, to find out which HKEY\_USERS subkey relates to a user of a given name? | The podcast tells me I should ask, and answer, questions when they're not answered on SO already. Here goes.
The easy way, with .NET 2.0 and up, is this:
```
NTAccount f = new NTAccount("username");
SecurityIdentifier s = (SecurityIdentifier) f.Translate(typeof(SecurityIdentifier));
String sidString = s.ToString();
```
The hard way, which works when that won't, and works on .NET 1.1 also:
```
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool LookupAccountName([In,MarshalAs(UnmanagedType.LPTStr)] string systemName, [In,MarshalAs(UnmanagedType.LPTStr)] string accountName, IntPtr sid, ref int cbSid, StringBuilder referencedDomainName, ref int cbReferencedDomainName, out int use);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
internal static extern bool ConvertSidToStringSid(IntPtr sid, [In,Out,MarshalAs(UnmanagedType.LPTStr)] ref string pStringSid);
/// <summary>The method converts object name (user, group) into SID string.</summary>
/// <param name="name">Object name in form domain\object_name.</param>
/// <returns>SID string.</returns>
public static string GetSid(string name) {
IntPtr _sid = IntPtr.Zero; //pointer to binary form of SID string.
int _sidLength = 0; //size of SID buffer.
int _domainLength = 0; //size of domain name buffer.
int _use; //type of object.
StringBuilder _domain = new StringBuilder(); //stringBuilder for domain name.
int _error = 0;
string _sidString = "";
//first call of the function only returns the sizes of buffers (SDI, domain name)
LookupAccountName(null, name, _sid, ref _sidLength, _domain, ref _domainLength, out _use);
_error = Marshal.GetLastWin32Error();
if (_error != 122) //error 122 (The data area passed to a system call is too small) - normal behaviour.
{
throw (new Exception(new Win32Exception(_error).Message));
} else {
_domain = new StringBuilder(_domainLength); //allocates memory for domain name
_sid = Marshal.AllocHGlobal(_sidLength); //allocates memory for SID
bool _rc = LookupAccountName(null, name, _sid, ref _sidLength, _domain, ref _domainLength, out _use);
if (_rc == false) {
_error = Marshal.GetLastWin32Error();
Marshal.FreeHGlobal(_sid);
throw (new Exception(new Win32Exception(_error).Message));
} else {
// converts binary SID into string
_rc = ConvertSidToStringSid(_sid, ref _sidString);
if (_rc == false) {
_error = Marshal.GetLastWin32Error();
Marshal.FreeHGlobal(_sid);
throw (new Exception(new Win32Exception(_error).Message));
} else {
Marshal.FreeHGlobal(_sid);
return _sidString;
}
}
}
}
``` | The `LookupAccountName()` native method has the advantage of being able to be executed on a remote machine whereas the .NET methods can't be executed remotely.
Though the example doesn't show it `LookupAccountName(null)` <- this is the remote system to execute on. | Convert a username to a SID string in C#/.NET | [
"",
"c#",
"windows",
"identity",
"sid",
""
] |
I have to parse a bunch of stats from text, and they all are formatted as numbers.
For example, this paragraph:
> A total of 81.8 percent of New York
> City students in grades 3 to 8 are
> meeting or exceeding grade-level math
> standards, compared to 88.9 percent of
> students in the rest of the State.
I want to match just the 81 and 88 numbers, not the ".8" and ".9" that follow.
How can I do this? I've heard the term back-reference or look-aheads or something. Will any of that help?
I am using C#.
Edit:
It's required that I get the "3" and the "8" in the above example. It's just a simple example, but I need pretty much all numbers. | If you don't want to deal with groups, you can use a lookahead like you say; this pattern finds the integer part of all decimal numbers in the string:
```
Regex integers = new Regex(@"\d+(?=\.\d)");
MatchCollection matches = integers.Matches(str);
```
`matches` will contain `81` and `88`. If you'd like to match the integer part of ANY numbers (decimal or not), you can instead search for integers that don't start with a `.`:
```
Regex integers = new Regex(@"(?<!\.)\d+");
```
This time, matches would contain `81`, `3`, `8` and `88`. | ```
/[^.](\d+)[^.]/
```
As stated below just use MatchObj.Groups(1) to get the digit. | Regex that matches anything before a certain character? | [
"",
"c#",
"regex",
"parsing",
"regex-lookarounds",
""
] |
Can I declare parameterized constructor inside servlet which is only constructor ?
If no then why ? | No.
Servlet instances are created by the container via reflection, and they expect to find a public, no-arg constructor (the default constructor).
To configure your servlet, use servlet parameters specified in the web.xml file. These are passed to your servlet's [`init()`](http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/Servlet.html#init(javax.servlet.ServletConfig)) method.
---
While it would be *possible* for a servlet container to choose a non-default constructor and coerce character strings to simple types and invoke the constructor reflectively, this isn't what the Servlet specification requires.
Part of the reason may be historical; servlets were first specified long before dependency injection systems made this alternative widely practiced. However, such constructors would be fairly limited; it would be practical to pass arguments that can be created from a simple character string specified in the web.xml, but more useful objects—a `DataSource`, for example—would be awkward.
It would be nice to have final member variables in a servlet though.
The JSR formerly known as "WebBeans" (JSR 299, I think), will provide some standards for dependency injection support in Servlets. This might address some of the drawbacks in the current approach. | Since servlets are instantiated by the container they need a no-argument constructor.
Additionally the container may reuse servlets and will not call the constructor on reuse. | Parameterized constructor in servlet | [
"",
"java",
"servlets",
"jakarta-ee",
""
] |
Having a few problems trying to parse a CSV in the following format using the FileHelpers library. It's confusing me slightly because the field delimiter appears to be a space, but the fields themselves are sometimes quoted with quotation marks, and other times by square brackets. I'm trying to produce a RecordClass capable of parsing this.
Here's a sample from the CSV:
```
xxx.xxx.xxx.xxx - - [14/Jun/2008:18:04:17 +0000] "GET http://www.some_url.com HTTP/1.1" 200 73662339 "-" "iTunes/7.6.2 (Macintosh; N; Intel)"
```
It's an extract from an HTTP log we receive from one of our bandwidth providers. | While I thank Marc Gravell and Jon Skeet for their input, my question was how to go about parsing a file containing lines in the format described using the FileHelpers library (albeit, I worded it badly to begin with, describing 'CSV' when in fact, it isn't).
I have now found a way to do just this. It's not particularly the most elegant method, however, it gets the job done. In an ideal world, I wouldn't be using FileHelpers in this particular implementation ;)
For those who are interested, the solution is to create a FileRecord class as follows:
```
[DelimitedRecord(" ")]
public sealed class HTTPRecord
{
public String IP;
// Fields with prefix 'x' are useless to me... we omit those in processing later
public String x1;
[FieldDelimiter("[")]
public String x2;
[FieldDelimiter("]")]
public String Timestamp;
[FieldDelimiter("\"")]
public String x3;
public String Method;
public String URL;
[FieldDelimiter("\"")]
public String Type;
[FieldIgnored()]
public String x4;
[FieldDelimiter(" ")]
public String x5;
public int HTTPStatusCode;
public long Bytes;
[FieldQuoted()]
public String Referer;
[FieldQuoted()]
public String UserAgent;
}
``` | The obvious statement is "then it isn't CSV"...
I'd be tempted to use a quick regex to munge the date into the same escaping as everything else... on a line-by-line basis, something like:
```
string t = Regex.Replace(s, @"\[([^\]]*)\]", @"""$1""")
```
Then you should be able to use a standard parser using space as a delimiter (respecting quotes). | Using FileHelpers; how to parse this CSV type | [
"",
"c#",
"asp.net",
"vb.net",
"filehelpers",
""
] |
Using jQuery 1.2.x and jQuery UI 1.5.x, one was able to trigger dragging manually like so:
```
jQuery("#myDiv").mousedown(function(ev) {
target = jQuery(ev.target);
if (target.hasClass("drag-me")) {
target.draggable({
helper: "clone",
start: function()
{
console.log("drag start");
},
stop: function()
{
jQuery(this).draggable("destroy");
}
}).trigger("mousedown.draggable", [ev]);
} });
```
It is applied to the following HTML:
```
<div id="myDiv">
<div class="drag-me"></div>
<div class="drag-me"></div>
<div class="drag-me"></div>
<div class="drag-me"></div>
<div class="drag-me"></div>
<div class="drag-me"></div>
<div class="drag-me"></div>
</div>
```
It was a handy way to apply dragging to elements inside a container that has its children changed dynamically. I like to call it "drag delegation".
However with the release of jQuery 1.3.x & jQuery 1.6+, the script above stopped working. Using jQuery 1.3.2 & jQuery UI 1.7.1 returns an error "too much recursion".
How can I trigger dragging manually? Any suggestions? | It turns out to be much simpler than you'd expect. Looking at the .trigger() method's documentation, no mention is made to the fact that one can also supply the original event as an argument and not just a string representation of the event type.
Thus one can achieve delegated dragging more efficiently like so:
```
$("ul#dynamiclist").delegate("li", "mousedown", function(event) {
$(this).draggable({
helper: "clone",
cursorAt: { left: 5, top: -5 },
cursor: "move",
stop: function() {
$(this).draggable("destroy");
}
}); });
```
The ideal solution would have been for the UI library to have some method to perform this type of delegation natively for dynamic elements....
Note that this is applicable to jQuery 1.4.2 & jQuery UI 1.7.2 | Answers above seem overcomplicated.
```
$('.nonDraggableObjectWhichTriggersDrag').mousedown(function(e) {
$('.draggableObject').trigger(e);
});
``` | Trigger Mouse Dragging in jQuery UI | [
"",
"javascript",
"jquery",
"user-interface",
"triggers",
"drag",
""
] |
how can i find out which class/method has called the actual method? | You could try to create an exception to get its stacktrace.
```
Throwable t = new Throwable();
StackTraceElement[] stackTraceElements = t.getStackTrace();
```
Now `stackTraceElement[0]` contains the caller of the current method.
But beware (from [Throwable.getStackTrace()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Throwable.html#getStackTrace())):
> Some virtual machines may, under some
> circumstances, omit one or more stack
> frames from the stack trace. In the
> extreme case, a virtual machine that
> has no stack trace information
> concerning this throwable is permitted
> to return a zero-length array from
> this method. Generally speaking, the
> array returned by this method will
> contain one element for every frame
> that would be printed by
> printStackTrace. | Here's one way that I've used:
```
StackTraceElement element=Thread.currentThread().getStackTrace()[3];
String className=element.getClassName();
String methodName=element.getMethodName();
```
[3] is hardcoded because:
[0] is Thread.dumpThreads()
[1] is Thread.getStackTrace()
[2] is the current method
[3] is the one before the current method | How do I find out the calling class? | [
"",
"java",
""
] |
I have an ArrayList that contains,
```
[0] = "1"
[1] = "10"
[2] = "2"
[3] = "15"
[4] = "17"
[5] = "5"
[6] = "6"
[7] = "27"
[8] = "8"
[9] = "9"
```
Now i need to sort the array list such that it becomes,
```
[0] = "1"
[1] = "2"
[2] = "5"
[3] = "6"
[4] = "8"
[5] = "9"
[6] = "10"
[7] = "15"
[8] = "17"
[9] = "27"
```
At last i will be getting the values from ArrayList and using them as **'int'** values. How can i do this? Or shall i convert them to int at first and then sort them.? | If you can be sure the list contains only strings that can be transformed to integers, then with the **[`IEnumerable<T>.OrderBy`](http://msdn.microsoft.com/en-us/library/bb534966.aspx)** extension method, try this:
```
var sortedList = list.OrderBy(item => int.Parse(item));
```
If you're using an `ArrayList` instead of a `List<string>` (boo!), you'll need to `Cast` first:
```
var sortedList = list.Cast<string>().OrderBy(item => int.Parse(item));
```
You can also define your own comparer as JaredPar noted, but IMO that's a lot of work for something that's already implemented. However, it's more efficient. | There are numerous sort methods in the framework including ArrayList.Sort. The problem is that they are all going to sort alphabetically and not numerically. You'll need to write a custom sorter that understands numeric sorts.
Try the following (some argument checking left out for brevity)
```
public class NumericComparer : IComparer {
public int Compare(object x, object y) {
string left = (string)x;
string right = (string)y;
int max = Math.Min(left.Length, right.Length);
for ( int i = 0; i < max; i++ ) {
if ( left[i] != right[i] ) {
return left[i] - right[i];
}
}
return left.Length - right.Length;
}
}
list.Sort(new NumericComparer());
``` | How to sort elements of array list in C# | [
"",
"c#",
""
] |
> Duplicate of
> [C++ union in C#](https://stackoverflow.com/questions/126781/c-union-in-c)
Is there a C# equivalent to the C union typedef?
What is the equivalent of the following in C#?
```
typedef union byte_array
{
struct{byte byte1; byte byte2; byte byte3; byte byte4;};
struct{int int1; int int2;};
};byte_array
``` | C# doesn't natively support the C/C++ notion of unions. You can however use the StructLayout(LayoutKind.Explicit) and FieldOffset attributes to create equivalent functionality.
Note that this works only for primitive types like int and float.
```
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct byte_array
{
[FieldOffset(0)]
public byte byte1;
[FieldOffset(1)]
public byte byte2;
[FieldOffset(2)]
public byte byte3;
[FieldOffset(3)]
public byte byte4;
[FieldOffset(0)]
public short int1;
[FieldOffset(2)]
public short int2;
}
``` | Using the [`StructLayout`](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx) attribute, it would look a little like this:
```
[StructLayout(LayoutKind.Explicit, Pack=1)]
public struct ByteArrayUnion
{
#region Byte Fields union
[FieldOffset(0)]
public byte Byte1;
[FieldOffset(1)]
public byte Byte2;
[FieldOffset(2)]
public byte Byte3;
[FieldOffset(3)]
public byte Byte4;
#endregion
#region Int Field union
[FieldOffset(0)]
public int Int1;
[FieldOffset(4)]
public int Int2;
#endregion
}
``` | C# equivalent to C union | [
"",
"c#",
"c",
"unions",
""
] |
I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:
```
$string = 'Hello <?php echo 'World';?>';
echo $string;
```
**Output**
```
Hello
```
**Source Code**
```
Hello <?php echo 'World';?>
```
When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.
One thing to consider is that the PHP could be located anywhere in the string at any given time.
**\* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. \***
Thanks again for any help I may receive. | ```
$str = "Hello
<?php echo 'World';?>";
$matches = array();
preg_match('/<\?php (.+) \?>/x', $str, $matches);
eval($matches[1]);
```
This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.
Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.
Edit: Would need adapting with preg\_replace\_callback to remove the source/interpolate correctly. | You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.
**Answer to the edit:**
Use preg\_replace\_callback to get the php part, eval it, replace the input to the output, then echo it.
But. If you should eval things come from database, i'm almost sure, it's a design error. | how to eval() a segment of a string | [
"",
"php",
"string",
"eval",
""
] |
To get TimeSpan in minutes from given two Dates I am doing the following
```
int totalMinutes = 0;
TimeSpan outresult = end.Subtract(start);
totalMinutes = totalMinutes + ((end.Subtract(start).Days) * 24 * 60) + ((end.Subtract(start).Hours) * 60) +(end.Subtract(start).Minutes);
return totalMinutes;
```
Is there a better way? | ```
TimeSpan span = end-start;
double totalMinutes = span.TotalMinutes;
``` | Why not just doing it this way?
```
DateTime dt1 = new DateTime(2009, 6, 1);
DateTime dt2 = DateTime.Now;
double totalminutes = (dt2 - dt1).TotalMinutes;
```
Hope this helps. | How do I get TimeSpan in minutes given two Dates? | [
"",
"c#",
""
] |
I'm curious to find out if and when C++ meta templates are a good design choice for systems small to large. I understand that they increase your build time in order to speed up your execution time. However, I've heard that the meta template code is inherently hard to understand by many developers, which could be a problem for a large group of people working on a system with a very large code base (millions of lines of code). Where do you think C++ meta templates are useful (or not)? | Metaprogramming is just another tool in a (C++) programmers' toolbox - it has many great applications, but like anything can be mis- or over- used. I think it's got a bad reputation in terms of 'hard to use', and I think this mainly comes from the fact that it's a significant addition to the language and so takes a while to learn.
As an example of real-world use; I've used template metaprogramming to implement Compile-time asserts and shim libraries in the past; implementing these without templates would either have been impossible or required significantly more code than I had to write.
In the case of the shim library it could have been implemented in a classic object-orientated fashion which could have been designed to have a similar (low) level of code duplication as the templated implementation; however it's runtime performance would have been significantly worse.
If you want to see some good examples of how it can be used, I suggest you read [Modern C++ Design](http://en.wikipedia.org/wiki/Modern_C%2B%2B_Design) by Andrei Alexandrescu (there is a [sample chapter](http://www.informit.com/articles/article.aspx?p=25264) on the publisher's website) - IMO this is one of the best books on the subject. | Template metaprogramming doesn't make your code "inherently hard to understand". It moves the complexity around. The underlying metaprogramming code may be a pain to understand, but at the same time, it typically simplifies client code.
If its effect was *just* to make code harder to read, it wouldn't be used. The reason it is used from time to time is exactly that it simplifies the code as a whole.
Of course, programmers who are not familiar with metaprogramming will have trouble reading or maintaining the code, but isn't that just an argument against working with programmers who don't know their stuff?
Programmers who don't know about a for-loop wil find that hard to read too. | C++ Meta Templates: A Good or Bad Design Choice? | [
"",
"c++",
"metaprogramming",
""
] |
What does the `$` sign in jQuery stand for? | The jQuery object :)
From the jQuery documentation:
> By default, jQuery uses "$" as a shortcut for "jQuery"
So, using `$("#id"`) or `jQuery("#id")` is the same. | Strange but true, you can use "$" as a function name in JavaScript. It is shorthand for jQuery(). Which you can use if you want. jQuery can be ran in compatibility mode if another library is using the $ already. Just use jQuery.noConflict(). $ is pretty commonly used as a selector function in JS.
In jQuery the $ function does much more than select things though.
1. You can pass it a selector to get a
collection of matching elements from the DOM.
2. You can pass
it a function to run when the
document is ready (similar to
body.onload() but better).
3. You can pass it a string of HTML to turn
into a DOM element which you can
then inject into the document.
4. You can pass it a DOM element or
elements that you want to wrap with
the jQuery object.
Here is the documentation: <https://api.jquery.com/jQuery/> | What is the meaning of symbol $ in jQuery? | [
"",
"javascript",
"jquery",
""
] |
I have a WCF service that I'm using to replace an old ASP.NET web service. The service appears to be working fine but it is unable to handle simultaneous requests for some reason. My implementation of the service has the following properties:
```
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class HHService : IHHService
```
My host declaration looks like this:
```
baseAddress = new Uri("http://0.0.0.0:8888/HandHeld/");
host = new ServiceHost(typeof(HHService), baseAddress);
ServiceMetadataBehavior behavior;
behavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (behavior == null)
{
behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
behavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(behavior);
}
host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
host.AddServiceEndpoint(typeof(IHHService), new BasicHttpBinding(), "HHService.asmx");
HHService.LogMessage += new EventHandler<HHService.LogMessageEventArgs>(HHService_LogMessage);
host.Open();
```
The service runs and returns correct results, but if two clients try to make a call at the same time one client will block until the other is finished rather than the calls executing together. I'm not using any configuration files. I'm trying to do everything programmatically. Do i have something setup incorrectly that's causing this behavior? I've run other services using the NetTCPBinding without this problem.
**EDIT:**
In response to John Saunders:
I'm not familiar with any ASP.NET compatibility mode. I'm not using any session state the service is stateless it just processes requests. Aside from the implementation of the actual methods everything else I've done is in the code listed here.
**Possible Solution:**
I was calling the `host.Open()` function from the form\_load event of the main form. I moved the call to a separate thread. All this thread did was call `host.Open()` but now the service appears to be behaving as I would expect. | If your instance context mode is PerCall, then your server is always single-threaded, since by definition, every call gets a new server instance.
This works okay in a IIS environment, where IIS can spin up several server instances to handle n concurrent callers, one each as a single-threaded server for each incoming request.
You mention in one of your comments your hosting your WCF inside a forms app - this might be a design decision you need to reconsider - this is not really optimal, since the Winforms app cannot easily handle multiple callers and spin up several instances of the service code.
Marc | Is there a lock somewhere in your service function? | Why is my Winforms-hosted WCF service single threaded? | [
"",
"c#",
"winforms",
"wcf",
"basichttpbinding",
""
] |
I am trying to programatically download a file through clicking a link, on my site (it's a .doc file sitting on my web server). This is my code:
```
string File = Server.MapPath(@"filename.doc");
string FileName = "filename.doc";
if (System.IO.File.Exists(FileName))
{
FileInfo fileInfo = new FileInfo(File);
long Length = fileInfo.Length;
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", Length.ToString());
Response.WriteFile(fileInfo.FullName);
}
```
This is in a buttonclick event handler. Ok I could do something about the file path/file name code to make it neater, but when clicking the button, the page refreshes. On localhost, this code works fine and allows me to download the file ok. What am I doing wrong?
Thanks | Try a slightly modified version:
```
string File = Server.MapPath(@"filename.doc");
string FileName = "filename.doc";
if (System.IO.File.Exists(FileName))
{
FileInfo fileInfo = new FileInfo(File);
Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.WriteFile(fileInfo.FullName);
Response.End();
}
``` | Rather than having a button click event handler you could have a download.aspx page that you could link to instead.
This page could then have your code in the page load event. Also add Response.Clear(); before your Response.ContentType = "Application/msword"; line and also add Response.End(); after your Response.WriteFile(fileInfo.FullName); line. | Allowing user to download from my site through Response.WriteFile() | [
"",
"c#",
"asp.net",
""
] |
The installer for my .NET app consists of two file MyApp.msi and setup.exe.
I want to have a single installer MyApp.exe (self extracting archive will do) with a specified icon.
How can I do that? Is there any free tool available? | [InnoSetup](http://www.innosetup.com/) and [NSIS](http://nsis.sourceforge.net/) are free tools for creating application setups.
For InnoSetup, [ISTool](http://www.istool.org/) makes it very easy to create setup scripts. | Technically the MSI is a single-file installer. It can be double-clicked to install the application. Setup.exe just launches the MSI. | Creating single file installer for .NET application | [
"",
"c#",
"packaging",
""
] |
Can anyone explain to why Server.Execute() is requiring my rendered UserControls to contain `<form>` tags (or alternately, what I am doing wrong that is making Server.Execute() require form tags in my UserControls)?
I have created an ASMX service to dynamically load UserControls via JQuery+JSON as follows:
ControlService.asmx
```
<%@ WebService Language="C#" CodeBehind="ControlService.asmx.cs" Class="ManagementConcepts.WebServices.ControlService" %>
```
ControlService.cs
```
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ControlService : System.Web.Services.WebService
{
private string GetControl(String controlName, String ClassId)
{
Page page = new Page();
UserControl ctl = (UserControl)page.LoadControl(controlName);
page.Controls.Add(ctl);
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetSimpleControl(string ClassId)
{
return GetControl("SimpleControl.ascx", ClassId);
}
}
```
I load the control into a page via the following bit of JQuery which replaces a with the id ContentPlaceholder with the HTML returned from the service:
JQueryControlLoadExample.aspx
```
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JQueryControlLoadExample.aspx.cs" Inherits="ControlService_Prototype._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ControlService Prototype</title>
</head>
<body>
<form id="theForm" runat="server" action="JQueryControlLoadExample.aspx">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" >
<Scripts>
<asp:ScriptReference NotifyScriptLoaded="true" Path="~/Scripts/jquery-1.3.2.js" />
</Scripts>
</asp:ScriptManager>
<div>
<asp:HiddenField runat="server" ID="hdncourse"/>
<asp:HiddenField runat="server" ID="hdnTargetContent" Value="GetSimpleControl"/>
<div runat="server" id="ContentPlaceholder" class="loading"></div>
</div>
<script type="text/javascript">
$(document).ready(function() {
var servicemethod = document.getElementById("hdnTargetContent").value;
$.ajax({
type: "POST",
url: "ControlService.asmx/" + servicemethod,
data: "{'ClassId':'"+document.getElementById("hdncourse").value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#ContentPlaceholder').html(msg.d);
}
});
});
</script>
</form>
</body>
</html>
```
This works with one huge caveat. If I don't define a form inside the .ascx control's markup then HttpContext.Current.Server.Execute() throws an HttpException with the following message:
`Control 'hdnspecialoffer' of type 'HiddenField' must be placed inside a form tag with runat=server.`
SimpleControl.ascx
```
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SimpleControl.ascx.cs" Inherits="ControlService_Prototype.UserControls.SimpleControl" %>
<asp:HiddenField runat="server" ID="hdnspecialoffer"/>
```
When I added a form tag to the ascx control to work around this, the form would render, but the renderer rewrites the form tag in the control so that it POSTs back to the ASMX service instead of the form defined in the aspx page.
I googled around and discovered Scott Guthrie's excellent [ViewManager](http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx) example. I don't see anything fundamentally different from what he did there, which leads me to believe that what I am doing ought to work. | Looks like the answer was buried in the comments for the [ViewManager](http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx)
You'll want a class that inherits from Page and overrides the check for server controls not in a form
```
public class FormlessPage : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
}
}
```
Then when you render the control, use
```
Page page = new FormlessPage();
UserControl ctl = (UserControl)page.LoadControl(controlName);
//etc
```
I'm assuming you'll lose the ability to have events firing from any controls rendered this way. | Instead of using an asp.net hidden control on your user control, just use a regular html hidden input with the code tags <% %> to fill the data like this:
```
<input id="Hidden1" type="hidden" value="<%= text %>"/>
```
"text" is a public variable in the code behind file.
This worked for me and didn't require a form with `runat="server"`. | Issues rendering UserControl using Server.Execute() in an ASMX web service | [
"",
"c#",
"asp.net",
"user-controls",
"asmx",
""
] |
I commonly run into a scenario where "the powers that be" want an exact copy of a page in multiple places on a website. Rather than actually duplicate the content, all I do is override the section in the nav that is highlighted, and then include the page. The final page looks something like this:
```
<?php
$top_nav_item_id = 'teen';
include('../interests/teacher-resources.php');
?>
```
This typically works. I am trying to duplicate this for a blog category, done in wordpress. All I seem to get is a blank page, no matter what I do. I've tried all of the following lines:
```
<?php
include('../blog/index.php');
include('../blog/type/teen/index.php');
include('../blog/type/teen/');
include('../blog/');
?>
```
Does anyone have any ideas? Is this a URL rewriting thing? Do I have to include the template file for that particular category?
Any help is appreciated. | This solution is a bit of a hack, but then, the problem is a bit of a hack to begin with.
I received a good explanation of why I couldn't include the blog page, but not any alternatives that would work for me.
My final solution was to modify the category template for that page directly. As stated originally, I use $top\_nav\_item\_id to control which menu item is highlighted in the nav, to give the appearance of the page belonging to that section. Rather than override this, I simply made it conditional on a query string. As long as the user is following legit links on my site, they will get the correct query string and have no problems.
$\_POST is disabled in Wordpress. $query\_string (built into WP) uses some sort of caching, and would always display as it was first loaded.
Final solution:
```
if(strtolower($_SERVER['QUERY_STRING'])=='display=teen') {
$top_nav_item_id = 'teen';
} else {
$top_nav_item_id = 'programs';
}
```
Thanks to all who tried to help. | PHP `include` expects files, not URLs, so it doesn't have access to the URL namespace exposed by WordPress. Those files don't exist on-disk; mod\_rewrite first turns the pretty URLs into an internal request to `index.php`, WordPress figures out what you really wanted based on the original URL, fetches a bunch of stuff from the database, then produces the page. | Why Can't I Include A Blog? | [
"",
"php",
"wordpress",
"include",
""
] |
we have an internal webapplication running on tomcat, build on Spring. The webapplication front-end is build with Flex.
I would like to create a cross-platform systray application that allows to go the home page of the application and displays alerts when certain things happen in the server.
What would you think is the best technology for:
* The systray itself? Java Swing?
* Communication between the server and the systray? Webservice? RSS feed? Spring remoting? JMX Notifications?
regards,
Wim | If you want to stay with Java you have two options:
* Use Swing/AWT. Make sure you are using Java 6 and above (you can install it with your application), since it has support for system tray (from the API):
```
TrayIcon trayIcon = null;
if (SystemTray.isSupported()) {
// get the SystemTray instance
SystemTray tray = SystemTray.getSystemTray();
// load an image
Image image = Toolkit.getDefaultToolkit.getImage("");
// create a action listener to listen for default action executed on
// the tray icon
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// execute default action of the application
// ...
}
};
// create a popup menu
PopupMenu popup = new PopupMenu();
// create menu item for the default action
MenuItem defaultItem = new MenuItem("");
defaultItem.addActionListener(listener);
popup.add(defaultItem);
// / ... add other items
// construct a TrayIcon
trayIcon = new TrayIcon(image, "Tray Demo", popup);
// set the TrayIcon properties
trayIcon.addActionListener(listener);
// ...
// add the tray image
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println(e);
}
// ...
} else {
// disable tray option in your application or
// perform other actions
// ...
}
// ...
// some time later
// the application state has changed - update the image
if (trayIcon != null) {
trayIcon.setImage(updatedImage);
}
// ...
```
* Use [SWT](http://www.eclipse.org/swt/)/[JFace](http://wiki.eclipse.org/index.php/JFace). Here is an example (taken from [here](http://www.eclipse.org/swt/snippets/)):
```
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
Image image = new Image(display, 16, 16);
final Tray tray = display.getSystemTray();
if (tray == null) {
System.out.println("The system tray is not available");
} else {
final TrayItem item = new TrayItem(tray, SWT.NONE);
item.setToolTipText("SWT TrayItem");
item.addListener(SWT.Show, new Listener() {
public void handleEvent(Event event) {
System.out.println("show");
}
});
item.addListener(SWT.Hide, new Listener() {
public void handleEvent(Event event) {
System.out.println("hide");
}
});
item.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
System.out.println("selection");
}
});
item.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event event) {
System.out.println("default selection");
}
});
final Menu menu = new Menu(shell, SWT.POP_UP);
for (int i = 0; i < 8; i++) {
MenuItem mi = new MenuItem(menu, SWT.PUSH);
mi.setText("Item" + i);
mi.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
System.out.println("selection " + event.widget);
}
});
if (i == 0)
menu.setDefaultItem(mi);
}
item.addListener(SWT.MenuDetect, new Listener() {
public void handleEvent(Event event) {
menu.setVisible(true);
}
});
item.setImage(image);
}
shell.setBounds(50, 50, 300, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
image.dispose();
display.dispose();
}
``` | With Adobe AIR and BlazeDS or LCDS you can easily build this type of application. | What technology to use to write systray front-end to webapp? | [
"",
"java",
"apache-flex",
"swing",
"spring",
""
] |
I know you can overload an existing operator. I want to know if it is possible to create a new operator. Here's my scenario.
I want this:
```
var x = (y < z) ? y : z;
```
To be equivalent to this:
```
var x = y <? z;
```
In other words, I would like to create my own `<?` operator. | No, it is not possible. You would need to create a method instead | No, but you can overload [some existing operators](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/operators) in C#.
In some other languages, like F#, you can use:
```
let (<?) = min
``` | Is it possible to create a new operator in c#? | [
"",
"c#",
".net",
"operators",
""
] |
The following code compiles fine in VC6 but when I compile the same project in VS2008 it gives the following error
error C2146: syntax error : missing ';' before identifier 'm\_pItr'
```
template <class pKey, class Data, class pCompare,
class hKey = int, class hCompare = less<hKey>,
class sKey = int, class sCompare = less<sKey>,
class tKey = int, class tCompare = less<tKey>,
class cKey = int, class cCompare = less<cKey>>
class GCache
{
private:
typedef map<pKey, Data, pCompare> PRIMARY_MAP;
PRIMARY_MAP pMap;
PRIMARY_MAP::iterator m_pItr; //error here
//Code truncated
}
```
Any ideas of what is wrong here? Someone with experience in migrating C++ code from VC6 to VC2005/2008 might be able to help. | You may need to insert 'typename', to tell the compiler PRIMARY\_MAP::iterator is, in all cases, a type.
e.g.
```
class GCache
{
private:
typedef map<pKey, Data, pCompare> PRIMARY_MAP;
PRIMARY_MAP pMap;
typename PRIMARY_MAP::iterator m_pItr;
//Code truncated
}
``` | It should be `typename PRIMARY_MAP::iterator m_pItr;` . Otherwise compiler thinks that PRIMARY\_MAP::iterator is a static object and will not be able to recognize it as a type. So you have to give an hint to the compiler indicating that it is a type and not a static object. | missing ; before identifier while compiling VC6 code in VC9 | [
"",
"c++",
"migration",
"visual-c++-6",
""
] |
mod1.py
```
import mod2
class Universe:
def __init__(self):
pass
def answer(self):
return 42
u = Universe()
mod2.show_answer(u)
```
mod2.py
```
#import mod1 -- not necessary
def show_answer(thing):
print thing.answer()
```
Coming from a C++ background I had the feeling it was necessary to import the module containing the Universe class definition before the show\_answer function would work. I.e. everything had to be declared before it could be used.
Am I right in thinking this isn't necessary? This is duck typing, right? So if an import isn't required to see the methods of a class, I'd at least need it for the class definition itself and the top level functions of a module?
In one script I've written, I even went as far as writing a base class to declare an interface with a set of methods, and then deriving concrete classes to inherit that interface, but I think I get it now - that's just wrong in Python, and whether an object has a particular method is checked at runtime at the point where the call is made?
I realise Python is *so* much more dynamic than C++, it's taken me a while to see how little code you actually need to write!
I think I know the answer to this question, but I just wanted to get clarification and make sure I was on the right track.
UPDATE: Thanks for all the answers, I think I should clarify my question now:
Does mod2.show\_answer() need an import (of any description) to know that thing has a method called answer(), or is that determined dynamically at runtime? | `import` is all about names -- mostly "bare names" that are bound at top level (AKA global level, AKA module-level names) in a certain module, say `mod2`. When you've done `import mod2`, you get the `mod2` namespace as an available name (top-level in your own module, if you're doing the `import` itself as top level, as is most common; but a local `import` within a function would make `mod2` a local variable of that function, etc); and therefore you can use `mod2.foobar` to access the name `foobar` that's bound at top level in `mod2`. If you have no need to access such names, then you have no need to `import mod2` in your own module. | In this case you're right: show\_answer() is given an object, of which it calls the method "answer". As long as the object given to show\_answer() has such a method, it doesn't matter where the object comes from.
If, however, you wanted to create an instance of Universe inside mod2, you'd have to import mod1, because Universe is not in the mod2 namespace, even after mod2 has been imported by mod1. | Python - when is 'import' required? | [
"",
"python",
"import",
"module",
""
] |
I'm using Console\_Getopt in PHP 5.2, and finding it surprising about how different it is from getopt in other languages (perl, bash, java). Can anyone recommend how to parse the args from the array "$opts" returned?
php myprog.php -a varA -c -b varB
```
$o= new Console_Getopt;
$opts = $o->getopt($argv, "a:b:c");
print_r($opts);
```
// the print\_r returns below
```
Array
(
[0] => Array
(
[0] => Array
(
[0] => a
[1] => varA
)
[1] => Array
(
[0] => c
[1] =>
)
[2] => Array
(
[0] => b
[1] => varB
)
)
[1] => Array
(
)
)
```
I started doing something like below, which is long-winded, so I'm looking for suggestions on dealing with command-line flags in php.
```
foreach($opts[0] as $i -> $keyval) {
list($key, $val) = $keyval;
if($key == 'a') {
print "valueForA: $val\n";
} else if($key == 'b') {
print "valueForB: $val\n";
} else if($key == 'c') {
print "c is set\n";
}
}
```
I wonder why PHP's getopt isn't like perl's, where the array's key is the flag eg $opts{'a'} .. that would be convenient. | Per the inline documentation
> The return value is an array of two elements: the list of parsed
> options and the list of non-option command-line arguments. Each entry in
> the list of parsed options is a pair of elements - the first one
> specifies the option, and the second one specifies the option argument,
> if there was one.
Which means you easily discard the second array, and assume a commitment to the keeping the array of arrays, first element option, second element value, format.
With that assumption in place, try
```
$o= new Console_Getopt;
$opts = $o->getopt($argv, "a:b:c");
print_r(getHashOfOpts($opts));
function getHashOfOpts($opts) {
$opts = $opts[0];
$return_opts = $opts;
$return_opts = Array();
foreach($opts as $pair){
$return_opts[$pair[0]] = $pair[1];
}
return $return_opts;
}
```
to get an data structure more of your liking.
As for why this is different than other implementation of getopt, ask [the maintainers](http://pear.php.net/package/Console_Getopt). | Check GetOptionKit for PHP:
<https://github.com/c9s/php-GetOptionKit>
## Synopsis
```
use GetOptionKit\OptionCollection;
use GetOptionKit\OptionParser;
$options = new OptionCollection;
$options->add( 'f|foo:' , 'option require value' ); # returns spec object.
$options->add( 'b|bar+' , 'option with multiple value' );
$options->add( 'z|zoo?' , 'option with optional value' );
$options->add( 'f|foo:=i' , 'option require value, with integer type' );
$options->add( 'f|foo:=s' , 'option require value, with string type' );
$options->add( 'v|verbose' , 'verbose flag' );
$options->add( 'd|debug' , 'debug flag' );
$parser = new OptionParser($options);
$result = $parser->parse( array( 'program' , '-f' , 'foo value' , '-v' , '-d' ) );
$spec = $result->verbose;
$spec = $result->debug;
$spec->value; # get value
```
GetOptionKit\OptionPrinter can print options for you:
```
* Available options:
-f, --foo option requires a value.
-b, --bar option with multiple value.
-z, --zoo option with optional value.
-v, --verbose verbose message.
-d, --debug debug message.
--long long option name only.
-s short option name only.
``` | php's command line option parsing, howto | [
"",
"php",
"command-line-interface",
""
] |
I'm attempting to make a class that will convert ArrayLists of objects into ArrayLists of other objects. i.e.
```
ArrayList<Foo> convert(ArrayList<Bar> input){
//conversion logic
}
ArrayList<Bar> convert(ArrayList<Foo> input){
//conversion logic
}
```
Unfortunately Java doesn't want to have two functions with the same name and what it believes to be the same inputs and outputs.
I'm attempting to go a different route. Instead of multiple functions with the same name, I want to make one function that accepts an ArrayList, determines which type of object is inside, does the proper conversion, and returns an ArrayList:
```
ArrayList convert(ArrayList input){
//conversion logic for Foo
//conversion logic for Bar
}
```
Is something like this possible? | How about an interface:
```
public class Converter<From, To> {
List<To> convert(List<From> input);
}
```
And then have as many implementations as you want. For example:
```
private static final Converter<Foo, Bar> fooToBarConverter = new Converter<Foo, Bar>() {
public List<Bar> convert(List<Foo> input) {
...
}
}
``` | Try:
```
public <T, U> ArrayList<U> convert(Class<T> typeIn, ArrayList<T> input){
// dispatch on typeIn
}
```
Or better yet
```
public <T, U, V extends ArrayList<U>> V convert(Class<T> typeIn,
Class<V> typeOut, ArrayList<T> input){
// dispatch on typeIn
return typeOut.cast(yourConversionResult);
}
```
Because you might return `ArrayList<Foo>` or `ArrayList<Bar>` within the same method and having the proper cast will help you return them without compiler warnings.
**Edit:** The return type cast for the second sample wasn't going to work. Tried to fix it | Detect type of object in ArrayList | [
"",
"java",
""
] |
I have an index view that lists items, and it's a long list so I use Paginator to limit items to 50-to-a-view.
Each item has an "edit" link that goes to an edit view with inputs/validations/etc. When that form is submitted, I redirect the use back to the index view.
So far so good, but here's the rub:
If a user is on page N of the index and they click edit and edit an item, I want them to be redirected back to page N of the index. If I knew the page number, I could just stick "/page:N" on to end of the URL, but I have no idea how I can get the page number. (N could be any page number, but especially >=2)
Any ideas would be appreciated. | The page number should be part of the $params var in the list view. Just tack it onto the end of the edit link and handle it from there. On the edit page you will need a way to take in the optional page number, store it during any form submission, and forward back to the list with the same page number. | I created a component that saves the page in the session. Then in the app\_controller.php, I check to see if there is anything in the session for the particular model being used and then add that to the url. If you are interested in the code for the component, message me. I also store the order, if the user changed the sort order in the index page before editing.
See here for the source:
<http://github.com/jimiyash/cake-pluggables/blob/a0c3774982c19d02cfdd19a2977eabe046a4b294/controllers/components/memory.php>
Here is the gist of what I am doing.
```
//controller or component code
if(!empty($params['named']) && !empty($params['controller']) && $params['action'] == 'admin_index'){
$this->Session->write("Pagem.{$params['controller']}", $params['named']);
}
//app_controller.php
$redirectNew = "";
if(is_array($redirectTo)){
if(!empty($params['prefix']) && $params['prefix'] == 'admin'){
$redirectNew .= '/admin';
}
if(!empty($params['controller'])){
$redirectNew .= "/" . $params['controller'];
}
if(!empty($redirectTo['action'])){
$redirectNew .= "/" . $redirectTo['action'];
}
} else {
$redirectNew = $redirectTo;
}
$controller = $params['controller'];
if($this->Session->check("Pagem.$controller")){
$settings = $this->Session->read("Pagem.$controller");
$append = array();
foreach($settings as $key=>$value){
$append[] = "$key:$value";
}
return $redirectNew . "/" . join("/", $append);
} else {
return $redirectNew;
}
``` | How do you maintain page number after redirect in CakePHP? | [
"",
"php",
"cakephp",
"pagination",
"http-redirect",
""
] |
I have a function that take an argument which can be either a single item or a double item:
```
def iterable(arg)
if #arg is an iterable:
print "yes"
else:
print "no"
```
so that:
```
>>> iterable( ("f","f") )
yes
>>> iterable( ["f","f"] )
yes
>>> iterable("ff")
no
```
The problem is that string is technically iterable, so I can't just catch the ValueError when trying `arg[1]`. I don't want to use isinstance(), because that's not good practice (or so I'm told). | Use isinstance (I don't see why it's bad practice)
```
import types
if not isinstance(arg, types.StringTypes):
```
Note the use of StringTypes. It ensures that we don't forget about some obscure type of string.
On the upside, this also works for derived string classes.
```
class MyString(str):
pass
isinstance(MyString(" "), types.StringTypes) # true
```
Also, you might want to have a look at this [previous question](https://stackoverflow.com/questions/836387/how-can-i-tell-if-a-python-variable-is-a-string-or-a-list).
Cheers.
---
**NB:** behavior changed in Python 3 as `StringTypes` and `basestring` are no longer defined. Depending on your needs, you can replace them in `isinstance` by `str`, or a subset tuple of `(str, bytes, unicode)`, e.g. for Cython users.
As [@Theron Luhn](https://stackoverflow.com/questions/1055360/how-to-tell-a-variable-is-iterable-but-not-a-string#comment44380487_1055378) mentionned, you can also use `six`. | As of 2017, here is a portable solution that works with all versions of Python:
```
#!/usr/bin/env python
import collections
import six
def iterable(arg):
return (
isinstance(arg, collections.Iterable)
and not isinstance(arg, six.string_types)
)
# non-string iterables
assert iterable(("f", "f")) # tuple
assert iterable(["f", "f"]) # list
assert iterable(iter("ff")) # iterator
assert iterable(range(44)) # generator
assert iterable(b"ff") # bytes (Python 2 calls this a string)
# strings or non-iterables
assert not iterable(u"ff") # string
assert not iterable(44) # integer
assert not iterable(iterable) # function
``` | how to tell a variable is iterable but not a string | [
"",
"python",
""
] |
I have the following problem which I'm trying to solve with javascript. I have a div with a background image specified in a css file, and I want my javascript to change that image periodically (let`s say every 5 secs).
I know how to do that, the problem is that I have a folder of images to choose from for the back image. I need to be able to read the filenames (from the image folder) into an array, change the background image of the div, delay for 5 seconds and change again. | You're still going to need php or asp to query the folder for files. Javascript will not be able to "remotely" inspect the file system.
You can do something like the following in jQuery:
```
$.ajax({
url: 'getFolderAsArrayOfNames.php',
dataType: 'json',
success: function(data) {
for(var i=0;i<data.length;i++) {
// do what you need to do
}
});
});
```
And in your getFolderAsArrayOfNames.php, something like this:
```
echo "function "
.$_GET['callback']
."() {return "
.json_encode(scandir('somepath/*.jpg'))
."}";
``` | in your javascript, use an array like
```
var images = [ "image1.jpg", "image2.jpg", "image3.jpg" ];
function changeImage() {
var image = document.getElementById("yourimage");
image.src=$images[changeImage.imageNumber];
changeImage.imageNumber = ++changeImage.imageNumber % images.length;
}
changeImage.imageNumber=0;
setInterval(changeImage,5000);
```
The values in the array should be generated by your php | Javascript read files in folder | [
"",
"javascript",
"css",
""
] |
I would like to add an overlay image on a Google Map. The image is a SVG file I have generated (Python with SVGFig).
I am using the following code:
```
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(48.8, 2.4), 12);
// ground overlay
var boundaries = new GLatLngBounds(new GLatLng(48.283188032632829, 1.9675270369830129), new GLatLng(49.187215000000002, 2.7771877478303999));
var oldmap = new GGroundOverlay("test.svg", boundaries);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.addOverlay(oldmap);
}
```
Surprisingly, it works with Safari 4, but it doesn't work with Firefox (with Safari 3, the background is not transparent).
Does anyone have an idea on how I could overlay an SVG?
PS1: I read some works like [this](http://www.bdcc.co.uk/Gmaps/BdccGmapBits.htm) or the source code of swa.ethz.ch/googlemaps, but it seems that they have to use JavaScript code to parse the SVG and add one by one all the elements (but I did not understand all the source...).
PS2: The SVG is composed of different filled paths and circles, with transparency.
If there is no solution to overlay my SVG, I can use 2 alternative solutions:
* rasterize the SVG
* convert the paths and circles in GPolygons
But I do not really like the 1st solution because of the poor quality of the bitmap and the time to generate it with antialiasing.
And for the 2nd solution, the arcs, ellipses and circles will have to be decomposed into small polylines. A lot of them will be necessary for a good result. But I have around 3000 arcs and circles to draw, so... | Here are some news (I hope it's better to put them here in an answer, instead of editing my questions or to create a new question. Please feel free to move it if needed, or to tell me, so as I can rectify):
My problem was the following:
```
var oldmap = new GGroundOverlay("test.svg", boundaries);
map.addOverlay(oldmap);
```
did not work on Safari 3, Firefox and Opera (IE is not enable to draw SVG).
In fact, this code produce the insertion (in a `<div>`) of the following element
```
<img src="test.svg" style=".....">
```
And Safari 4 is able to draw a SVG file as an image, but this is not the way to do for the other browser. So the idea is now to create a custom overlay for the SVG, as explained [here](http://code.google.com/intl/fr-FR/apis/maps/documentation/overlays.html#Custom_Overlays).
That's the reason why I asked for [this question](https://stackoverflow.com/questions/1071328/how-to-produce-same-result-on-different-browsers-when-embedding-svg-file-in-html) (I am sorry, but HTML/javascript are not my strongest points).
And since there is a small bug with Webkit for rendering a SVG with transparent background with `<object>`element, I need to use `<object>` or `<img>` accordingly to the browser (I don't like this, but... for the moment, it's still the quick-and-dirty experiments)
So I started with this code (still work in progress):
```
// create the object
function myOverlay(SVGurl, bounds)
{
this.url_ = SVGurl;
this.bounds_ = bounds;
}
// prototype
myOverlay.prototype = new GOverlay();
// initialize
myOverlay.prototype.initialize = function(map)
{
// create the div
var div = document.createElement("div");
div.style.position = "absolute";
div.setAttribute('id',"SVGdiv");
div.setAttribute('width',"900px");
div.setAttribute('height',"900px");
// add it with the same z-index as the map
this.map_ = map;
this.div_ = div;
//create new svg root element and set attributes
var svgRoot;
if (BrowserDetect.browser=='Safari')
{
// Bug in webkit: with <objec> element, Safari put a white background... :-(
svgRoot = document.createElement("img");
svgRoot.setAttribute("id", "SVGelement");
svgRoot.setAttribute("type", "image/svg+xml");
svgRoot.setAttribute("style","width:900px;height:900px");
svgRoot.setAttribute("src", "test.svg");
}
else //if (BrowserDetect.browser=='Firefox')
{
svgRoot = document.createElement("object");
svgRoot.setAttribute("id", "SVGelement");
svgRoot.setAttribute("type", "image/svg+xml");
svgRoot.setAttribute("style","width:900px;height:900px;");
svgRoot.setAttribute("data", "test.svg");
}
div.appendChild(svgRoot);
map.getPane(G_MAP_MAP_PANE).appendChild(div);
//this.redraw(true);
}
...
```
The `draw` function is not yet written.
I still have a problem (I progress slowly, thanks to what I read/learn everywhere, and also thanks to people who answer my questions).
Now, the problem is the following : with the `<object>` tag, the map is not draggable. All over the `<object>` element, the mouse pointer is not "the hand icon" to drag the map, but just the normal pointer.
And I did not find how to correct this. Should I add a new mouse event (I just saw mouse event when a click or a double-click append, but not for dragging the map...) ?
Or is there another way to add this layer so as to preserve the drag-ability ?
Thank you for your comments and answers.
PS: I also try to add one by one the elements of my SVG, but... in fact... I don't know how to add them in the DOM tree. In [this example](http://swa.ethz.ch/googlemaps/), the SVG is read and parsed with `GXml.parse()`, and all the elements with a given tag name are obtained (`xml.documentElement.getElementsByTagName`) and added to the SVG node (`svgNode.appendChild(node)`). But in my case, I need to add directly the SVG/XML tree (add all its elements), and there are different tags (`<defs>`, `<g>`, `<circle>`, `<path>`, etc.). It is may be simpler, but I don't know how to do.. :( | I spend the last evening on this problem, and I finally found the solution to my problem.
It was not so difficult.
The idea is, as Chris B. said, to load the SVG file with GDownloadUrl, parse it with GXml.parse() and add in the DOM tree every SVG elements I need
To simplify, I have supposed that all the SVG elements was put in a big group called "mainGroup". I have also supposed that some elements can be in the file.
So here is the library, based on the [Google Maps Custom Overlays](http://code.google.com/intl/fr-FR/apis/maps/documentation/overlays.html#Custom_Overlays):
```
// create the object
function overlaySVG( svgUrl, bounds)
{
this.svgUrl_ = svgUrl;
this.bounds_ = bounds;
}
// prototype
overlaySVG.prototype = new GOverlay();
// initialize
overlaySVG.prototype.initialize = function( map)
{
//create new div node
var svgDiv = document.createElement("div");
svgDiv.setAttribute( "id", "svgDivison");
//svgDiv.setAttribute( "style", "position:absolute");
svgDiv.style.position = "absolute";
svgDiv.style.top = 0;
svgDiv.style.left = 0;
svgDiv.style.height = 0;
svgDiv.style.width = 0;
map.getPane(G_MAP_MAP_PANE).appendChild(svgDiv);
// create new svg element and set attributes
var svgRoot = document.createElementNS( "http://www.w3.org/2000/svg", "svg");
svgRoot.setAttribute( "id", "svgRoot");
svgRoot.setAttribute( "width", "100%");
svgRoot.setAttribute( "height","100%");
svgDiv.appendChild( svgRoot);
// load the SVG file
GDownloadUrl( this.svgUrl_, function( data, responseCode)
{
var xml = GXml.parse(data);
// specify the svg attributes
svgRoot.setAttribute("viewBox", xml.documentElement.getAttribute("viewBox"));
// append the defs
var def = xml.documentElement.getElementsByTagName("defs");
//for( var int=0; i<def.length; i++)
svgRoot.appendChild(def[0].cloneNode(true));
//append the main group
var nodes = xml.documentElement.getElementsByTagName("g");
for (var i = 0; i < nodes.length; i++)
if (nodes[i].id=="mainGroup")
svgRoot.appendChild(nodes[i].cloneNode(true));
});
// keep interesting datas
this.svgDiv_ = svgDiv;
this.map_ = map;
// set position and zoom
this.redraw(true);
}
// remove from the map pane
overlaySVG.prototype.remove = function()
{
this.div_.parentNode.removeChild( this.div_);
}
// Copy our data to a new overlaySVG...
overlaySVG.prototype.copy = function()
{
return new overlaySVG( this.url_, this.bounds_, this.center_);
}
// Redraw based on the current projection and zoom level...
overlaySVG.prototype.redraw = function( force)
{
// We only need to redraw if the coordinate system has changed
if (!force) return;
// get the position in pixels of the bound
posNE = map.fromLatLngToDivPixel(this.bounds_.getNorthEast());
posSW = map.fromLatLngToDivPixel(this.bounds_.getSouthWest());
// compute the absolute position (in pixels) of the div ...
this.svgDiv_.style.left = Math.min(posNE.x,posSW.x) + "px";
this.svgDiv_.style.top = Math.min(posSW.y,posNE.y) + "px";
// ... and its size
this.svgDiv_.style.width = Math.abs(posSW.x - posNE.x) + "px";
this.svgDiv_.style.height = Math.abs(posSW.y - posNE.y) + "px";
}
```
And, you can use it with the following code:
```
if (GBrowserIsCompatible())
{
//load map
map = new GMap2(document.getElementById("map"), G_NORMAL_MAP);
// create overlay
var boundaries = new GLatLngBounds( new GLatLng(48.2831, 1.9675), new GLatLng(49.1872, 2.7774));
map.addOverlay( new overlaySVG( "test.svg", boundaries ));
//add control and set map center
map.addControl(new GLargeMapControl());
map.setCenter(new GLatLng(48.8, 2.4), 12);
}
```
So, you can use it exactly as you use the `GGroundOverlay` function, except that your SVG file should be created with the Mercator projection (but if you apply it on small area, like one city or smaller, you will not see the difference).
This should work with Safari, Firefox and Opera. You can try my small example [here](http://docmatic.fr/temp/test.html)
Tell me what do you think about it. | How can I overlay SVG diagrams on Google Maps? | [
"",
"javascript",
"google-maps",
"svg",
""
] |
I need a Postgres function to return a virtual table (like in Oracle) with custom content. The table would have 3 columns and an unknown number of rows.
I just couldn't find the correct syntax on the internet.
Imagine this:
```
CREATE OR REPLACE FUNCTION "public"."storeopeninghours_tostring" (numeric)
RETURNS setof record AS
DECLARE
open_id ALIAS FOR $1;
returnrecords setof record;
BEGIN
insert into returnrecords('1', '2', '3');
insert into returnrecords('3', '4', '5');
insert into returnrecords('3', '4', '5');
RETURN returnrecords;
END;
```
How is this written correctly? | (This is all tested with postgresql 8.3.7-- do you have an earlier version? just looking at your use of "ALIAS FOR $1")
```
CREATE OR REPLACE FUNCTION storeopeninghours_tostring(numeric)
RETURNS SETOF RECORD AS $$
DECLARE
open_id ALIAS FOR $1;
result RECORD;
BEGIN
RETURN QUERY SELECT '1', '2', '3';
RETURN QUERY SELECT '3', '4', '5';
RETURN QUERY SELECT '3', '4', '5';
END
$$;
```
If you have a record or row variable to return (instead of a query result), use "RETURN NEXT" rather than "RETURN QUERY".
To invoke the function you need to do something like:
```
select * from storeopeninghours_tostring(1) f(a text, b text, c text);
```
So you have to define what you expect the output row schema of the function to be in the query. To avoid that, you can specify output variables in the function definition:
```
CREATE OR REPLACE FUNCTION storeopeninghours_tostring(open_id numeric, a OUT text, b OUT text, c OUT text)
RETURNS SETOF RECORD LANGUAGE 'plpgsql' STABLE STRICT AS $$
BEGIN
RETURN QUERY SELECT '1'::text, '2'::text, '3'::text;
RETURN QUERY SELECT '3'::text, '4'::text, '5'::text;
RETURN QUERY SELECT '3'::text, '4'::text, '5'::text;
END
$$;
```
(not quite sure why the extra ::text casts are required... '1' is a varchar by default maybe?) | All previously existing answers are outdated or were inefficient to begin with.
Assuming you want to return three `integer` columns.
### PL/pgSQL function
Here's how you do it with modern PL/pgSQL (PostgreSQL 8.4 or later):
```
CREATE OR REPLACE FUNCTION f_foo() -- (open_id numeric) -- parameter not used
RETURNS TABLE (a int, b int, c int) AS
$func$
BEGIN
RETURN QUERY VALUES
(1,2,3)
, (3,4,5)
, (3,4,5)
;
END
$func$ LANGUAGE plpgsql IMMUTABLE ROWS 3;
```
In Postgres 9.6 or later you can also add [`PARALLEL SAFE`](https://www.postgresql.org/docs/current/sql-createfunction.html).
Call:
```
SELECT * FROM f_foo();
```
### Major points
* Use [`RETURNS TABLE`](https://www.postgresql.org/docs/current/sql-createfunction.html) to define an ad-hoc row type to return.
Or `RETURNS SETOF mytbl` to use a pre-defined row type.
* Use [`RETURN QUERY`](https://www.postgresql.org/docs/current/plpgsql-control-structures.html#PLPGSQL-STATEMENTS-RETURNING) to return multiple rows with one command.
* Use a [`VALUES`](https://www.postgresql.org/docs/current/sql-values.html) expression to enter multiple rows manually. This is standard SQL and has been around *for ever*.
* **If** you actually need a parameter, use a parameter name `(open_id numeric)` instead of [`ALIAS`, which is discouraged](https://www.postgresql.org/docs/current/plpgsql-declarations.html#PLPGSQL-DECLARATION-ALIAS). In the example the parameter wasn't used and just noise ...
* No need for double-quoting perfectly legal identifiers. Double-quotes are only needed to force otherwise illegal names (mixed-case, illegal characters or reserved words).
* [Function volatility can be `IMMUTABLE`](https://stackoverflow.com/questions/28569415/how-do-immutable-stable-and-volatile-keywords-effect-behaviour-of-function/28573737#28573737), since the result never changes.
* `ROWS 3` is optional, but since we *know* how many rows are returned, we might as well declare it to Postgres. Can help the query planner to pick the best plan.
### Simple SQL
For a simple case like this, you can use a plain SQL statement instead:
```
VALUES (1,2,3), (3,4,5), (3,4,5)
```
Or, if you want (or have) to define specific column names and types:
```
SELECT *
FROM (
VALUES (1::int, 2::int, 3::int)
, (3, 4, 5)
, (3, 4, 5)
) AS t(a, b, c);
```
### SQL function
You can wrap it into a simple [SQL function](https://www.postgresql.org/docs/current/xfunc-sql.html) instead:
```
CREATE OR REPLACE FUNCTION f_foo()
RETURNS TABLE (a int, b int, c int) AS
$func$
VALUES (1, 2, 3)
, (3, 4, 5)
, (3, 4, 5);
$func$ LANGUAGE sql IMMUTABLE ROWS 3;
``` | Return setof record (virtual table) from function | [
"",
"sql",
"postgresql",
"stored-procedures",
"plpgsql",
""
] |
My co-worker is 0 for 2 on questions he has inspired ([1](https://stackoverflow.com/questions/444235/revision-control-locking-is-the-jury-still-out), [2](https://stackoverflow.com/questions/583255/c-code-in-header-files)), so I thought I'd give him a chance to catch up.
Our latest disagreement is over the style issue of where to put "`const`" on declarations.
He is of the opinion that it should go either in front of the type, or after the pointer. The reasoning is that this is what is typically done by everyone else, and other styles are liable to be confusing. Thus a pointer to a constant `int`, and a constant pointer to `int` would be respectively:
```
const int *i;
int * const i;
```
However, I'm confused anyway. I need rules that are consistent and easy to understand, and the only way I can make sense of "`const`" is that it goes *after* the thing it is modifying. There's an exception that allows it to go in front of the final type, but that's an exception, so it's easier on me if I don't use it.
Thus a pointer to a constant `int`, and a constant pointer to `int` would be respectively:
```
int const * i;
int * const i;
```
As an added benefit, doing things this way makes deeper levels of indirection easier to understand. For example, a pointer to a constant pointer to `int` would clearly be:
```
int * const * i;
```
My contention is that if someone just learns it his way, they'll have little trouble figuring out what the above works out to.
The ultimate issue here is that he thinks that putting `const` after `int` is so unspeakably ugly, and so harmful to readability that it should be banned in the style guide. Of course, I think if anything the guide should suggest doing it my way, but either way we shouldn't be *banning* one approach.
**Edit:**
I've gotten a lot of good answers, but none really directly address my last paragraph ("The ultimate issue"). A lot of people argue for consistency, but is that so desirable in this case that it is a good idea to *ban* the other way of doing it, rather that just discouraging it? | The most important thing is **consistency**. If there aren't any coding guidelines for this, then pick one and stick with it. But, if your team already has a de facto standard, don't change it!
That said, I think by far the more common is
```
const int * i;
int * const j;
```
because most people write
```
const int n;
```
instead of
```
int const n;
```
A side note -- an easy way to read pointer `const`ness is to read the declaration starting at the right.
```
const int * i; // pointer to an int that is const
int * const j; // constant pointer to a (non-const) int
int const * aLessPopularWay; // pointer to a const int
``` | There's a class of examples where putting the `const` on the right of the type also helps avoid confusion.
If you have a pointer type in a typedef, then it is not possible to change the constness of the *to* type:
```
typedef int * PINT;
const PINT pi;
```
`pi` still has the type `int * const`, and this is the same no matter where you write the `const`. | const int *p vs. int const *p - Is const after the type acceptable? | [
"",
"c++",
"c",
"pointers",
"coding-style",
"constants",
""
] |
I have a `byte[]` array that is loaded from a file that I happen to known contains [UTF-8](http://en.wikipedia.org/wiki/UTF-8).
In some debugging code, I need to convert it to a string. Is there a one-liner that will do this?
Under the covers it should be just an allocation and a *memcopy*, so even if it is not implemented, it should be possible. | ```
string result = System.Text.Encoding.UTF8.GetString(byteArray);
```
or one of the overload if you know the length:
```
string result = System.Text.Encoding.UTF8.GetString(byteArray, 0, 42);
``` | There're at least four different ways doing this conversion.
1. **Encoding's GetString**
, but you won't be able to get the original bytes back if those bytes have non-ASCII characters.
2. **BitConverter.ToString**
The output is a "-" delimited string, but there's no .NET built-in method to convert the string back to byte array.
3. **Convert.ToBase64String**
You can easily convert the output string back to byte array by using `Convert.FromBase64String`.
Note: The output string could contain '+', '/' and '='. If you want to use the string in a URL, you need to explicitly encode it.
4. **HttpServerUtility.UrlTokenEncode**
You can easily convert the output string back to byte array by using `HttpServerUtility.UrlTokenDecode`. The output string is already URL friendly! The downside is it needs `System.Web` assembly if your project is not a web project.
A full example:
```
byte[] bytes = { 130, 200, 234, 23 }; // A byte array contains non-ASCII (or non-readable) characters
string s1 = Encoding.UTF8.GetString(bytes); // ���
byte[] decBytes1 = Encoding.UTF8.GetBytes(s1); // decBytes1.Length == 10 !!
// decBytes1 not same as bytes
// Using UTF-8 or other Encoding object will get similar results
string s2 = BitConverter.ToString(bytes); // 82-C8-EA-17
String[] tempAry = s2.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
decBytes2[i] = Convert.ToByte(tempAry[i], 16);
// decBytes2 same as bytes
string s3 = Convert.ToBase64String(bytes); // gsjqFw==
byte[] decByte3 = Convert.FromBase64String(s3);
// decByte3 same as bytes
string s4 = HttpServerUtility.UrlTokenEncode(bytes); // gsjqFw2
byte[] decBytes4 = HttpServerUtility.UrlTokenDecode(s4);
// decBytes4 same as bytes
``` | How to convert UTF-8 byte[] to string | [
"",
"c#",
".net",
"arrays",
"string",
"type-conversion",
""
] |
I have a string '2009-06-24 09:52:43.000', which I need to insert to a DateTime column of a table.
But I don't care about the time, just want to insert it as 2009-06-24 00:00:00.000
How can I do that in T-SQL? | For SQL Server 2005 and below:
```
CONVERT(varchar(8), @ParamDate, 112) -- Supported way
CAST(FLOOR(CAST(@ParamDate AS float)) AS DATETIME) -- Unsupported way
```
For SQL Server 2008 and above:
```
CAST(@ParamDate AS DATE)
```
For SQL Server 2022 and above:
```
DATETRUNC(d, @ParamDate)
``` | ```
declare @originalDate datetime
select @originalDate = '2009-06-24 09:52:43.000'
declare @withoutTime datetime
select @withoutTime = dateadd(d, datediff(d, 0, @originalDate), 0)
select @withoutTime
``` | How to convert datetime to date only (with time set to 00:00:00.000) | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
In Django, how can I see the number of current visitors? Or how do I determine the number of active sessions?
Is this a good method?
use django.contrib.sessions.models.Session, set the expiry time short. Every time when somebody does something on the site, update expiry time. Then count the number of sessions that are not expired. | You might want to look into something like [django-tracking](http://code.google.com/p/django-tracking/) for this.
> django-tracking is a simple attempt at
> keeping track of visitors to
> Django-powered Web sites. It also
> offers basic blacklisting
> capabilities.
**Edit**: As for your updated question... [Answer redacted after being corrected by muhuk]
Alternatively, I liked the response to this question: [How do I find out total number of sessions created i.e. number of logged in users?](https://stackoverflow.com/questions/978333/how-do-i-find-out-total-number-of-sessions-created-i-e-number-of-logged-in-users)
You might want to try that instead. | [django-tracking2](https://github.com/bruth/django-tracking2)
can be helpful to track the visitors.
As specially this is easy to configure in the deployment like AWS, because it is not required any dependency and environment variables.
django-tracking2 tracks the length of time visitors and registered users spend on your site. Although this will work for websites, this is more applicable to web *applications* with registered users. This does not replace (nor intend) to replace client-side analytics which is great for understanding aggregate flow of page views. | Number of visitors in Django | [
"",
"python",
"django",
""
] |
I trying to get started with Google Perf Tools to profile some CPU intensive applications. It's a statistical calculation that dumps each step to a file using `ofstream'. I'm not a C++ expert so I'm having troubling finding the bottleneck. My first pass gives results:
```
Total: 857 samples
357 41.7% 41.7% 357 41.7% _write$UNIX2003
134 15.6% 57.3% 134 15.6% _exp$fenv_access_off
109 12.7% 70.0% 276 32.2% scythe::dnorm
103 12.0% 82.0% 103 12.0% _log$fenv_access_off
58 6.8% 88.8% 58 6.8% scythe::const_matrix_forward_iterator::operator*
37 4.3% 93.1% 37 4.3% scythe::matrix_forward_iterator::operator*
15 1.8% 94.9% 47 5.5% std::transform
13 1.5% 96.4% 486 56.7% SliceStep::DoStep
10 1.2% 97.5% 10 1.2% 0x0002726c
5 0.6% 98.1% 5 0.6% 0x000271c7
5 0.6% 98.7% 5 0.6% _write$NOCANCEL$UNIX2003
```
This is surprising, since all the real calculation occurs in SliceStep::DoStep. The "\_write$UNIX2003" (where can I find out what this is?) appears to be coming from writing the output file. Now, what confuses me is that if I comment out all the `outfile << "text"` statements and run pprof, 95% is in `SliceStep::DoStep` and `\_write$UNIX2003' goes away. However my application does not speed up, as measured by total time. The whole thing speeds up less than 1 percent.
What am I missing?
Added:
The pprof output without the `outfile <<` statements is:
```
Total: 790 samples
205 25.9% 25.9% 205 25.9% _exp$fenv_access_off
170 21.5% 47.5% 170 21.5% _log$fenv_access_off
162 20.5% 68.0% 437 55.3% scythe::dnorm
83 10.5% 78.5% 83 10.5% scythe::const_matrix_forward_iterator::operator*
70 8.9% 87.3% 70 8.9% scythe::matrix_forward_iterator::operator*
28 3.5% 90.9% 78 9.9% std::transform
26 3.3% 94.2% 26 3.3% 0x00027262
12 1.5% 95.7% 12 1.5% _write$NOCANCEL$UNIX2003
11 1.4% 97.1% 764 96.7% SliceStep::DoStep
9 1.1% 98.2% 9 1.1% 0x00027253
6 0.8% 99.0% 6 0.8% 0x000274a6
```
This looks like what I'd expect, except I see no visible increase in performance (.1 second on a 10 second calculation). The code is essentially:
```
ofstream outfile("out.txt");
for loop:
SliceStep::DoStep()
outfile << 'result'
outfile.close()
```
Update: I timing using boost::timer, starting where the profiler starts and ending where it ends. I do not use threads or anything fancy. | From my comments:
The numbers you get from your profiler say, that the program should be around 40% faster without the print statements.
The runtime, however, stays nearly the same.
Obviously one of the measurements must be wrong. That means you have to do more and better measurements.
First I suggest starting with another easy tool: the time command. This should get you a rough idea where your time is spend.
If the results are still not conclusive you need a better testcase:
* Use a larger problem
* Do a warmup before measuring. Do some loops and start any measurement afterwards (in the same process).
---
> Tiristan: It's all in user. What I'm doing is pretty simple, I think... Does the fact that the file is open the whole time mean anything?
That means the profiler is wrong.
Printing 100000 lines to the console using python results in something like:
```
for i in xrange(100000):
print i
```
To console:
```
time python print.py
[...]
real 0m2.370s
user 0m0.156s
sys 0m0.232s
```
Versus:
```
time python test.py > /dev/null
real 0m0.133s
user 0m0.116s
sys 0m0.008s
```
**My point is:**
Your internal measurements *and* time show you do not gain anything from disabling output. Google Perf Tools says you should. Who's wrong? | Google perftools collects samples of the call stack, so what you need is to get some visibility into those.
According to the doc, you can display the call graph at statement or address granularity. That should tell you what you need to know. | What exactly does C++ profiling (google cpu perf tools) measure? | [
"",
"c++",
"profiling",
"gperftools",
""
] |
The MSDN documentation for the is keyword says:
```
expression is not null
```
Why? If *MethodThatReturnsNull() is type* were called shouldn't that return false since null certainly isn't that type? | It does return `false` if `expression` is `null`. Perhaps you're misunderstanding the documentation? | The only thing you can say for certain about null is that you don't know what it is. Comparing something to null generally has a result of null ...
Q: Does 1 == "I don't know"?
A: "I dont know"
Check out [this blog post](http://blogs.msdn.com/ericlippert/archive/2009/05/14/null-is-not-empty.aspx) by Eric Lippert. | Why does the is keyword require a non-null expression? | [
"",
"c#",
"language-design",
"keyword",
""
] |
SQL Server 2000 was deployed with English Query. At that time, I was young and new to SQL so I skipped that chapter. Now after years, there is again an idea of making a logical program which can understand simple user questions.
Is there any alternative to that? Where is English Query now? | Though it's not the same thing, Full Text Search is the closest thing to "English Query" that exists in SQL 2005+. | English Query was [discontinued](http://www.infoq.com/news/English-Query-Discontinued) after SQL Server 2000. | What happened with SQL English query? | [
"",
"sql",
"sql-server",
"sql-server-2000",
""
] |
I'm using OpenCV for object detection and one of the operations I would like to be able to perform is a per-pixel square root. I imagine the loop would be something like:
```
IplImage* img_;
...
for (int y = 0; y < img_->height; y++) {
for(int x = 0; x < img_->width; x++) {
// Take pixel square root here
}
}
```
My question is how can I access the pixel value at coordinates (x, y) in an IplImage object? | Assuming img\_ is of type IplImage, and assuming 16 bit unsigned integer data, I would say
```
unsigned short pixel_value = ((unsigned short *)&(img_->imageData[img_->widthStep * y]))[x];
```
See also [here](http://opencv.willowgarage.com/documentation/basic_structures.html#id1) for IplImage definition. | OpenCV IplImage is a one dimensional array. You must create a single index to get at image data. The position of your pixel will be based on the color depth, and number of channels in your image.
```
// width step
int ws = img_->withStep;
// the number of channels (colors)
int nc = img_->nChannels;
// the depth in bytes of the color
int d = img_->depth&0x0000ffff) >> 3;
// assuming the depth is the size of a short
unsigned short * pixel_value = (img_->imageData)+((y*ws)+(x*nc*d));
// this gives you a pointer to the first color in a pixel
//if your are rolling grayscale just dereference the pointer.
```
You can pick a channel (color) by moving over pixel pointer pixel\_value++. I would suggest using a look up table for square roots of pixels if this is going to be any sort of real time application. | OpenCV: Accessing And Taking The Square Root Of Pixels | [
"",
"c++",
"c",
"opencv",
""
] |
Is there a natural language parser for date/times in javascript? | [SugarJS](http://sugarjs.com/) supports some natural language parsing of dates and times.
You can jump to the live example here: <http://sugarjs.com/dates>
For example, it supports the following inputs:
* the day after tomorrow
* 2 weeks from monday
* May 25th of next year
You can then covert the result into different date formats or use the API to further manipulate the date. | I made [Chrono](https://github.com/berryboy/chrono) a small library for parsing dates in JavaScript. I added a date range parsing feature (such as '12 Nov - 13 Dec 2012') . | Is there a natural language parser for date/times in javascript? | [
"",
"javascript",
"datetime",
"nlp",
""
] |
```
Zoom.addEventListener('click', function(){$(document).ready(function(){$("#draggable").draggable({containment: '#imgContainer', scroll: false});});});
```
let me first explain the code. Zoom is a handler/button on clicking which i am enabling the dragging of an image object.
the above code works fine with Chrome but FF is finding errors. Let me quote Firebug:
```
[Exception... "Not enough arguments" nsresult: "0x80570001 (NS_ERROR_XPC_NOT_ENOUGH_ARGS)" location: "JS frame :: http://localhost/slide/script.js :: anonymous :: line 69" data: no]
[Break on this error] Zoom.addEventListener('click', functio... '#imgContainer', scroll: false});});});
```
i am getting it to work fine in Chrome but in Firefox i cannot click the button.
pls help me out... | Check Mozilla documentation at [<https://developer.mozilla.org/en/DOM/element.addEventListener>](https://developer.mozilla.org/en/DOM/element.addEventListener).
You need to add a third parameter to the function call. Just try adding the value false, like this:
```
Zoom.addEventListener('click', function(){$(document).ready(function(){$("#draggable").draggable({containment: '#imgContainer', scroll: false});});},false);
``` | Assuming `Zoom` is a button object you've set somewhere, if I understand what you're trying to do correctly, then what you need is:
```
$(function() {
$(Zoom).click(function() {
$("#draggable").draggable({
containment: '#imgContainer',
scroll: false
});
});
});
```
If `Zoom` is already a jQuery object, then `Zoom.click(...` will be sufficient. | FF javascript woes | [
"",
"javascript",
"jquery",
""
] |
I enjoy and highly recommend [Juval Lowy's](http://www.idesign.net) - [C# Coding Standard](http://www.idesign.net/Downloads/GetDownload/1985). Juval explicitly avoids rationale for each directive in order to keep the standard tight (see the preface). However, there are a few directives for which I find myself curious as to the rationale.
**What is the specific rationale to the following directives from Lowy's C# standard?**
Hopefully there are hard (non-subjective) answers to these.
***1.13 Avoid fully qualified type names. Use the "using" statement instead.***
Is this a performance issue? Sometimes I only need one instance of the fully qualified name and adding a *using* seems heavy.
***1.26 Use empty parenthesis on parameterless-anonymous methods. Omit the parenthesis only if the anonymous method could have been used on any delegate.***
Actually I am just confused by the second sentence. Explanation with example(s) would help, thank you.
***2.19 Avoid defining custom exception classes***
What are the considerations in minimizing their numbers? (He next gives guidelines if you do define them (in 2.20).)
***2.29 Avoid using the ternary conditional operator***
Too hard for the reader to digest, or other considerations?
***2.31 Avoid function calls in Boolean conditional statements. Assign into local variables and check on them.***
I don't think I do this, but I am curious...why not?
***2.47 Avoid interfaces with one member.***
Because it is always/usually more prefereable to do what? One method interfaces work when?
***2.53 Prefer using explicit interface implementation***
Why? Also, [Jon Skeet disagrees here](https://stackoverflow.com/questions/408415/why-explicit-interface-implementation).
Thanks in advance!
Robert | Obviously, I'm not Juval, but I can take a stab at these
**1.13 Avoid fully qualified type names. Use the "using" statement instead.**
Performance can't be the issue here. I'm sure the issue is readability.
**1.26 Use empty parenthesis on parameterless-anonymous methods. Omit the parenthesis only if the anonymous method could have been used on any delegate.**
```
public delegate void Foo1();
public delegate void Foo2(int val);
public void Foo()
{
Foo1 first = delegate { Console.WriteLine("Hello world"); };
Foo2 second = delegate { Console.WriteLine("Hello world"); };
Foo1 third = delegate() { Console.WriteLine("Hello world"); };
Foo2 fourth = delegate() { Console.WriteLine("Hello world"); }; // does not compile
}
```
Without the parens, the anonymous delegate can be applied to any delegate. With the parens, you're being specific about the signature of the delegate. Prefer the second syntax unless you really need the flexibility.
**2.19 Avoid defining custom exception classes**
Again, readability is the issue here. The framework exception classes are rich and well-understood. Be wary when replacing them.
**2.29 Avoid using the ternary conditional operator**
It's a readability and expandability thing. I don't really agree, but it's a standard religious fight.
**2.31 Avoid function calls in Boolean conditional statements. Assign into local variables and check on them.**
Partially this is readability, and partially it's for ease of debugging. I've starting to assign almost everything to temporary variables just so that they're easily found in the debugger later on.
**2.47 Avoid interfaces with one member.**
"Avoid" is kinda like "prefer", he's just saying think twice before you do it. If you only have one member, is the interface really modeling something useful and complete in your design? It's pretty rare to have a class with just one member, think seriously about why your interface is any different.
**2.53 Prefer using explicit interface implementation**
This is similar to the idea of using the least-public accessor you can. If your class doesn't *need* to make the interface public, then it probably shouldn't. This is going to differ significantly based on your design, obviously, but given the fact that most people just make the interface implicit without really thinking about it, it's advice worth considering. | **2.29 Avoid using the ternary conditional operator** I have no problems with "simple" uses of the ternary operator but have recommended against using it in a nested fashion:
```
// This is fine
x := (conditionA) ? true_resultA : false_resultA;
// This would probably be clearer using if-then-elseif
x := (conditionA) ?
((conditionA1) ? true_resultA1 : (condition2) ? true_result2 : false_result2) :
((conditionA2) ? true_resultA2 : false_resultA2);
``` | Juval Lowy's C# Coding Standards Questions | [
"",
"c#",
"coding-style",
""
] |
I want to perform the action at a certain timeout, like fire an
event. I figured out how to do every n number of seconds, but not 1.5
seconds. Here is what I have. Please suggest how to handle my case:
```
void Publish()
{
static int local_time=time(NULL);
int current_time = time (NULL);
if((current_time+PUBLISH_TIMEOUT)>local_time)
{
fireEvent();
local_time=current_time;
}
}
``` | This returns the wall time since the application started in millisecs. It uses the machines clock so it is quite possible that changing the clock's time while the app is running will confuse it. In your case I would add a schedule time to my event object and fire when schedule time <= msec()
```
clock_t msec() {
static struct timeval msec_base;
struct timeval now;
long seconds, useconds;
if (!msec_base.tv_usec)
gettimeofday(&msec_base, NULL);
gettimeofday(&now, NULL);
seconds = now.tv_sec - msec_base.tv_sec;
useconds = now.tv_usec - msec_base.tv_usec;
return ((seconds) * 1000 + useconds/1000.0);
}
``` | `gettimeofday()` returns microseconds so you can use it instead of `time()` - see definition of `struct timeval` this function fills.
Check out `man gettimeofday` for details. | Performing an operation at an interval | [
"",
"c++",
"c",
"unix",
""
] |
I want to subclass `ObservableCollection` to add a property to it. Unfortunately, the `PropertyChanged` event is protected. Basically, I want to subclass it to have a `SelectedItem` that I can bind to for lists in my MVVM WPF app.
Here's the skeleton of my class:
```
public class SelectableList<T> : ObservableCollection<T>
{
public T SelectedItem {get;set;}
}
```
But I cannot do the following:
```
SelectableList<int> intList = new SelectableList<int>();
intList.PropertyChanged += new PropertyChangedEventHandler(intList_Changed);
```
because of access restrictions. This causes me to ask a deeper question. How is the UI notified of `PropertyChanged` events (e.g. Count property)? Note that I cannot do it in a code-behind.
My head is spinning, can someone please enlighten me? | ```
SelectableList<int> intList = new SelectableList<int>();
((INotifyPropertyChanged)intList).PropertyChanged +=
new PropertyChangedEventHandler(intList_Changed);
```
ObservableCollection [implements INotifyPropertyChanged explicitly](http://msdn.microsoft.com/en-us/library/aa288461%28v=vs.71%29.aspx), which means you have to cast the instance to the interface before you can access the interface's methods, properties and events. As to why this is done, I don't know. The [Binding markup extensio](http://msdn.microsoft.com/en-us/library/system.windows.data.binding.aspx)n doesn't "know" ObservableCollections or any other type. It checks types to see if they implement or extend specific interfaces/base classes (INPC, INCC, DependencyObject, etc) and so doesn't care if the interface is implemented explicitly. | ObservableCollection (int .NET 3.5) appears to implement the PropertyChanged event in an [interesting way](http://msdn.microsoft.com/en-us/library/ak9w5846%28v=vs.80%29.aspx).
```
protected event PropertyChangedEventHandler PropertyChanged;
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged;
```
This means that the protected *PropertyChanged* event is likely only meant to be used for internal implementation. The other **INotifyPropertyChanged.PropertyChanged** event is the one that actually fulfills the implementation of the *INotifyPropertyChanged* interface as an [explicit interface](http://msdn.microsoft.com/en-us/library/aa288461%28v=vs.71%29.aspx). Strangely I do not see any place within the ObservableCollection where the *INotifyPropertyChanged.PropertyChanged* is actually raised. This may signal that this was a bug in .NET 3.5 although I haven't tested to confirm whether for example a property changed event is raised for Count when an item is added to a collection but that appears to be how it is supposed to work.
In the .NET 4.0 implementation it appears that the *INotifyPropertyChanged.PropertyChanged* event instead hooks to the same private delegate used by the protected *PropertyChanged* event which may have been a bug fix. It is also possible this is just due to [differences in how auto event implementations are handled in .NET 4.0](http://blogs.msdn.com/b/cburrows/archive/2010/03/18/events-get-a-little-overhaul-in-c-4-part-iii-breaking-changes.aspx).
**Correction:** I have verified that the *INotifyPropertyChanged.PropertyChanged* event is raised by ObservableCollection so the assumptions I made above based on results from using Reflector to look at the ObservableCollection implementation must be inaccurate. My guess is that reflector is doing something strange bug I have no proof of that yet.
So to get your example to work you would need to write for this to work would look like the example below just as Will has demonstrated in his answer.
```
SelectableList<int> intList = new SelectableList<int>();
((INotifyPropertyChanged)intList).PropertyChanged +=
new PropertyChangedEventHandler(intList_Changed);
```
Interesting right? Using explicit interfaces is mainly used to avoid inevitable collisions in members required for a given interface but they can be used to in a sense hide the existence of a member.
If you would like to raise property change events for your own custom properties that you introduce in your subclass look into overriding and/or calling the protected **OnPropertyChanged** method that ObservableCollection also implements. This technique is a well adopted standard and allows subclasses to raise events or handle events without having access to the underlying event delegate. It is generally preferred to use this technique too by the way instead of having a subclass hook event handlers to it's own base classes events. For more examples look at how events in various controls are implemented in WinForms and WPF. | ObservableCollection PropertyChanged event | [
"",
"c#",
"wpf",
"mvvm",
"observablecollection",
"propertychanged",
""
] |
Recently, I was discussing with another programmer the best way to refactor a huge(1000 lines) method full of "if" statements.
The code is written in Java, but I guess this issue could happen in other languages such as C# as well.
To solve this problem, he suggested using a chain-of-responsibility pattern.
He proposed having a base "Handler" class. Then, "Handler1", "Handler2", etc. would extend "Handler".
Then, handlers would have a "getSuccessor" method, which would either return null(if it was the last of the chain) or the next Handler of the chain.
Then, a "handleRequest(Request)" function would either deal with Request, or pass it to the next of the chain and, if none of the previous solutions worked, it would return just null or throw an exception.
To add a new Handler to the chain, the coder would go to the last element of the chain and tell it there was a new element. To do something, he'd just call handleRequest on the first element of the chain.
To solve this problem, I suggested using a different approach.
I'd have a base "Handler" class as well, with "Handler1", "Handler2", just like the previous method mentioned.
However, there would be no "getSuccessor" method. Instead, I'd have a Collection class with a list of handlers(a Vector, an ArrayList, or whatever is best in this case).
The handleRequest function would still exist, but it wouldn't propagate the call to the next handlers. It would just process the request or return null.
To handle a request, one would use
```
for(Handler handle : handlers){
result = handle.handleRequest(request);
if(result!=null) return result;
}
throw new CouldNotParseRequestException(); //just like in the other approach
```
Or, to prevent code duplication, a "parseRequest(request)" method could be added to the collection class.
To add a new handler, one would go to the collection constructor(or static{} block, or something equivaleng) and simply add the code "addHandler(new Handler3());".
Exactly what advantages of chain-of-responsibility am I missing with this approach? Which method is best(assuming there *is* a best method)? Why? What potential bugs and issues can each design method cause?
For those who need context, here is what the original code looked like:
```
if(x instanceof Type1)
{
//doSomething1
} else if(x instanceof Type2)
{
//doSomething2
}
//etc.
``` | I like your idea with collection better than those successors. It makes it easy and clear to manipulate this set of handlers: the collections interface is well known and everybody understands how to iterate over a List or what not.
If you use this successor way suggested by a friend, take care not to fall into a very deep recursion (unless your platform supports tail calls, I don't know if JVMs are capable of that).
I wouldn't recommend adding any methods to the collection. You get much more complicated design that's harder to comprehend and harder to modify. There are two separate concerns: storing a set of handlers and the interpretation of this handlers as a chain of responsibility. A method that handles requests by iterating over a collection is on higher level of abstraction than collection housekeeping methods, therefore shouldn't belong to collection interface. | Which approach is best depends on what your handlers want to do.
If the handlers can completely handle a request request on their own, your approach is fine. The handlers do not have a reference to other handlers, which makes the handler interface simple. Unlike the standard implementation of Chain of Responsibility, you can add or remove handlers from the middle of the chain. In fact, you can choose to build different chains depending on the type of request.
One problem with your approach is that a handler cannot do pre-processing or post-processing on the request. If this functionality is required, then Chain of Responsibility is better. In CoR, the handler is the one responsible for delegating to the next handler on the chain, so the handler can do pre-processing and/or post-processing, including modifying or replacing the response from the next handler on the chain. In this way, CoR is very similar to Decorator; it's just the intent that's different.
Since in CoR, the handler keeps a reference to the next item on the chain, you cannot add or remove items from the middle of the chain. A variation of CoR that allows you to add or remove items from the middle of the chain is a Filter Chain (see, for example, [javax.servlet.FilterChain](http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/FilterChain.html)).
The code example you showed was a bunch of "if" statements that did different behavior based on the type of an object. If that is typical for the code you are cleaning up, you can simply have a map from the request type to the handler required.
Another approach to removing "if" statements is inheritance. If you had some behavior that you needed to do, and there was one variation for a web server, and other variation for a SOAP server, you could have a WebServerRequestHandler and a SoapServerRequestHandler, each extending RequestHandler. The advantage with inheritance is there a clearer place to put logic that is common to both types of request. The disadvantage is that since Java doesn't have multiple inheritance, you can only model single-dimensional problems. | What are the advantages of chain-of-responsibility vs. lists of classes? | [
"",
"java",
"list",
"chain-of-responsibility",
""
] |
I need to use a COM component (a dll) developed in Delphi ages ago. The problem is: the dll does not contain a type library... and every interop feature (eg. TlbImp) in .NET seem to rely on TLBs. The component has been used in Delphi programs here for many years without problems because "It's not much of a problem using COM objects from Delphi, because we know the interfaces" (quote Delphi developer).
Is there any way I can use this DLL from c# without a TLB? I've tried using the DLL as unmanaged, but the only method it exports are `DllUnregisterServer`, `DllRegisterServer`, `DllCanUnloadNow` and `DllGetClassObject`. I know the names of the classes and functions I'm going to use, if that can be of any help.
**UPDATE:**
I've tried implementing Jeff's suggestion, but I'm getting this error:
*"Unable to cast COM object of type 'ComTest.ResSrvDll' to interface type 'ComTest.IResSrvDll'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{75400500-939F-11D4-9E44-0050040CE72C}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E\_NOINTERFACE))."*
This is what I've done:
I got this interface definition from one of the Delphi-guys:
```
unit ResSrvDllIf;
interface
type
IResSrvDll = interface
['{75400500-939F-11D4-9E44-0050040CE72C}']
procedure clearAll;
function ResObjOpen(const aClientID: WideString; const aClientSubID: WideString;
const aResFileName: WideString; aResShared: Integer): Integer; {safecall;}
...
end;
implementation
end.
```
From this I've made this interface
```
using System.Runtime.InteropServices;
namespace ComTest
{
[ComImport]
[Guid("75400500-939F-11D4-9E44-0050040CE72C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IResSrvDll
{
int ResObjOpen(string aClientID, string aClientSubID, string aResFileName, int aResShared);
}
}
```
And this coclass (got the guid from the delphi-guys)
```
using System.Runtime.InteropServices;
namespace ComTest
{
[ComImport]
[Guid("75400503-939F-11D4-9E44-0050040CE72C")]
public class ResSrvDll
{
}
}
```
**UPDATE**
The solution from Jeff is the way to do it. It is worth noticing, though, that the interface definition must match the COM-components *exactly*! ie. same order, same names, etc. | You just need the CLS\_ID and interface id. I wrote about this specific issue on my blog:
"[Using Obscure Windows COM APIs in .NET](http://www.moserware.com/2009/04/using-obscure-windows-com-apis-in-net.html)" | It is quite frequent that you will encounter an interface implementation that is not backed by a type library (Delphi or otherwise). Shell extensions are one example.
You basically need to make a Windows API call to create the instance through the proper COM function calls. The API will take care of managing the DLL via the exported functions you mentioned earlier.
You will need to recreate the interface definition in C# code but after that you simply create the object, cast it to the interface, and it is no different than anything else. The only real caveat here is, depending on your usage, you may have some threading issues to deal with so check the "threading model" that was used for the DLL and consider your usage based on that.
Here is a link to a tutorial on consuming the interfaces that are not TLB based.
[Tutorial](http://www.codeguru.com/csharp/csharp/cs_misc/com/article.php/c9065 "Tutorial") | Using a COM dll from C# without a type library | [
"",
"c#",
"delphi",
"com",
"interop",
""
] |
In JavaScript there's a useful way to test for a variable which has never been defined at any given point. For example, the following snippet of code will return **true** if the variable **bob** has not been defined:
```
typeof(bob)=='undefined'
```
How do I accomplish the same test in Ruby?
edit: I'm looking for a test which is equally compact in nature. I've come up with some awkward approximations using exceptions and such, but those aren't very pretty! | ```
defined?(variable_name)
irb(main):004:0> defined?(foo)
=> nil
irb(main):005:0> foo = 1
=> 1
irb(main):006:0> defined?(foo)
=> "local-variable"
```
Here is a good [write up](http://redhanded.hobix.com/inspect/methodCheckDefined.html) on it. | `defined?` is a function that returns nil if the item is undefined.
```
defined? somevar
=> nil
somevar = 12
defined? somevar
=> "local-variable"
```
So:
```
if defined?(somevar)
do_something
end
``` | Testing for undefined variables in Ruby a la JavaScript? | [
"",
"javascript",
"ruby",
"undefined",
""
] |
What is the technical reason why it is considered bad practice to use the C++ `throw` keyword in a function signature?
```
bool some_func() throw(myExc)
{
...
if (problem_occurred)
{
throw myExc("problem occurred");
}
...
}
``` | No, it is not considered good practice. On the contrary, it is generally considered a bad idea.
<http://www.gotw.ca/publications/mill22.htm> goes into a lot more detail about why, but the problem is partly that the compiler is unable to enforce this, so it has to be checked at runtime, which is usually undesirable. And it is not well supported in any case. (MSVC ignores exception specifications, except throw(), which it interprets as a guarantee that no exception will be thrown. | Jalf already linked to it, but the [GOTW](http://www.gotw.ca/publications/mill22.htm) puts it quite nicely why exception specifications are not as useful as one might hope:
```
int Gunc() throw(); // will throw nothing (?)
int Hunc() throw(A,B); // can only throw A or B (?)
```
> Are the comments correct? Not quite. `Gunc()` may indeed throw something, and `Hunc()` may well throw something other than A or B! The compiler just guarantees to beat them senseless if they do… oh, and to beat your program senseless too, most of the time.
That's just what it comes down to, you probably just will end up with a call to `terminate()` and your program dying a quick but painful death.
The GOTWs conclusion is:
> So here’s what seems to be the best advice we as a community have learned as of today:
>
> * **Moral #1:** Never write an exception specification.
> * **Moral #2:** Except possibly an empty one, but if I were you I’d avoid even that. | Throw keyword in function's signature | [
"",
"c++",
"exception",
""
] |
I am looking for a complete i18n `gettext()` hello world example. I have started a script based upon [A tutorial on Native Language Support using GNU gettext](https://web.archive.org/web/20130330233819/http://oriya.sarovar.org/docs/gettext_single.html) by G. Mohanty. I am using Linux and G++.
Code:
```
cat >hellogt.cxx <<EOF
// hellogt.cxx
#include <libintl.h>
#include <locale.h>
#include <iostream>
#include <cstdlib>
int main (){
char* cwd = getenv("PWD");
std::cout << "getenv(PWD): " << (cwd?cwd:"NULL") << std::endl;
char* l = getenv("LANG");
std::cout << "getenv(LANG): " << (l?l:"NULL") << std::endl;
char* s = setlocale(LC_ALL, "");
std::cout << "setlocale(): " << (s?s:"NULL") << std::endl;
std::cout << "bindtextdomain(): " << bindtextdomain("hellogt", cwd) << std::endl;
std::cout << "textdomain(): " << textdomain( "hellogt") << std::endl;
std::cout << gettext("hello, world!") << std::endl;
}
EOF
g++ -ohellogt hellogt.cxx
xgettext -d hellogt -o hellogt.pot hellogt.cxx
msginit --no-translator -l es_MX -o hellogt_spanish.po -i hellogt.pot
sed --in-place hellogt_spanish.po --expression='/#: /,$ s/""/"hola mundo"/'
sed --in-place hellogt_spanish.po --expression='s/PACKAGE VERSION/hellogt 1.0/'
mkdir -p ./es_MX/LC_MESSAGES
msgfmt -c -v -o ./es_MX/LC_MESSAGES/hellogt.mo hellogt_spanish.po
export LANG=es_MX
ls -l $PWD/es_MX/LC_MESSAGES/hellogt.mo
./hellogt
strace -e trace=open ./hellogt
```
The program compiles, the text is extracted, Spanish file is created, modified and binary created but hellogt still displays English. The trace shows no evidence of looking in the current working directory for es\_MX nor any references to LC\_MESSAGES directory. | ```
cat >hellogt.cxx <<EOF
// hellogt.cxx
#include <libintl.h>
#include <locale.h>
#include <iostream>
int main (){
setlocale(LC_ALL, "");
bindtextdomain("hellogt", ".");
textdomain( "hellogt");
std::cout << gettext("hello, world!") << std::endl;
}
EOF
g++ -o hellogt hellogt.cxx
xgettext --package-name hellogt --package-version 1.2 --default-domain hellogt --output hellogt.pot hellogt.cxx
msginit --no-translator --locale es_MX --output-file hellogt_spanish.po --input hellogt.pot
sed --in-place hellogt_spanish.po --expression='/"hello, world!"/,/#: / s/""/"hola mundo"/'
mkdir --parents ./es_MX.utf8/LC_MESSAGES
msgfmt --check --verbose --output-file ./es_MX.utf8/LC_MESSAGES/hellogt.mo hellogt_spanish.po
LANGUAGE=es_MX.utf8 ./hellogt
```
Here is a description of the files created by the above:
```
hellogt.cxx C++ source file
hellogt Executable image
hellogt.pot Extracted text from C++ source file (portable object template)
hellogt_spanish.po Modified text for Spanish with translations added (using sed)
es_MX.utf8/
LC_MESSAGES/
hellogt.mo Binary translated text for Spanish used at run-time
``` | Your problem is that `hellogt.mo` is in the wrong location - your program isn't actually opening it. You can tell this by using `strace` to trace `open` syscalls:
```
strace -e trace=open ./hellogt
...
open("/tmp/.//es_MX/LC_MESSAGES/hellogt.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/tmp/.//es/LC_MESSAGES/hellogt.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
```
You can affect where gettext looks for message catalogs with the `LOCPATH` environment variable, but if you move it to where gettext is attempting to load it from your example works:
```
mkdir -p es/LC_MESSAGES
cp hellogt.mo es/LC_MESSAGES
./hellogt
hola mundo
``` | Complete C++ i18n gettext() "hello world" example | [
"",
"c++",
"linux",
"internationalization",
"gettext",
""
] |
For example the [C++11 interfaces](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2320.html)
I am having a hard time figuring out when to use which of these things (cv, mutex and lock).
Can anyone please explain or point to a resource?
Thanks in advance. | On the page you refer to, "mutex" is the actual low-level synchronizing primitive. You can take a mutex and then release it, and only one thread can take it at any single time (hence it is a synchronizing primitive). A recursive mutex is one which can be taken by the *same* thread multiple times, and then it needs to be released as many times by the same thread before others can take it.
A "lock" here is just a C++ wrapper class that takes a mutex in its constructor and releases it at the destructor. It is useful for establishing synchronizing for C++ scopes.
A condition variable is a more advanced / high-level form of synchronizing primitive which combines a lock with a "signaling" mechanism. It is used when threads need to wait for a resource to become available. A thread can "wait" on a CV and then the resource producer can "signal" the variable, in which case the threads who wait for the CV get notified and can continue execution. A mutex is combined with CV to avoid the race condition where a thread starts to wait on a CV at the same time another thread wants to signal it; then it is not controllable whether the signal is delivered or gets lost. | This question has been answered. I just add this that may help to decide WHEN to use these synchronization primitives.
Simply, the mutex is used to guarantee mutual access to a shared resource in the critical section of multiple threads. The luck is a general term but a binary mutex can be used as a lock. In modern C++ we use lock\_guard and similar objects to utilize RAII to simplify and make safe the mutex usage. The conditional variable is another primitive that often combined with a mutex to make something know as a [monitor](https://en.wikipedia.org/wiki/Monitor_(synchronization)).
> I am having a hard time figuring out when to use which of these things
> (cv, mutex and lock). Can anyone please explain or point to a
> resource?
Use a mutex to guarantee mutual exclusive access to something. It's the default solution for a broad range of concurrency problems. Use lock\_guard if you have a scope in C++ that you want to guard it with a mutex. The mutex is handled by the lock\_guard. You just create a lock\_guard in the scope and initialize it with a mutex and then C++ does the rest for you. The mutex is released when the scope is removed from the stack, for any reason including throwing an exception or returning from a function. It's the idea behind [RAII](https://en.cppreference.com/w/cpp/language/raii) and the lock\_guard is another resource handler.
There are some concurrency issues that are not easily solvable by only using a mutex or a simple solution can lead to complexity or inefficiency. For example, the [produced-consumer problem](https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem) is one of them. If we want to implement a consumer thread reading items from a buffer shared with a producer, we should protect the buffer with a mutex but, without using a conditional variable we should lock the mutex, check the buffer and read an item if it's not empty, unlock it and wait for some time period, lock it again and go on. It's a waste of time if the buffer is often empty (busy waiting) and also there will be lots of locking and unlocking and sleeps.
The solution we need for the producer-consumer problem must be simpler and more efficient. A monitor (a mutex + a conditional variable) helps us here. We still need a mutex to guarantee mutual exclusive access but a conditional variable lets us sleep and wait for a certain condition. The condition here is the producer adding an item to the buffer. The producer thread notifies the consumer thread that there is and item in the buffer and the consumer wakes up and gets the item. Simply, the producer locks the mutex, puts something in the buffer, notifies the consumer. The consumer locks the mutex, sleeps while waiting for a condition, wake s up when there is something in the buffer and gets the item from the buffer. It's a simpler and more efficient solution.
The next time you face a concurrency problem think this way: If you need mutual exclusive access to something, use a mutex. Use lock\_guard if you want to be safer and simpler. If the problem has a clue of waiting for a condition that must happen in another thread, you MIGHT need a conditional variable.
As a general rule of thumb, first, analyze your problem and try to find a famous concurrency problem similar to yours (for example, see classic problems of synchronization section in [this page](https://en.wikipedia.org/wiki/Synchronization_(computer_science))). Read about the solutions proposed for the well-known solution to peak the best one. You may need some customization. | Differences between Conditional variables, Mutexes and Locks | [
"",
"c++",
"multithreading",
"c++11",
"mutex",
"condition-variable",
""
] |
I am writing an application that sends command line commands to a 3rd party application.
So I have a list of commands like:
```
"process images"
"apply effect blur"
"save as png"
...
```
I don't know how to best organize them in OOP style.
Right now I have:
```
switch ( e.KeyCode )
{
case Keys.A:
SendCommand ( "process images" );
break;
case Keys.B:
SendCommand ( "apply effect blur" );
break;
case Keys.C:
SendCommand ( "save as png" );
break;
...
}
```
I want to be able to do this in a clean way. Maybe like:
`SendCommand (Commands.ApplyBlur)`, etc.
But I don't know which way is the best. I thought of storing these in a collection but thought it wouldn't be clear or reasonable. | I suggest to use a dictionary to map between the input and the command. The simplest solution is to map directly between keys and the command text.
```
Dictionary<ConsoleKey, String> map = new Dictionary<ConsoleKey, String>()
{
{ ConsoleKey.A, "process image" },
{ ConsoleKey.B, "apply blur effect" },
{ ConsoleKey.C, "save as png" }
};
ConsoleKey key = Console.ReadKey().Key;
String command;
if (map.TryGetValue(key, out command))
{
SendCommand(command);
}
else
{
HandleInvalidInput();
}
```
Depending on your actual needs it might be a cleaner solution to perform a two step mapping - from input key to an enum value, and from the enum value to the command text. You should also think about creating a command class and providing static instances for your commands.
```
public class Command
{
public Command(String commandText)
{
this.CommandText = commandText;
}
public String CommandText { get; private set; }
public void Send()
{
// Dummy implementation.
Console.WriteLine(this.CommandText);
}
// Static command instances.
public static readonly Command ProcessImage = new Command("process image");
public static readonly Command BlurImage = new Command("apply blur effect");
public static readonly Command SaveImagePng = new Command("save as png");
}
```
With this class the code to send the commands would be something like the following.
```
Dictionary<ConsoleKey, Command> map = new Dictionary<ConsoleKey, Command>()
{
{ ConsoleKey.A, Command.ProcessImage },
{ ConsoleKey.B, Command.BlurImage},
{ ConsoleKey.C, Command.SaveImagePng }
};
ConsoleKey key = Console.ReadKey().Key;
Command command;
if (map.TryGetValue(key, out command))
{
command.Send();
}
else
{
HandleInvalidInput();
}
``` | I'm just starting to understand Design Patterns, but this seems to be perfect for the [Command Pattern](http://en.wikipedia.org/wiki/Command_pattern). | How can I organize collections of strings in OOP? | [
"",
"c#",
".net",
""
] |
I've painfully learned during last few days a lot about programming in c++.
I love it :)
I know I should release memory - the golden "each malloc=free" or "each new=delete" rules exist now in my world, but I'm using them to rather simple objects.
What about vector ? Wherever I can, I'm using vector.clear() but that clearly isn't enough, because I'm having huge memory leaks.
Could you guide me on how should I treat this thing?
\*Edit
Thanks, your comments made me think about the alghorithm of this application and I'll be able to eliminate the vector totally. :O
Sorry - I started explaining what is my use case here and I found out what I really need. It's like that when you code last 3 days for 18 hours a day :|
\*Edit 2
This is crazy. By small changes in code, I've eliminated memory usage from 2x130 mb (constantly growing) into 2x 13,5mb, constant size. Thanks for making me think about that in another way.
Btw. such self code review got a name - anyone remember that? It's when you ask anyone (even your mother or dog) and start explaining what's your problem - and suddenly you solve this 5 hour problem yourself, just by trying to look at it from other point of view, or just by trying to summarize what's it all about. I often find myself being catched on that... | The rule is that when you clear a vector of objects, the destructor of each element will be called. On the other hand, if you have a vector of pointers, `vector::clear()` will not call `delete` on them, and you have to delete them yourself.
So if all you have is a vector of strings, and not pointers to strings, then your memory leaks must be caused by something else. | You don't need to be doing this. std::string cleans itself up, so the strings are not your problem. Remember that YOU didn't use `new` so YOU don't have to use `delete`.
You should probably learn about [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) - it makes allocation and deallocation much simpler. You'll avoid memory leaks this way. | Should I delete vector<string>? | [
"",
"c++",
"memory-management",
""
] |
I am using pixels as the unit for my font. In one place, I am performing a hit test to check if the user has clicked within the bounding rectangle of some text on screen. I need to use something like `MeasureString` for this. Unfortunately, the code doing the hit test is deep within a library which does not have access to a `Graphics` object or even a `Control`.
How do I get the bounding box of a string given the font without using the `Graphics` class? Why do I even need a `Graphics` object when my font is in pixels? | If you have a reference to System.Windows.Forms, try using the TextRenderer class. There is a static method (MeasureText) which takes the string and font and returns the size. [MSDN Link](http://msdn.microsoft.com/en-us/library/system.windows.forms.textrenderer.aspx) | You don't need to use the graphics object that you are using to render to do the measuring. You could create a static utility class:
```
public static class GraphicsHelper
{
public static SizeF MeasureString(string s, Font font)
{
SizeF result;
using (var g = Graphics.FromHwnd(IntPtr.Zero))
{
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
result = g.MeasureString(s, font, int.MaxValue, StringFormat.GenericTypographic);
}
return result;
}
}
```
It might be worthwhile, depending on your situation to set the dpi of the bitmap as well. | Measure a String without using a Graphics object? | [
"",
"c#",
"text",
"fonts",
"gdi+",
""
] |
I'm looking for a Python framework that will enable me to play video as well as draw on that video (for labeling purposes).
I've tried Pyglet, but this doesn't seem to work particularly well - when drawing on an existing video, there is flicker (even with double buffering and all of that good stuff), and there doesn't seem to be a way to get the frame index in the video during the per-frame callback (only elapsed time since the last frame). | Try a Python wrapper for OpenCV such as [ctypes-opencv](http://code.google.com/p/ctypes-opencv/). The C API reference is [here](http://code.google.com/p/ctypes-opencv/), and the wrapper is very close (see docstrings for any changes).
I have used it to draw on video without any flicker, so you should have no problems with that.
A rough outline of calls you need:
* Load video with cvCreateFileCapture, load font with cvFont.
* Grab frame with cvQueryFrame, increment your frame counter.
* Draw on the frame with cvPutText, cvEllipse, etc etc.
* Display to user with cvShowImage. | Qt (PyQt) has Phonon, which might help out. PyQt is available as GPL or payware. (Qt has LGPL too, but the PyQt wrappers don't) | Python Video Framework | [
"",
"python",
"video",
"pyglet",
""
] |
I want to run unit tests (Junit) on some model classes that typically will send emails confirming that things happened. Is there a mock email server that you can use with unit tests that will let you confirmation that your run tried to send an email without actually sending the emails out?
This seems like it would be a nice to have, just not sure I want to write my own. The app stack for the emailing aspect is Velocity+Spring, so it would be preferable if the test server can be pointed at by simply changing the applicationContext.xml file. | [Dumbster](https://github.com/rjo1970/dumbster) is a fake SMTP server designed for testing against. It's written in Java. | I think the [Mock JavaMail](https://github.com/kohsuke/mock-javamail) project is what you want. | Running Junit Email Tests Without Emails Actually Going Out | [
"",
"java",
"unit-testing",
"email",
"junit",
""
] |
I apologize if this question is listed elsewhere and I just didn't find it in my search. I am trying to find a way to set the DefaultFont property of a form so that users can select the font they want and it will be auto set every time the form opens. I already have the code to save to the user settings, I'm just looking for a way to set the Default Font property. I'm using Visual Studio 2005 with C#. Please let me know if there isn't enough info in here. Thanks! | Basically, it is
```
private void Form1_Load(object sender, EventArgs e)
{
this.Font = font_from_settings;
}
```
But it will be a little tricky to make sure no control is overriding it's own font property. You can use the designer to reset font-properties or delete them from \*.Designer.cs | I think you have to enumerate the controls collection and set the font for each control on the form individually.
But as Henk points out, if your controls have no font settings in the designer, they will inherit the font settings for the form. | Setting default fonts in C# | [
"",
"c#",
".net",
""
] |
Which of these 2 methods is better and why?
Method 1:
```
void fun(int i) {
//do stuff
}
...
for_each(a.begin(), a.end(), fun);
```
Method 2:
```
class functor {
public:
void operator()(int i);
};
...
for_each(a.begin(), a.end(), functor());
```
Edit: Should have formulated it this way, in what situation is one of the above method preferable to the other?
Thanks a lot! | Functors may (and **will**) be trivially inlined – this isn't done for regular function pointers.
Thus, functors have a real performance benefit which may be huge in tight loops. Furthermore, functors are generally more easily composable and in particuler play nicer with the STL: `std::bind`*`x`* doesn't work on function pointers, for instance.
I hate how they clutter the code but given all the advantages, I'd prefer them over function pointers any time. | To clear up a misconception of what a compiler can inline, a good enough compiler can inline function pointers. It can just inline function objects more easily since there is more static information available. E.g., a pointer to a function that takes no parameters and returns a bool is of type bool (\*)(), while a functor has an explicit type, namely, the functor, and the template instantiation can statically call the functor operator, rather than having to call through a function pointer.
In practice, though, it's mainly a matter of giving the compiler enough information to optimize effectively.
For example, Visual C++ 2008, given the following code with full optimizations:
```
#include "stdafx.h"
#include <algorithm>
const char print_me[]= "hello!";
class print_functor
{
public:
void operator()(char c)
{
printf("%c", c);
}
};
void print_function(char c)
{
printf("%c", c);
}
int _tmain(int argc, _TCHAR* argv[])
{
std::for_each(print_me, print_me + sizeof(print_me)/sizeof(print_me[0]), print_functor());
printf("\n");
std::for_each(print_me, print_me + sizeof(print_me)/sizeof(print_me[0]), print_function);
return 0;
}
```
inlines both `std::for_each` calls completely. Incidentally, on the PC, the first for\_each has an unnecessary `lea ecx, [ecx]`. | Using STL algorithms, is it better to pass a function pointer or a functor? | [
"",
"c++",
"stl",
"functor",
""
] |
first post, so play nice!
I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:
```
mass = 1.0
volume = 0.5
mydict = {'mass':mass,'volume':volume}
mydict['density'] = mydict['mass']/mydict['volume']
```
So in this case, mydict['density'] just returns 2.0. If I change mydict['mass'] = 2.0, the density will not be updated. Fine - I can kind of understand why - the density is defined by the values when they were passed to the declaration. So I thought maybe I could approach this with a lambda expression, eg (apologies for the horrid code!):
```
mydict['density_calc'] = lambda x,y: x/y
mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume'])
```
But again, this only returns the original density, despite changing mydict['mass']. As a final attempt, I tried this:
```
def density(mass,volume): return mass/volume
mydict['density_calc'] = lambda x,y: density(x,y)
mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume'])
```
Again, no dice. This seems like a really simple problem to solve, so apologies in advance, but if anyone could help me out, I'd be very appreciative!
Cheers,
Dave | Here's a quick hack on how to subclass `dict` to meet your specs, but probably not to meet Python's specs for a dictionary:
```
class MyDict(dict):
def __getitem__(self, key):
if key == 'density':
return self['mass'] / self['volume']
else:
return dict.__getitem__(self,key)
def keys(self):
return ['density'] + dict.keys(self)
x = MyDict()
x['mass'] = 1.0
x['volume'] = 0.5
print x
print x.keys()
print x['density']
x['mass'] = 2.0
print x['density']
```
which prints
```
{'volume': 0.5, 'mass': 1.0}
['density', 'volume', 'mass']
2.0
4.0
```
But that doesn't account for dict.iterkeys(), among other things. | Seems like an abuse of a dictionary structure. Why not create a simple class?
```
class Entity(object):
def __init__(self, mass, volume):
self.mass = mass
self.volume = volume
def _density(self):
return self.mass / self.volume
density = property(_density)
``` | Python: linking/binding variables together in a dictionary | [
"",
"python",
"variables",
"dictionary",
""
] |
I am working on a website design, and I need a way to fade in the background image of the body tag when it is completely done loading (perhaps then a pause of 500 ms).
If you see [August](http://www.august.com.au/)'s website design you will see the background fades in; however, this is done with a Flash background. Is there any way to do this with jQuery or JavaScript?
---
**Update 9/19/2010:**
So for those that are coming from Google (this is currently the number one result for "fade in background on load", I just thought I'd make a more clear implementation example for everyone.
Add a `<div id="backgroundfade"></div>` to your code somewhere in the footer (you can also append this via JavaScript if you don't want your DOM getting cluttered.
Style as such -
```
#backgroundfade {
position: fixed;
background: #FFF /* whatever color your background is */
width: 100%;
height: 100%;
z-index: -2;
}
```
Then add this to your JavaScript scripting file (jQuery required):
```
$(document).ready(function() {
$('#backgroundfade').fadeOut(1000);
});
```
This has the effect of fading the `#backgroundfade` element (the box "covering" your actual background) out in 1 second upon DOM completion. | I haven't done this myself, but it might work.
You could, I guess, setup the background image and then mask it with a big old div that has a black background. Then play with opacity of this div to create the fade effect. This black div would have to cover the entire body. | Yep:
Don't give the body a background image. Then prepare an animated GIF with the fading effect. In Javascript:
```
document.onload = function () {
window.setTimeout (function () {
document.getElementsByTagName ("body")[0].style.backgroundImage = "url(/path/to/image.gif)";
}, 500);
};
```
In jQuery it would be
```
$(function () {
$('body').css ('backgroundImage', 'url(/path/...)');
});
```
If you don't want to do the animated GIF trick, but need support for JPEG or PNG, it get's nasty. You'll have to create a placeholder `<div/>`, position it to the right place and play with opacity. You also have to detect when the background image has loaded, so that you don't get silly jumps on slow connections. A non-working example:
```
var x = new Image();
x.onload = function () {
/*
create div here and set it's background image to
the same value as 'src' in the next line.
Then, set div.style.opacity = 0; (best, when the
div is created) and let it fade in (with jQuery
or window.setInterval).
*/ };
x.src = "/path/to/img.jpg";
```
Cheers, | A way to fade in the background on load? | [
"",
"javascript",
"jquery",
"background",
""
] |
> **Possible Duplicate:**
> [.NET How to check if path is a file and not a directory?](https://stackoverflow.com/questions/439447/net-how-to-check-if-path-is-a-file-and-not-a-directory)
Can anyone think of a good way of telling whether a file system object path equates to a a file or a directory?
I did have the following method:
```
public static bool PathIsFile(this string fullPath)
{
return (Path.GetExtension(fullPath).Length > 0);
}
```
But some files have no extension and some directories have a dot in their name so this is not cutting it. | There's no way of knowing just from a string analysis that something is a file or a directory, since, as you noted,
```
C:\WINDOWS\WhoKnowsWhatThisIs
```
might be either a directory or a file.
You'll have to call something like `System.IO.Directory.Exists()` or `System.IO.File.GetAttributes()` to test. | Have you checked out:
```
System.IO.Directory.Exists(path);
```
and
```
System.IO.File.Exists(path);
```
These return boolean, but I can't find out (at the moment) what errors they raise if given a file or directory respectively.
There's also the `System.IO.FileInfo` and `System.IO.DirectoryInfo` classes which should help you here. | How to tell whether a file system object is a path or a directory | [
"",
"c#",
".net",
"file",
"directory",
""
] |
OK, i have confirmed i only this issue when i attempt to query on the primary key if that primary key in the entity is set to 'Auto Generated Value' -- but w/o this, how can i insert? Sorry if this is a noob linq2sql but i just started working with it.
How does one go about using Linq to Sql with this option turned off but also have the db handle the pk's? I would hate to have to qry everytime to get the pk i should assign...
I hope someone can help me out, im completely unable to use linq to sql in one of my projects, not really sure what to do... here is an example, this line throws a StackOverflow exception.
```
MyDataContext dc = new MyDataContext(ConnStr);
var obj = dc.MyDataTable.AsQueryable().SingleOrDefault(a => a.pkID == 4);
```
-- That second line throws the StackOverflow exception.
Heres another example using the same datacontext
```
var o = dc.MyDataTable.Take(1); <-- works fine
var abc = o.ToArray(); <-- unable to evaluate, debugger stops
```
Any ideas what i can try? I seem to be fine using linq to sql in another project in the same solution.
-- UPDATE--
I forgot to mention that this particular entity 'MyDataTable' has the pk set as 'Auto Generated Value' -- i have it set to this cause i have sql doing auto increment and this is the identity column. | How is pkID implemented? Any chance it's recursive in some way? | The `Take(1)` working doesn't surprise me, as this doesn't really execute anything (it is deferred until the data is iterated).
That is an interesting problem - not least because the `SingleOrDefault(x=>x.ID == id)` actually has [different processing](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362313) internally - it recognises this as a primary-key lookup and checks the identity manager **first**.
***EDIT*** As an off-the-wall thing, try `.Where(x=>x.ID == id).SingleOrDefault()` - as per the bug (previous link), this doesn't use the identity lookup trick until 4.0 ships.
I would be start by wondering:
* is there anything odd in the ID getter/setter (have you added code?)
+ have you done *anything* in a partial class for this type?
* is it part of an inheritance chain?
+ and if so, have you monkeyed with a partial class for the parent type?
* do you get anything in the call-stack window when it explodes? | linq to sql + stackoverflow exception when querying objects | [
"",
"c#",
".net",
"linq",
"linq-to-sql",
"stack-overflow",
""
] |
I have web.config with the given value:
```
<appSettings>
<add key="vDirectory" value="fr" />
<add key="BookingSummaryPage" value="/pli/forms/BookingSummary.aspx" />
</appSettings>
```
Now I want to read the value of "vDirectory" through java script.
I am using below code:
```
<script language="javascript" type="text/javascript">
function test()
{
var t='<%=ConfigurationManager.AppSettings("vDirectory").ToString() %>'
alert(t);
}
</script>
<input type="button" value="Click Me" onclick="test();" />
```
The error generated is:
```
Error 'System.Configuration.ConfigurationManager.AppSettings' is a 'property' but is used like a 'method'
``` | Edit: this doesn't answer your first issue, but still applies after you fix that. If vDirectory was something like "c:\new folder" you'd end up with a newline in `t`.
I'm not sure what language you're using but you want to run the string though addslashes() (or the equivalent in your language) before you print it out like that:
```
var t='<%=addslashes(ConfigurationManager.AppSettings("vDirectory").ToString()) %>';
```
Or even better, JSON encode it if there's a function for that:
```
// Note no quotes as json_encode will add them
var t=<%=json_encode(ConfigurationManager.AppSettings("vDirectory").ToString()) %>;
``` | Try this:
ConfigurationManager.AppSettings["vDirectory"].ToString()
Please note that square brackets are used instead of normal brackets. | Reading web.config value through javascript | [
"",
"javascript",
""
] |
I have a windows form that executes a batch file. I want to transfer everything that happends in my console to a panel in my form. How can I do this? How can my DOS console comunicate with my windows form panel???
Thanks | You can call the DOS or batch program from your Form application and redirect the output to a string:
```
using (var p = new System.Diagnostics.Process( ))
{
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = PathToBatchFile;
p.StartInfo.Arguments = args;
p.Start( );
string o = p.StandardOutput.ReadToEnd( );
p.WaitForExit( );
}
``` | [The doc states](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandarderror.aspx) that if you want to read both StandardError and StandardOutput, you need to read *at least one of them* asynchronously in order to avoid deadlocks.
Also, if you call ReadToEnd on one of the redirected streams, you must do so *before* calling WaitForExit(). If you WaitForExit before ReadToEnd, the output buffer can fill up, suspending the process, which means it will never exit. That would be a very long wait. This is also in the doc!
example:
```
string output;
string error;
System.Diagnostics.Process p = new System.Diagnostics.Process
{
StartInfo =
{
FileName = program,
Arguments = args,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
UseShellExecute = false,
}
};
if (waitForExit)
{
StringBuilder sb = new StringBuilder();
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
Action<Object,DataReceivedEventArgs> stdErrorRead = (o,e) =>
{
if (!String.IsNullOrEmpty(e.Data))
sb.Append(e.Data);
};
p.ErrorDataReceived += stdErrorRead;
p.Start();
// begin reading stderr asynchronously
p.BeginErrorReadLine();
// read stdout synchronously
output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
// return code is in p.ExitCode
if (sb.Length > 0)
error= sb.ToString();
}
``` | C# Windows Form .Net and DOS Console | [
"",
"c#",
".net",
""
] |
I have a float variable and would like to get only the part after the comma, so if I have 3.14. I would like to get 14 as an integer. How can I do that? | The cheating way to do it is:
```
private Int32 FractionalPart(double n)
{
string s = n.ToString("#.#########", System.Globalization.CultureInfo.InvariantCulture);
return Int32.Parse(s.Substring(s.IndexOf(".") + 1));
}
```
edit2: OK OK OK OK. Here is the most paranoid never fail version I can come up with. This will return the first 9 digits (or less, if there aren't that many) of the decimal portion of the floating point number. This is guaranteed to not overflow an Int32. We use the invariant culture so we know that we can use a period as the decimal separator. | You can subtract the integer portion from the value itself to retrieve the fractional part.
```
float x = 3.14
float fractionalPortion = x - Math.Truncate(x);
```
You can then multiply it to get the fractional part represented as an integer at whatever precision you'd like.
Mapping the fractional portion to an integer has some challenges - many floating point numbers cannot be represented as a base-10 integer, and thus may require more digits to represent than an integer can support.
Also, what of the case of numbers like 3.1 and 3.01? Mapping directly to an integer would both result in 1. | C# get digits from float variable | [
"",
"c#",
".net",
"floating-point",
""
] |
Can anyone help, I have a popup that is being blocked. It is a popup that is created because somebody has clicked on a Print picture on my site.
I thought IE is not supposed to block these when the popup came via an `onclick`?
Can anyone help? The `child1` variable is always returned as `NULL` if popup blocker enabled...
Maybe the problem is that the `onclick` event then passes control to a new function which loads a html file and does `child.document.write`
Here is my simple code..
```
var width = 800;
var height = 600;
var left = parseInt((screen.availWidth / 2) - (width / 2));
var top = parseInt((screen.availHeight / 2) - (height / 2));
var windowFeatures = "width=" + width + ",height=" + height
+ ",menubar=yes,toolbar=yes,scrollbars=yes,resizable=yes,left="
+ left + ",top=" + top + "screenX=" + left + ",screenY=" + top;
child1 = window.open("about:blank", "subWind", windowFeatures);
``` | The problem will be that open will only return a reference to the window if you are navigating to somewhere within your current host. You are navigating to about:blank which is not within your host.
Try adding a blank.htm file to your site and open that instead. I'm still not sure that document.write will be allowed the document won't be open for write, you may be able to manipulate the DOM of the existing blank document though. | The Internet Explorer pop-up blocker, when set to `Medium` filter level, will not block windows opened by JavaScript if they have been initiated by a user action. The following works fine in IE 6, 7 and 8:
```
<script type="text/javascript">
function openWin() {
var width = 800;
var height = 600;
var left = Math.floor((screen.availWidth - width) / 2);
var top = Math.floor((screen.availHeight - height) / 2);
var windowFeatures = "width=" + width + ",height=" + height +
",menubar=yes,toolbar=yes,scrollbars=yes,resizable=yes," +
"left=" + left + ",top=" + top +
"screenX=" + left + ",screenY=" + top;
child1 = window.open("about:blank", "subWind", windowFeatures);
writeTo(child1);
}
function writeTo(w) {
w.document.write('Test');
}
</script>
<a href="#" onclick="openWin();return false;">Test</a>
```
Note that using `document.write` into the newly opened window does not work in some web browsers. Also note that this may trigger a pop-up blocker in other browsers, even if it works as shown in Internet Explorer.
I have seen where invoking JavaScript from an `onclick` event can, in some cases, cause the pop-up blocker to trigger. It seems to have something to do with how *far* `window.open()` is from the onclick event. Too many levels of functions calling functions before you call `window.open()`. Without seeing your exact implementation, I can't tell you whether this is the problem you are having or not. | Javascript window.open is blocked by IE popup blocker | [
"",
"javascript",
"popup",
""
] |
Try to write:
```
List<Object> list;
@SuppressWarnings("unchecked")
list = (List<Object>) new Object();
```
It will fail on the 3rd line, on the word `list`, with the following:
```
list cannot be resolved to a type
```
I understand that it is related to how annotations work. Anybody knows the reasoning behind this?
**EDIT:** thanks for the fast answer. I knew it'd work if the assignment was made also a declaration, anyway. | You must put the annotation on the declaration, not just the assignment. This compiles:
```
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) new Object();
```
See the Javadocs for [`SuppressWarnings`](http://java.sun.com/javase/6/docs/api/java/lang/SuppressWarnings.html), which lists its targets as
```
@Target(value={TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE})
```
And if you look up [`LOCAL_VARIABLE`](http://java.sun.com/javase/6/docs/api/java/lang/annotation/ElementType.html#LOCAL_VARIABLE), it says:
> Local variable declaration
(There is no target for arbitrary statements, so no annotation could possibly go there and still allow it to compile.) | From Sun's [Annotation Tutorial](http://72.5.124.55/docs/books/tutorial/java/javaOO/annotations.html):
> Annotations can be applied to a program's declarations of classes, fields, methods, and other program elements.
The end phrase "and other program elements" is disappointingly vague, but according to [The Java Programming Language - Annotations](http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html):
> Once an annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants.
which makes it clear that Annotations can only be applied to declarations. | Strange Java error with annotations | [
"",
"java",
"annotations",
""
] |
how do i switch on an enum which have the flags attribute set (or more precisely is used for bit operations) ?
I want to be able to hit all cases in a switch that matches the values declared.
The problem is that if i have the following enum
```
[Flags()]public enum CheckType
{
Form = 1,
QueryString = 2,
TempData = 4,
}
```
and I want to use a switch like this
```
switch(theCheckType)
{
case CheckType.Form:
DoSomething(/*Some type of collection is passed */);
break;
case CheckType.QueryString:
DoSomethingElse(/*Some other type of collection is passed */);
break;
case CheckType.TempData
DoWhatever(/*Some different type of collection is passed */);
break;
}
```
If "theCheckType" is set to both CheckType.Form | CheckType.TempData I want it to hit both case's. Obviously it wont hit both in my example because of the break, but other than that it also fails because CheckType.Form is not equal to CheckType.Form | CheckType.TempData
The only solution then as I can see it is to make a case for every possible combination of the enum values ?
Something like
```
case CheckType.Form | CheckType.TempData:
DoSomething(/*Some type of collection is passed */);
DoWhatever(/*Some different type of collection is passed */);
break;
case CheckType.Form | CheckType.TempData | CheckType.QueryString:
DoSomething(/*Some type of collection is passed */);
DoSomethingElse(/*Some other type of collection is passed */);
break;
... and so on...
```
But that really isnt very desired (as it will quickly grow very big)
Right now i have 3 If conditions right after eachother instead
Something like
```
if ((_CheckType & CheckType.Form) != 0)
{
DoSomething(/*Some type of collection is passed */);
}
if ((_CheckType & CheckType.TempData) != 0)
{
DoWhatever(/*Some type of collection is passed */);
}
....
```
But that also means that if i have an enum with 20 values it have to go through 20 If conditions every single time instead of "jumping" to only the needed "case"/'s as when using a switch.
Is there some magic solution to solve this problem?
I have thought of the possibility to loop through the declared values and then use the switch, then it would only hit the switch for each value declared, but I don't know how it will work and if it performance vice is a good idea (compared to a lot of if's) ?
Is there an easy way to loop through all the enum values declared ?
I can only come up with using ToString() and splitting by "," and then loop through the array and parse every single string.
---
UPDATE:
I see that i haven't done a good enough job explaining.
My example is to simple (tried to simplify my scenario).
I use it for a ActionMethodSelectorAttribute in Asp.net MVC to determine if a method should be available when resolving the url/route.
I do it by declaring something like this on the method
```
[ActionSelectorKeyCondition(CheckType.Form | CheckType.TempData, "SomeKey")]
public ActionResult Index()
{
return View();
}
```
That would mean that it should check if the Form or TempData have a key as specified for the method to be available.
The methods it will be calling (doSomething(), doSomethingElse() and doWhatever() in my previous example) will actually have bool as return value and will be called with a parameter (different collections that doesn't share a interface that can be used - see my example code in the link below etc).
To hopefully give a better idea of what i am doing i have pasted a simple example of what i am actually doing on pastebin - it can be found here <http://pastebin.com/m478cc2b8> | How about this. Of course the arguments and return types of DoSomething, etc., can be anything you like.
```
class Program
{
[Flags]
public enum CheckType
{
Form = 1,
QueryString = 2,
TempData = 4,
}
private static bool DoSomething(IEnumerable cln)
{
Console.WriteLine("DoSomething");
return true;
}
private static bool DoSomethingElse(IEnumerable cln)
{
Console.WriteLine("DoSomethingElse");
return true;
}
private static bool DoWhatever(IEnumerable cln)
{
Console.WriteLine("DoWhatever");
return true;
}
static void Main(string[] args)
{
var theCheckType = CheckType.QueryString | CheckType.TempData;
var checkTypeValues = Enum.GetValues(typeof(CheckType));
foreach (CheckType value in checkTypeValues)
{
if ((theCheckType & value) == value)
{
switch (value)
{
case CheckType.Form:
DoSomething(null);
break;
case CheckType.QueryString:
DoSomethingElse(null);
break;
case CheckType.TempData:
DoWhatever(null);
break;
}
}
}
}
}
``` | Just use [HasFlag](https://msdn.microsoft.com/en-us/library/system.enum.hasflag(v=vs.110).aspx)
```
if(theCheckType.HasFlag(CheckType.Form)) DoSomething(...);
if(theCheckType.HasFlag(CheckType.QueryString)) DoSomethingElse(...);
if(theCheckType.HasFlag(CheckType.TempData)) DoWhatever(...);
``` | Switch on Enum (with Flags attribute) without declaring every possible combination? | [
"",
"c#",
"enums",
"switch-statement",
"flags",
"bit",
""
] |
How do I find out what's wrong with the device info set returned? I'm re-writing my code again and I'm still hitting the same stumbling block.
```
deviceInfoSet = SetupDiGetClassDevs(ref tGuid, 0, IntPtr.Zero, (uint)SetupDiFlags.DIGCF_PRESENT );
if (deviceInfoSet.ToInt32() == INVALID_DEVICE_HANDLE)
{
int errCode = Marshal.GetLastWin32Error();
errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
statusLabel.Text += "Invalid deviceinfoset returned: " + errCode + " => " + errorMessage + ".";
}
```
The above code doesn't cause any errors but when I use the code below:
```
result = true;
while (result)
{
result = SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref tGuid, Index, ref anInterface);
if (!result)
{
int errCode = Marshal.GetLastWin32Error();
errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
statusLabel.Text += "\nSetDiEnumDeviceInterface Error: " + errCode + " => " + errorMessage + ".";
break;
}
Index++;
}
```
to try and access the device info set list, error code 259 (**No more data is available**) is returned. I am at a loss as to what I'm doing wrong. | Are you sure you're using the right GUID?
Check out <http://blogs.msdn.com/doronh/archive/2006/02/15/532679.aspx>
Edit: Everything else looks by-the-book and correct.
Edit2: Trying including DIGCF\_DEVICEINTERFACE in call to SetupDiGetClassDevs, and see if that works for you. That is, both DIGCF\_PRESENT and DIGCF\_DEVICEINTERFACE.
Edit3: For the 64bit issue (@Thies), check out <http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ea816aea-f718-4a0e-b013-0aa273de037f> | I'm not familiar with this particular interface but it doesn't appear you are doing anything wrong. It simply appears that you are trying to read data from a device which currently has no data to offer.
Is that the case? Do you know for sure that the device is currently trying to return data to you? | How can I find out what is wrong with a SetupDiGetClassDev interface in C#? | [
"",
"c#",
".net",
"usb",
""
] |
If I use try/catch in WindowProc override of MFC window/view classes there is a performance hit. Why is it so and what is the alternative ?
This I caught as a result of profiling. Removing the block makes the function consume much lesser time. I am using MS VS 2008. | In [usage-of-try-catch-blocks-in-c](https://stackoverflow.com/questions/951380/usage-of-try-catch-blocks-in-c) Todd Gardner explains that compilers use the "table" approach or the "code" approach to implement exceptions. The "code" approach explains the performance hit. | Just using try/catch should not produce a performance hit - maybe you are throwing too many exceptions? Have you profiled your code to find out where the performance hit is coming from? | Using try/catch in WindowProc MFC | [
"",
"c++",
"mfc",
""
] |
I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?
I seem to remember using some web server type thing to browse through local help files, but I may have imagined that! | For the web server, you can run the `pydoc` module that is included in the python distribution as a script:
```
python /path/to/pydoc.py -p 1234
```
where `1234` is the port you want the server to run at. You can then visit `http://localhost:1234/` and browse the documentation. | From the Python REPL (the command-line interpreter / Read-Eval-Print-Loop), type `help("modules")` to see a list of all your available libs.
Then to see functions within a module, do `help("posix")`, for example. If you haven't `import`ed the library yet, you have to put quotes around the library's name. | How do I find out what Python libraries are installed on my Mac? | [
"",
"python",
""
] |
I'm having a problem with Fluent NHibernate mappings, I think, and can't quite get past how I should be setting the mapping to avoid an issue.
I have a business object (literally, a "business"), and a review object. Each Business can have multiple reviews that are created on a page in the UI. The business is a property of the Review, as follows:
```
public class Business
{
public virtual int BusinessId {get;set;}
public virtual DateTime LastModified {get;set;}
public virtual IList<Review> Reviews {get;set;}
[... more removed for brevity ...]
}
public class Review
{
public virtual int ReviewId {get;set;}
public virtual string ReviewText {get;set;}
public virtual Business Business {get;set;}
[... more removed for brevity ...]
}
```
My mappings are as follows:
```
public class ReviewMap : ClassMap<Review>
{
public ReviewMap()
{
WithTable("Reviews");
Id(x => x.ReviewId).TheColumnNameIs("ReviewId").GeneratedBy.Identity();
References(x => x.Business).TheColumnNameIs("BusinessId");
Map(x => x.ReviewText);
[... and so on...]
}
public class BusinessMap : ClassMap<Business>
{
public BusinessMap()
{
WithTable("Businesses");
Id(x => x.BusinessId).TheColumnNameIs("BusinessId").GeneratedBy.Identity();
Map(x => x.Name).TheColumnNameIs("BusinessName");
Map(x => x.LastModified, "LastModifiedOn");
HasMany<Review>(x => x.Reviews)
.Inverse()
.LazyLoad();
[... more removed for brevity ...]
}
}
```
The repository code is
```
public void Save(T entity)
{
using (ISession session = GetSession())
using (ITransaction tx = session.BeginTransaction())
{
session.SaveOrUpdate(entity);
tx.Commit();
}
}
```
In the code, I assign the properties to the Review object, and call the Repository's Save method.
The problem is that since I'm not updating the Business per se, I don't expect it to get saved--all I want is the review saved. But the code tries to save the Business as well, and I get an excption, as I haven't set the "LastModified" property--nor do I want to, as I'm saving the REVIEW, not the business.
How should I be setting up the mapping to let this happen? | Ok, so the problem was this: the Business's LastModified property wasn't actually set in the actual business object, as the database allowed NULL for this property.
What that meant was that when I tried to save the review, it also tried to save the business--most likely because it recognized that the database object had no value (null) for LastModified, but by default, since LastModified is a DateTime, its value was DateTime.MinValue.
Once I updated the business table in the database so that LastModified is now NOT NULL, it works.
The unfortunate part of this is that the data I was working with got into this state without this being an issue. | As I can't comment yet, I'll post here.
If you did want the LastModified column to be nullable, the corresponding property should have been a `DateTime?` rather than a plain `DateTime`. | Fluent NHibernate Mapping - Saving Child object | [
"",
"c#",
"fluent-nhibernate",
"mapping",
""
] |
I use to use IDL and MatLab in college and now that I have been working for some years I miss the : notation for indexing into arrays. e.g.
```
arrray[1:5]
```
which would return an array from elements from 1 to 5. Another example is:
```
stringVar.Split(")".ToCharArray())[1:*]
```
which would return an array of strings skipping over the first element.
**Has anyone seen a way to shoe-horn : notation this into C#?**
I have seen it in some interpreted languages and Perl or Python, can't remember.
**I wonder if this could be done with some operator overriding?** | This is not currently implemented in the BCL. The best way to add this on would be via an extension method. For instance, here's a quick and dirty example (not fully featured).
```
public static IEnumerable<T> GetRange<T>(this IEnumerable<T> enumerable, string range) {
var arr = range.Split(':');
var start = Int32.Parse(arr[0]);
if ( arr[1] == "*" ) {
return enmuerable.Skip(start);
} else {
var end = Int32.Parse(arr[1]);
return enumerable.Skip(start).Take(end-start);
}
}
```
Then you could do
```
strVar.GetRange("1:*"); // Skip first element take rest
strVar.GetRange("1:5"); // Skip first element next 5
```
**Note**: I'm not familiar with Matlab syntax at all so I'm not sure if I implemented it to the proper specs but hopefully it gets the general idea across. | Syntactically, there's nothing like this in C# and can't be done with operator overloading. Basically, per C# spec, the lexical analyzer will consider that a syntax error. You could use a third party custom preprocessor to make it work.
`ArraySegment` structure, however, *semantically* does a similar thing.
If you really love this stuff, consider looking at Python (or IronPython if you want it on .NET platform). | adding : notation to C# for indexing into arrays | [
"",
"c#",
".net",
""
] |
I'm writing some template classes for parseing some text data files, and as such it is likly the great majority of parse errors will be due to errors in the data file, which are for the most part not written by programmers, and so need a nice message about why the app failed to load e.g. something like:
> Error parsing example.txt. Value ("notaninteger")of [MySectiom]Key is not a valid int
I can work out the file, section and key names from the arguments passed to the template function and member vars in the class, however I'm not sure how to get the name of the type the template function is trying to convert to.
My current code looks like, with specialisations for just plain strings and such:
```
template<typename T> T GetValue(const std::wstring §ion, const std::wstring &key)
{
std::map<std::wstring, std::wstring>::iterator it = map[section].find(key);
if(it == map[section].end())
throw ItemDoesNotExist(file, section, key)
else
{
try{return boost::lexical_cast<T>(it->second);}
//needs to get the name from T somehow
catch(...)throw ParseError(file, section, key, it->second, TypeName(T));
}
}
```
Id rather not have to make specific overloads for every type that the data files might use, since there are loads of them...
Also I need a solution that does not incur any runtime overhead unless an exception occurs, i.e. a completely compile time solution is what I want since this code is called tons of times and load times are already getting somewhat long.
EDIT: Ok this is the solution I came up with:
I have a types.h containg the following
```
#pragma once
template<typename T> const wchar_t *GetTypeName();
#define DEFINE_TYPE_NAME(type, name) \
template<>const wchar_t *GetTypeName<type>(){return name;}
```
Then I can use the DEFINE\_TYPE\_NAME macro to in cpp files for each type I need to deal with (eg in the cpp file that defined the type to start with).
The linker is then able to find the appropirate template specialisation as long as it was defined somewhere, or throw a linker error otherwise so that I can add the type. | Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like:
```
template<typename T>
struct TypeParseTraits;
#define REGISTER_PARSE_TYPE(X) template <> struct TypeParseTraits<X> \
{ static const char* name; } ; const char* TypeParseTraits<X>::name = #X
REGISTER_PARSE_TYPE(int);
REGISTER_PARSE_TYPE(double);
REGISTER_PARSE_TYPE(FooClass);
// etc...
```
And then use it like
```
throw ParseError(TypeParseTraits<T>::name);
```
EDIT:
You could also combine the two, change `name` to be a function that by default calls `typeid(T).name()` and then only specialize for those cases where that's not acceptable. | The solution is:
```
typeid(T).name()
```
where `typeid(T)` returns [`std::type_info`](https://en.cppreference.com/w/cpp/types/type_info). | C++ Get name of type in template | [
"",
"c++",
"templates",
"compile-time",
"typename",
""
] |
I was just reading a [Java 7 preview presentation (pdf)](http://puredanger.com/techfiles/090204/Java7Preview.pdf) and there was a slide on *Chained Invocation*. Here is the example used in the slide:
```
// Construction with setters
DrinkBuilder margarita = new DrinkBuilder();
margarita.add("tequila");
margarita.add("orange liqueur");
margarita.add("lime juice");
margarita.withRocks();
margarita.withSalt();
Drink drink = margarita.drink();
// Construction with chained invocation
Drink margarita = new DrinkBuilder()
.add("tequila")
.add("orange liqueur")
.add("lime juice")
.withRocks()
.withSalt()
.drink();
```
And I have mixed feelings about this. One shouldn't chain too many method invocations into one statement. On the other hand, writing `margarita.this()` and `margarita.that()` isn't too convenient either.
Now, I am coming to Java from Delphi world. And in Delphi there is the [`with`](http://www.delphibasics.co.uk/RTL.asp?Name=With) language construct. This is cherished by a few and loathed by many (or is it the other way around?). I find `with` to be more elegant than the idea of chained invocation (which I believe works on the basis of `void` method returning reference to object on which it has been invoked - and this is the part I don't like, as `void` should return *nothing*).
I would appreciate the `with` language feature being adopted by Java, so the example code could be written like so:
```
Drink margarita = null;
with (new DrinkBuilder()) {
add("tequila");
add("orange liqueur");
add("lime juice");
withRocks();
withSalt();
margarita = drink();
}
```
Am I the only one who would prefer this solution to the chained invocation? Anyone else feels that `with` could be a useful extension to Java language? (Reminds me of someone's question about the need of "Java++"...) | the **with** statement can be translated in Java using anonymous classes with initializer:
```
Drink margarita = new DrinkBuilder() {{
add(“tequila”);
add(“orange liqueur”);
add(“lime juice”);
withRocks();
withSalt();
}}.drink();
```
the downsides of using this idiom are well documented [here](https://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization).
Chained Invocation is an alias for Method Chaining. That is well known idiom and works with any version of Java:
```
class Chained {
public Chained withFoo() {
// ...
return this;
}
public Chained withBar() {
// ...
return this;
}
}
```
a proposal for JDK 7 is [allowing of chaining method also for void return type](http://tech.puredanger.com/java7/#chained):
```
class ChainedJava7 {
public void withFoo() {
// ...
}
public void withBar() {
// ...
}
}
``` | [This](http://en.wikipedia.org/wiki/Fluent_interface) might interest you. | Chained invocation in Java 7? | [
"",
"java",
"language-design",
"language-features",
"java-7",
""
] |
I don't like having the same thing defined in two places, if I can avoid it.
I realize the two queries below are dealing with two different tables, but those tables hold basically the same kind of data (distinct predicates warrant the two queries), and I think of the two projections below as "the same thing defined in two places".
When/if I modify these queries later, to include different columns, I'm sure I'll always want the projections to remain identical.
Given that, and without using dynamic SQL, and without '\*' in any projection (not permitted in my production environment), can I define the "columnset" once and use it in both queries?
```
SELECT columnA
, columnB
, columnC
FROM Data
SELECT columnA
, columnB
, columnC
FROM DataArchive
``` | Have your base be a union of Data and DataArchive and use an inline table-valued function (SQL Server 2005 and up)?
```
CREATE FUNCTION UnifiedData (@LiveOnly bit, @ArchiveOnly bit)
RETURNS TABLE
AS
RETURN (
SELECT columnA
,columnB
,columnC
FROM (
SELECT 'Live' AS Src, *
FROM Data
WHERE @ArchiveOnly = 0
UNION ALL
SELECT 'Archive' AS Src, *
FROM DataArchive
WHERE @LiveOnly = 0
)
)
```
Not great, but should be handled pretty well by the optimizer since it's inlined. | I can't think of any efficient way of doing so. You could of course make a view with a `UNION ALL` of the two tables with the addition of a column that holds the table name as a string, then do `SELECT columnA, columnB, columnC FROM view WHERE table = 'Data'` but that feels like a rather ugly hack. | Refactored SQL projection? | [
"",
"sql",
"refactoring",
"refactoring-databases",
""
] |
Ok this is really frusturating me because I've done this a hundred times before, and this time it isn't working. So I know I'm doing something wrong, I just can't figure it out.
I am using the jQuery .get routine to load html from another file. I don't want to use .load() because it always replaces the children of the element I'm loading content into.
Here is my .get request:
```
$(document).ready(function() {
$.get('info.html', {}, function(html) {
// debug code
console.log($(html).find('ul').html());
// end debug code
});
});
```
The file 'info.html' is a standard xhtml file with a proper doctype, and the only thing in the body is a series of ul's that I need to access. For some reason, the find function is giving me a null value.
In firebug, the GET request is showing the proper RESPONSE text and when I run
```
console.log(html);
```
Instead of the current console.log line, I get the whole info.html as output, like I would expect.
Any ideas? | You cannot pull in an entire XHTML document. You can only handle tags that exist within the `<body>` of an html document. Frustrating. Strip everything from info.html that isn't within your `<body>` tag and try it again.
There are other potential ways around this issue - check below "Stackoverflow Related Items" at the base of this response.
> From the Doc: (<http://docs.jquery.com/Core/jQuery#htmlownerDocument>)
>
> *"HTML string cannot contain elements that are invalid within a div, such as
> html, head, body, or title elements.*"
### Stackoverflow Related Items:
* [Simple jQuery ajax example not finding elements in returned HTML](https://stackoverflow.com/questions/1033460/simple-jquery-ajax-example-not-finding-elements-in-returned-html)
* [What is the best practice for parsing remote content with jQuery?](https://stackoverflow.com/questions/1034881/what-is-the-best-practice-for-parsing-remote-content-with-jquery) | I know this is an old post but I've been having the EXACT same frustrating problem for a couple of hours and have found a solution. For me what actually worked was to have the html content wrapped with a **form** tag.
So having the following html source:
```
<html>
<head>
<body>
<form>
<div id="content">Some Stuff</div>
</form>
</body>
</head>
</html>
```
With this jquery snippet should work:
```
var callback = function (data) {
alert($("#content", $(data)).html());
};
$.get(url, null, callback, null);
```
Hope this helps... | jquery ajax parse response text | [
"",
"javascript",
"jquery",
"html",
"ajax",
""
] |
I am trying to write a method which receives a serializable object (implements Serializable) o and a method m.
The method should compare the state of o before invoking m and after invoking m, and tell if invoking m changed o. It should check if the bits representing o were changed after the methods. Ho can I do it? | If you check at jguru, [you'll see a useful example](http://www.jguru.com/faq/view.jsp?EID=103437):
> Wrap an ObjectOutputStream around a
> ByteArrayOutputStream. Serializing an
> object to the ObjectOutputStream will
> then store the object in the byte
> array:
```
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(myObject);
```
> To restore this object, reverse the
> process:
```
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object myObject = ois.readObject();
```
If you compare the resulting byte arrays before and after the method is called, you'll be able to detect whether the object has been affected. | First, correctly implement equals() (and hashCode()) on your object. You don't really need to serialize the object again. Just unserialize the original object and compare it (via equals()) to the object that you want to check for changes against.
I take it you mean:
```
public void checkChanged(Serializable o, Method m) { .... }
```
You can still do the above. Your assumption would be that the object o correctly implements equals() (and hashCode), which all objects SHOULD. You can (as other below have stated) compare the byte streams. It all depends on what you really mean by "changed". | In java, how to check if a method m changed the state of its receiver | [
"",
"java",
"serialization",
""
] |
C#, Net 2.0
Here's the code (I took out all my domain-specific stuff, and it still returns an empty array):
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ChildClass cc = new ChildClass();
cc.OtherProperty = 1;
FieldInfo[] fi = cc.GetType().GetFields();
Console.WriteLine(fi.Length);
Console.ReadLine();
}
}
class BaseClass<T>
{
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
}
class ChildClass : BaseClass<ChildClass>
{
private int myVar;
public int OtherProperty
{
get { return myVar; }
set { myVar = value; }
}
}
}
``` | The parameterless `GetFields()` returns *public* fields. If you want non-public ones, use:
```
cc.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
```
or whatever appropriate combination you want - but you *do* need to specify at least one of `Instance` and `Static`, otherwise it won't find either. You can specify both, and indeed public fields as well, to get everything:
```
cc.GetType().GetFields(BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.NonPublic |
BindingFlags.Public);
``` | Since the field is private, you need to use the overload of GetFields() that allows you to specify [BindingFlags.NonPublic](http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx).
To make this work, change it to:
```
FieldInfo[] fi = cc.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
``` | What's wrong with this reflection code? GetFields() is returning an empty array | [
"",
"c#",
"reflection",
"type-parameter",
""
] |
I noticed that the WPF designer does a very poor job on aligning the controls, compared to the Windows Forms designer.
In the window below, I am unable to align each label, so that its text is on the same line as the text in the text box beside. The first label is correctly aligned, but the WPF designer does not give me any snap lines to correctly align the second and the third one.
Also, I cannot align the button with the labels. The snap line puts the button a few pixels leftwards compared to the label texts.
I couldn't find a fast way to do this alignment manually, writing XAML code, either. Putting the controls in a grid, and setting the margin of each control is time consuming.
[alt text http://img520.imageshack.us/img520/4843/wpfdesigneralignment.png](http://img520.imageshack.us/img520/4843/wpfdesigneralignment.png)
Do you know a fast way to align the controls in the WPF windows ? | I tought I can avoid doing the alignment with hand-coded XAML. What I ended up with, is this (the styles can be reused in other windows):
```
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" SizeToContent="WidthAndHeight">
<Window.Resources>
<Style x:Key="ControlStyle" TargetType="Control">
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
<Style BasedOn="{StaticResource ControlStyle}" TargetType="Label">
<Setter Property="Margin" Value="-4,0,0,0"/>
</Style>
<Style BasedOn="{StaticResource ControlStyle}" TargetType="TextBox">
<Setter Property="Width" Value="120"/>
</Style>
<Style BasedOn="{StaticResource ControlStyle}" TargetType="Button">
<Setter Property="MinWidth" Value="70"/>
</Style>
<Style TargetType="Grid">
<Setter Property="Margin" Value="10,10,10,10"/>
</Style>
<Style x:Key="SeparatorColumn" TargetType="ColumnDefinition">
<Setter Property="Width" Value="10"/>
</Style>
<Style x:Key="SeparatorRow" TargetType="RowDefinition">
<Setter Property="Height" Value="3"/>
</Style>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Style="{StaticResource SeparatorColumn}"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Style="{StaticResource SeparatorRow}"/>
<RowDefinition/>
<RowDefinition Style="{StaticResource SeparatorRow}"/>
<RowDefinition/>
<RowDefinition Style="{StaticResource SeparatorRow}"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="0">Label:</Label>
<TextBox Grid.Row="0" Grid.Column="2">TextBox</TextBox>
<Label Grid.Row="2" Grid.Column="0">Label:</Label>
<TextBox Grid.Row="2" Grid.Column="2">TextBox</TextBox>
<Button Grid.Row="4" Grid.ColumnSpan="3">Button</Button>
<Label Grid.Row="6" Grid.Column="0">Label:</Label>
<TextBox Grid.Row="6" Grid.Column="2">TextBox</TextBox>
</Grid>
</Window>
``` | Use a Grid to lay out your controls then make sure you don't have any padding on the controls...unless of course you want some padding and you make sure they're all even.
A quick Google Search returned a basic tutorial:
[Introduction to the WPF Grid Control](http://dotnetslackers.com/Community/blogs/bmains/archive/2007/07/27/Introduction-to-the-WPF-Grid-Control.aspx) | How can I quickly align the controls in a WPF window? | [
"",
"c#",
"wpf",
""
] |
How do I serialize entity framework object into JavaScript Object (JSON)? I tried using [JSON.NET](http://json.codeplex.com/) but I am getting the following exception when I try to serialize it.
Exception: Newtonsoft.Json.JsonSerializationException, Message="Self referencing loop"
Hitesh | It sounds like you are having the same general problem as the original DataContract serializer, in regards to cyclic references. While objects referencing each other is fairly common with object graphs in memory, such cyclic references inevitably result in infinite recursions when serialized if the serializer does not specifically account for it. There are few, if any, established standards for dealing with cyclic references in the common non-binary serialization formats (XML and JSON being the two most prevalent.)
Microsoft solved the cyclic problem for the DataContract serializer in .NET 3.5 SP1 by making use of the ref semantics in xml. To my knowledge, there is no such thing for JSON, which might be why JSON.NET is preventing you from serializing your object graph.
I would make sure you have only references in your object graph that are navigable one-way, rather than both ways (i.e. only from parent to child, not from child to parent.) Those parent/child and child/parent are the most common types of cyclic references. It may also be that a lower-level child is ultimately referencing the root of the graph, causing an indirect cyclic graph to be created (these tend to be far less common than the parent/child loops, however.)
Once you eliminate any cyclic references in your object graph, you should be able to serialize. | I had this problem and solved it by adding the Newtonsoft.Json.JsonIgnoreAttribute to the property causing the loop. Obviously, that property won't be serialized. To help with this problem, I typically will have both the foreign reference ID and the foreign class in my entities. I realize this is not intuitive (or super great OO), but it is the way recommended by Julia Lerman in her book Programming Entity Framework: Code First. I've found it helps smooth out several problems with Entity Framework.
```
public class SomeEntity
{
[JsonIgnore]
public ForeignEntity SomeForeignEntity {get;set;}
public Guid ForeignEntityId {get;set;}
}
```
Update: I forgot to mention I also needed to disable proxies on the DbContext like so:
```
dataContext.Configuration.ProxyCreationEnabled = false;
```
If you are writing the code for a service (which seems likely if you are serializing), then this is probably not a problem, but there are some things you lose when the proxy creation is disabled. See here: <http://www.sellsbrothers.com/posts/Details/12665> for more details.
I am using the MS Web Api, so I just disable the the proxy creation when I construct my controller:
```
public class MailingApiController : ApiController
{
public MailingApiController()
{
PreventDeepSerialization();
}
private static void PreventDeepSerialization()
{
var dataContext = Injector.Get<IIntertwyneDbContext>();
dataContext.Configuration.ProxyCreationEnabled = false;
}
....
``` | Serialize Entity Framework Object using Json.Net | [
"",
"javascript",
"asp.net-mvc",
"entity-framework",
"json.net",
""
] |
I deployed my ASP.NET application under an existing virtual directory. The new deployment will have some features using JavaScript. The new features are not working.
If I deploy this build under a new virtual directory, the features using JavaScript are working.
I restarted the IIS Admin service. The problem continues.
What could be going wrong here? | ```
After the deployment if javascript features are not working then it may be beacuse executes the script which already cached. In this case to handle the situation please do the following
```
Try changing the JavaScript file's src?
From this:
To this:
This method should force your browser to load a new copy of the JS file. | Since javascript runs on the client, and not on the server, I doubt that IIS, per se, has anything to do with your problem.
What have you done to attempt to diagnose the problem? Have you looked at the network interaction between the browser and the server? Perhaps some script files are not being found.
Have you turned on any debugging tools (for instance, Firebug or the F12 command in IE8)? You may be getting errors you don't know about. | Why does JavaScript not work on my site under an existing virtual directory? | [
"",
"asp.net",
"javascript",
"iis",
"virtual-directory",
""
] |
How can I change the "selection style" on a DataGridView (winforms)? | You can easily change the forecolor and backcolor of selcted cells by assigning values to the SelectedBackColor and SelectedForeColor of the Grid's DefaultCellStyle.
If you need to do any further styling you you need to handle the SelectionChanged event
Edit: (Other code sample had errors, adjusting for multiple selected cells [as in fullrowselect])
```
using System.Drawing.Font;
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
foreach(DataGridViewCell cell in ((DataGridView)sender).SelectedCells)
{
cell.Style = new DataGridViewCellStyle()
{
BackColor = Color.White,
Font = new Font("Tahoma", 8F),
ForeColor = SystemColors.WindowText,
SelectionBackColor = Color.Red,
SelectionForeColor = SystemColors.HighlightText
};
}
}
``` | Use the [SelectedCells property](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectedcells.aspx) of the GridView and the [Style property](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.style.aspx) of the DataGridViewCell. | DataGridView selected cell style | [
"",
"c#",
"winforms",
""
] |
I am investigating a Java issue (using IBM JVM 1.4.2 64-bit) on Red Hat Linux.
I am wondering if anyone has seen this error message before and knows if there is a workaround to this problem?
Source:
```
import sun.misc.Signal;
import sun.misc.SignalHandler;
public class SignalTest extends Thread
{
private static Signal signal = new Signal("INT");
private static ShutdownHandler handler = new ShutdownHandler();
private static class ShutdownHandler implements SignalHandler
{
public void handle(Signal sig)
{
}
}
public static void main(String[] args)
{
try
{
Signal.handle(signal, handler);
}
catch(Throwable e)
{
e.printStackTrace();
}
try { Thread.sleep(5000); } catch(Exception e) { e.printStackTrace(); }
System.exit(0);
}
}
```
Output:
```
java.lang.IllegalArgumentException <Signal already used by VM: INT>
java.lang.IllegalArgumentException: Signal already used by VM: INT
at
com.ibm.misc.SignalDispatcher.registerSignal(SignalDispatcher.java:145)
at sun.misc.Signal.handle(Signal.java:199)
at xxx
```
Additional Information:
I found out something strange.
The reason why it fails is because I am running the program inside a shell script as a background process.
i.e.
sigtest.sh:
```
#!/bin/bash
java -cp . SignalTest >> sigtest.log 2>&1 &
```
If I run the program from the command line, or remove the "&" (i.e. make it a foreground process inside the shell script), it doesn't have a problem...
I don't understand why this is the case. | This is may very well be a JVM implementation specific problem. We are using an undocumented / unsupported API (`sun.misc.Signal/SignalHandler`) and therefore no contract on the behavior of the API is guaranteed.
The IBM JVM implementation could do signal-handling-related-things differently from the SUN JVM implementation and thus cause this problem. So that this specific use case works in the SUN JVM but not in the IBM JVM.
But try out the following (I can't try it out myself):
Do all combinations off starting the JVM with one/two/three of those parameters and there possible value combinations.
1. the `-Xrs` option specified / not specified
2. the property `ibm.signalhandling.sigint` set to `true` / `false`
3. the property `ibm.signalhandling.rs` set to `true` / `false`
(The properties where found via google in several error dumps but I can't find any specific documentation on them)
I don't know if the IBM JVM also supports this special flag but you could try adding this too which in SUN JVM seems to be specific for some problems with signal handlers under linux/solaris
```
-XX:-AllowUserSignalHandlers
```
Or try using a native signal handler if that is an option for you. Check out the code samples provided:
* in the [link below](http://www.ibm.com/developerworks/java/library/i-signalhandling)
* [Catching SIGINT in a Java application under UNIX](http://groups.google.com/group/comp.lang.java.programmer/browse_thread/thread/bac336a1411a3b4e/b3268276845a3ca4)
* [Check signal handling, native signal chainging](http://javajiggle.com/2008/01/06/if-jni-based-application-is-crashing-check-signal-handling/)
* [JDK 6 HotSpot VM - Signal Handling on Solaris OS and Linux](http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/signals.html#gbzcz)
Although it doesn't relate to your specific problem, an IBM article on JVM signal handling (slightly dated but still mostly correct). With samples for native code signal handlers:
[Revelations on Java signal handling and termination](http://www.ibm.com/developerworks/java/library/i-signalhandling)
---
But I guess this may all be to no avail as the IBM JVM implementation could rely on handling `SIGINT` itself to function correctly and thus never giving you a chance to handle `SIGINT` yourself.
Btw. from the [description to the `-Xrs` flag](http://java.sun.com/javase/6/docs/technotes/tools/solaris/java.html) I understand that it actually may hinder you to do what you want. It says
> When `-Xrs` is used on Sun's JVM, the
> signal masks for SIGINT, SIGTERM,
> SIGHUP, and SIGQUIT are not changed by
> the JVM, and **signal handlers for these**
> **signals are not installed**.
Or it could mean that only the JVM default actions for the signals aren't executed. Or it could depend on the JVM implementation what is really meant. | Try starting the JVM with an -Xrs option which is valid on the IBM JVM according to [this](http://www.ibm.com/developerworks/java/library/i-signalhandling/) anyway. That might prevent the conflict.
EDIT: In response to your underlying desire, look at:
[Runtime.getRuntime().addShutdownHook(Thread)](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread))
You subclass a thread object, and it will start as part of the shutdown (take out that -Xrs for this to work well). Some things (like calling halt on Runtime) can stop that from happening, so you do need to be aware of the possibility that it just won't end up happening. | Java error: java.lang.IllegalArgumentException: Signal already used by VM: INT | [
"",
"java",
"jvm",
"signals",
""
] |
What is the comparable technology of EJB (Enterprise Java Beans) in .net? | WCF in .Net 3.5 is the most similar as long as you aren't trying to use CMP. While it allows service endpoints for SOAP type things, it also allows binary remoting. | ### Definition of terms is important
When doing comparisons, the definition of terms is important. EJB is a
component model. It defines persistence, transaction, remoting, activation and
security capabilities (and maybe others) for components that operate within
the container.
You can look at comparable technologies in .NET, if that is what you are
after - the technical capabilities of the component model.
On the other hand some people use "EJB" as a term to loosely refer to
J2EE (or Java EE?). In which case it refers not *just* to a component model, but
to a set of related Java technologies usually associated to server-side
applications, including a component model. This might even include toolsets, which of course are
only tangentially related to the component model. If *that* is the
comparison, then it is more aptly described as "J2EE vs. .NET".
Still other people might be using an even fuzzier definition for EJB to
include things like web services capability, REST/XML communications, or
other stuff that is strictly outside Java EE or EJB proper. In other words when they say "compare EJB to .NET" they really mean to compare "Server-side Java platforms to server-side .NET". The latter strikes me as a much more practical comparison to make, than comparing, say, component models.
When doing the comparisons, it's important to be clear about just what
is being compared.
### EJB - the component model
In EJB you define an object and mark it as a Session Bean or an Entity
Bean. There's also the late addition of Message Driven Bean. Three
flavors of component in EJB. The Session Bean gets activation - how it
gets started and possibly "passivated" in times of high resource
contention on the server/container. The SB also gets security and
remoting services.
The basic idea is to define an object and then attach attributes to it,
either through the deployment descriptor or through in-code attributes,
the analog for which is called [annotations](http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html) in Java.
The closest thing to a EJB Session Bean is a .NET object. In any .NET
application, you can mark an object with transaction attributes, just
like a EJB SB. You can make it remotable, if you like, with .NET
Remoting and more attributes. Outside of COM+, there is no passivation technology in
.NET; .NET just ignores pooling as a generally interesting thing to do with
in-memory objects, and as a result there's no approach to do activation/passivation in .NET as there is with EJB.
---
> sidebar #1: that isn't quite true. In .NET, the Workflow capability provides a facility to have long-running activities that can and will be passivated and re-activated. But, Workflow is a distinct metaphor from "server side objects" or "services" which is the centerpoint of most server-side application architectures that use .NET.
---
> sidebar #2: It used to be that the designers of server-side platforms thought everyone was gonna want to use object pooling in order to be more efficient. Now it turns out that the JVM and .NET CLR are fast enough at creating objects, and memory is plentiful enough, that in general, object pooling is not of practical use. It is no longer interesting for the general case, though it still pays good dividends for expensive objects like database connections.
---
As with EJB, in .NET you can attach security
attributes to an object to allow it to run or not run based on the
identity of the caller, or other "evidence".
Entity Beans are a different animal. While persistence and remoting can
be combined, in most practical guidebooks, the recommendation is that an
entity bean not expose a remote interface. Instead the recommendation calls for a
session bean to call an entity bean. So let's just consider EB's as
persistent objects.
In .NET there are a bunch of alternatives here. LINQ-to-SQL gives one
option - with ORM and persistence services. The ADO.NET Entity
Framework is maybe a more comparable technology. Of course all the other
services in .NET - transactions security and remoting etc - also can be
applied to objects that use ADO.NET Entity Framework or LINQ.
On the other hand, depending on where your emphasis is in the EJB
umbrella, there may be better comparables. If you primarily use EJB for
remoting - and with the advent of REST, SOAP and other lightweight
protocols, almost no one does this anymore as far as I can tell - then a
better comparable in .NET is WCF.
Finally, the comparable to EJB MDB are .NET Queued Components.
### EJB Remoting
There are some common aspects to all these types of EJBs - like remote interfaces. Actually most architects recommend that you don't distribute your EJBs. In other words, they discourage people from using the remoting aspect that is so commonly discussed. Instead a servlet should invoke an EJB that is local, rather than invoking one on a remote machine. This is [Fowler's First Law](http://martinfowler.com/bliki/FirstLaw.html): *Don't distribute your objects*.
On the other hand, sometimes you must.
WCF is the communications framework within .NET, and is the aspect in .NET most comparable to EJB remoting. But they are not equivalent. WCF is a very general purpose framework for remote communications, supporting sync and async, multiple protocols, and extensible transport and channel model, while EJB remoting is fairly limited.
### Is starting from EJB the right approach?
EJB doesn't say anything (as far as I know) about web services, or REST,
or management or lightweight frameworks, or even HTML, or developer tools. Starting a
comparison with "EJB vs *blank*" artificially constrains the discussion
a little bit. It frames the discussion in a way that may not be
optimal.
There's nothing in EJB to handle, for example, an HTML page metaphor.
You get that in servlets or one of its cousins (portlets, etc), some of which are in J2EE proper. But strictly speaking, HTML output isn't covered in EJB.
Now, maybe you intend one of the more expansive definitions of
EJB. To that end, J2EE has now added web services into the specification. But even so, I'm not sure how relevant it is to consider the spec, with the variety of add-on Java-based frameworks for SOAP web services and REST.
Likewise, if you want to consider UI capabilities like portlets, servlets, and AJAX and compare them to the .NET equivalents, then you've moved well beyond EJB and J2EE and into server-side Java in general.
It gets back to my earlier point - be clear and precise in your own mind about what
you are interested in examining or comparing.
---
The EJB and J2EE specifications were ambitious - attempting to define the frameworks for server-side applications. But there was always a time lag between what developers were doing, what the spec was saying, and what the vendors were delivering. You know, maybe there was a 1-year lag between the finalization of a new version of the J2EE spec and the release of a compliant server from IBM.
Because of this it ended up being sort of artificial, after-the-fact. The spec was describing things that people were already doing. Things like Spring were coming out and J2EE wasn't saying anything about them. For the longest time J2EE had nothing to say about REST or Web services or AJAX. (Even now, does it say anything about AJAX? I don't know.)
In light of the distance between the theory of the spec and the reality of actual practice by developers, a better approach might be to identify the application requirements, and
then compare the appropriateness of EJB and other related technologies to the
apps you want to build.
In other words - suppose one of your requirements is that the app will be delivered via the browser, and it will have the responsiveness of AJAX. In that case you're going to have to consider jQuery, and that isn't anywhere covered in J2EE, or EJB. AJAX frameworks are available in various products (both Java and .NET). For example Visual Studio uses jQuery for the ASPNET AJAX stuff. But sticking to the specs sort of misses this stuff.
### Bottom Line
The bottom line is, any app that you build with EJBs can be built in
.NET, and vice versa.
I think a comparison like "EJB vs .NET" can be interested as an academic
discussion, but if you want practical insight into what technology to
use where, then you need to think a little differently.
You need to identify and prioritize requirements - like speed of
development, cost of deployment, mechanism of deployment, tool support, deployment platform support,
language support, performance, UI appearance, UI options, etc. Then weigh the options against that prioritized
list. | .NET - vs EJB | [
"",
"java",
".net",
"ejb",
""
] |
I have a simple PHP mailer script that takes values from a form submitted via POST and mails them to me:
```
<?php
$to = "me@example.com";
$name = $_POST['name'];
$message = $_POST['message'];
$email = $_POST['email'];
$body = "Person $name submitted a message: $message";
$subject = "A message has been submitted";
$headers = 'From: ' . $email;
mail($to, $subject, $body, $headers);
header("Location: http://example.com/thanks");
?>
```
How can I sanitize the input? | Sanitize the post variable with [`filter_var()`](http://www.php.net//manual/en/function.filter-var.php).
[Example here](http://net.tutsplus.com/tutorials/php/sanitize-and-validate-data-with-php-filters/). Like:
```
echo filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
``` | Since you're not building an SQL query or anything here, the only relevant validation that I can see for those inputs is an email validation for $\_POST["email"], and maybe an alphanumeric filter on the other fields if you really want to limit the scope of what the message can contain.
To filter the email address, simply use [filter\_var](http://php.net/filter_var):
```
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
```
As per Frank Farmer's suggestion, you can also filter out newlines in the email subject:
```
$subject = str_replace(array("\r","\n"),array(" "," "),$subject);
``` | How to sanitze user input in PHP before mailing? | [
"",
"php",
"security",
"email",
"sanitize",
""
] |
I need to calculate a **machine id for computers running MacOS**, but I don't know where to retrieve the informations - stuff like HDD serial numbers etc. The **main requirement** for my particular application is that the user **mustn't be able to spoof it**. Before you start laughing, I know that's far fetched, but at the *very least*, the spoofing method must require a reboot.
The best solution would be one in **C/C++**, but I'll take Objective-C if there's no other way. The über-best solution would **not need root privileges**.
Any ideas? Thanks. | Erik's suggestion of `system_profiler` (and its underlying, but undocumented SystemProfiler.framework) is your best hope. Your underlying requirement is not possible, and any solution without hardware support will be pretty quickly hackable. But you can build a reasonable level of obfuscation using `system_profiler` and/or SystemProfiler.framework.
I'm not sure your actual requirements here, but these posts may be useful:
* [Store an encryption key in Keychain while application installation process](https://stackoverflow.com/questions/886893/store-an-encryption-key-in-keychain-while-application-installation-process) (this was related to network authentication, which sounds like your issue)
* [Obfuscating Cocoa](http://robnapier.net/blog/obfuscating-cocoa-389) (this was more around copy-protection, which may not be your issue)
I'll repeat here what I said in the first posting: It is not possible, period, not possible, to securely ensure that only your client can talk to your server. If that is your underlying requirement, it is not a solvable problem. I will expand that by saying it's not possible to construct your program such that people can't take out any check you put in, so if the goal is licensing, that also is not a completely solvable problem. The second post above discusses how to think about that problem, though, from a business rather than engineering point of view.
**EDIT:** Regarding your request to require a reboot, remember that Mac OS X has kernel extensions. By loading a kernel extension, it is always possible to modify how the system sees itself at runtime without a reboot. In principle, this would be a Mac rootkit, which is not fundamentally any more complex than a Linux rootkit. You need to carefully consider who your attacker is, but if your attackers include Mac kernel hackers (which is not an insignificant group), then even a reboot requirement is not plausible. This isn't to say that you can't make spoofing annoying for the majority of users. It's just always possible by a reasonably competent attacker. This is true on all modern OSes; there's nothing special here about Mac. | The tool /usr/sbin/system\_profiler can provide you with a list of serial numbers for various hardware components. You might consider using those values as text to generate an md5 hash or something similar. | Machine ID for Mac OS? | [
"",
"c++",
"macos",
""
] |
I'm working on a project that'll use PEAR packages. Because you never know what version of the PEAR package will be installed on your hosting provider (and especially because I require a patch to have been applied to one of the packages), I'd like to put the PEAR source for my project right into SVN, so other developers can immediately have the dependencies.
But everything related to PEAR seems to have absolute directories! Running "pear config-create . pear.conf" to set up a new PEAR directory even fails with the error message:
Root directory must be an absolute path
I checked out the pear config files on some other servers and they, too, seem to have absolute paths.
Whenever a developer checks this out to his own machine, or we export it all to a server, we don't know what the absolute path will be.
Is there any way to set this up? | If you have PHP 5.3.1 use Pyrus, the PEAR2 installer. The pyrus managed installations can be moved where ever you like.
Download pyrus -
```
$> wget http://pear2.php.net/pyrus.phar
```
Create a directory to store your pyrus-installed packages:
```
$> mkdir mylibs
```
Install packages -
```
$> php pyrus.phar mylibs install pear/Net_URL
```
Your installed package is now at `mylibs/php/Net/URL.php`
Note that we passed the mylibs directory to indicate what directory to install to, as well as the channel name 'pear' (the default in pyrus is pear2.php.net). For convenience, the pyrus.phar file can be executed from cli if you chmod +x it.
You can move the `mylibs` directory wherever you'd like. Even commit it to your repository.
Lots of docs on the [PEAR website](http://pear.php.net/manual/en/). | I couldn't get my Hosting provider to install the PEAR libraries I wanted. Here's how I made PEAR part of my source tree.
## 1. Create a remote.conf file
Creating your remote.conf is a little different than in the manual. Lets say I want to install PEAR in `vendor/PEAR` of a project. You would do it like this:
```
#from the root of the project
$ cd vendor ; mkdir PEAR ; cd PEAR
$ pear config-create <absolute path to project>/vendor/PEAR/ remote.conf
```
## 2.Update the channels
```
$ pear -c remote.conf channel-update pear.php.net
```
## 3. install PEAR
```
$ pear -c remote.conf install --alldeps pear
```
## 4. install any other libraries
```
$ pear -c remote.conf install --alldeps <libname>
```
Voila... PEAR is part of the source tree.
## The Catches:
* Even though the paths in `remote.conf` are absolute the libraries themselves will still work. It's just updating that won't work from anywhere. You will need to update it from the same path that it was created from -- in the above case, from `vendor/PEAR`.
* Some libraries don't like being outside the path, so you may have to add `vendor/PEAR` to the path (I've got code, just ask if you need.) | Add PEAR packages to Subversion repository? | [
"",
"php",
"svn",
"pear",
""
] |
I'm looking for a way to remove the background of a 24bit bitmap, while keeping the main image totally opaque, up until now blending has served the purpose but now I need to keep the main bit opaque. I've searched on Google but found nothing helpful, I think I'm probably searching for the wrong terms though, so any help would be greatly appreciated.
Edit:
Yes sorry, I'm using black right now as the background. | When you are creating the texture for OpenGL, you'll want to create the texture as a 32-bit RGBA texture. Create a buffer to hold the contents of this new 32-bit texture and iterate through your 24-bit bitmap. Every time you come across your background color, set the alpha to zero in your new 32-bit bitmap.
```
struct Color32;
struct Color24;
void Load24BitTexture(Color24* ipTex24, int width, int height)
{
Color32* lpTex32 = new Color32[width*height];
for(x = 0; x < width; x++)
{
for(y = 0; y < height; y++)
{
int index = y*width+x;
lpTex32[index].r = ipTex24[index].r;
lpTex32[index].g = ipTex24[index].g;
lpTex32[index].b = ipTex24[index].b;
if( ipTex24[index] == BackgroundColor)
lpTex32[index].a = 0;
else
lpTex32[index].a = 255;
}
}
glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, lpTex32);
delete [] lpTex32;
}
``` | You will need to load your textures with GL\_RGBA format in your call to glTexImage2D.
If you have done this then you just need to enable blend:
```
/* Set up blend */
glEnable(GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
``` | How to remove black background from textures in OpenGL | [
"",
"c++",
"c",
"opengl",
"alpha",
"blending",
""
] |
My company is required to use an application developed in ASP.NET by another company. The application needs to be open in two separate browser windows. The company that developed the application has added some JavaScript at the top of the main page to stop user from opening multiple instances of the application. The script that is placed at the top of the main page is as follows:
```
<script type="text/javascript">
function OpenApplicationWindow() {
var sessionId = 'sidus455bjzspf55cunqrv55';
if (window.name.search(sessionId) == -1) {
window.open(window.location.href, sessionId, "resizable=yes,scrollbars=yes,toolbar=no,status=yes");
window.open('', '_parent', '');
window.close();
}
}
OpenApplicationWindow();
</script>
```
Is there anyway to open a link to that page and allow more than one instance to open? Or is there anyway to stop that script from running. | Short of disabling JavaScript (which would probably cause other problems), the only thing I can think of is to write a small proxy to strip that stuff out.
If you only need this on a few workstations, you could use Fiddler with the script editor to inspect and modify the response.
<http://www.fiddler2.com/Fiddler2/version.asp> -- download Fiddler
<http://www.fiddler2.com/fiddler/FSE.asp> -- download the script editor.
<http://www.fiddler2.com/Fiddler/Dev/ScriptSamples.asp> -- see the example on this page to remove all div tags. | You can use [GreaseMonkey for IE](http://www.gm4ie.com/), and create a small custom script to overwrite or remove the offending script.
More [information](http://www.ghacks.net/2008/11/16/install-greasemonkey-scripts-in-internet-explorer/) about using greasemonkey scripts in IE. | Stopping JavaScript from closing a window | [
"",
"javascript",
""
] |
This question is related to my other question "[How to redirect to Login page when Session is expired in Java web application?](https://stackoverflow.com/questions/1026846/how-to-redirect-to-login-page-when-session-is-expired-in-java-web-application)". Below is what I'm trying to do:
1. I've a JSF web application running on JBoss AS 5
2. When the user is inactive for, say 15 minutes, I need to log out the user and redirect him to the login page, if he is trying to use the application after the session has expired.
3. So, as suggested in '[JSF Logout and Redirect](http://www.jroller.com/hasant/entry/jsf_logout_and_redirect_user)', I've implemented a filter which checks for the session expired condition and redirects the user to a session-timed-out.jsp page, if the session has expired.
4. I've added SessionExpiryCheckFilter on top of all other filter definitions in web.xml, so that my session expiry check will get the first hit always.
Now comes the **challenge I'm facing**. Since I'm using JBoss AS, when the session expired, JBoss automatically redirects me to the login page (note that the session expiry check filter is not invoked). So, after I log-in, my SessionExpiryCheckFilter intercepts the request, and it sees a session is available. But, it throws the exception `javax.faces.application.ViewExpiredException: viewId:/mypage.faces - View /mypage.faces could not be restored.`
Have anyone faced this issue before? Any ideas to solve this issue? | The following approach works for me. Note that you have to use the JSTL core taglib redirect and not the jsp redirect in order for this to work (as the jsp also expires).
In your ***FacesConfig.xml*** you put the following:
```
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/sessionExpired.jsf</location>
</error-page>
```
***sessionExpired.jsp***:
```
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:redirect url="/login.jsf" />
```
You can also use this approach for other error types or exceptions. For example the element contains a mapping between an error code or exception type and the path of a resource in the web application.:
```
<error-page>
<error-code>400</error-code>
<location>/400.html</location>
</error-page>
```
or element contains a fully qualified class name of a Java exception type.
```
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/servlet/ErrorDisplay</location>
</error-page>
``` | If you are using Mojarra/Sun RI you might want to try to add this to your web.xml:
```
<context-param>
<param-name>com.sun.faces.enableRestoreView11Compatibility</param-name>
<param-value>true</param-value>
</context-param>
```
However be aware that this isn't always the perfect solution. It hides the fact that the user has lost its session. | Handling 'session expired' in JSF web application, running in JBoss AS 5 | [
"",
"java",
"session",
"jsf",
"servlet-filters",
"viewexpiredexception",
""
] |
How would one get resx resource strings into javascript code stored in a .js file?
If your javascript is in a script block in the markup, you can use this syntax:
```
<%$Resources:Resource, FieldName %>
```
and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed.
I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active.
One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser?
Or does anyone have any other suggestions? | There's no native support for this.
I built a JavaScriptResourceHandler a while ago that can serve Serverside resources into the client page via objects where each property on the object represents a localization resource id and its value. You can check this out and download it from this blog post:
<http://www.west-wind.com/Weblog/posts/698097.aspx>
I've been using this extensively in a number of apps and it works well. The main win on this is that you can localize your resources in one place (Resx or in my case a custom ResourceProvider using a database) rather than having to have multiple localization schemes. | Here is my solution for now. I am sure I will need to make it more versatile in the future... but so far this is good.
```
using System.Collections;
using System.Linq;
using System.Resources;
using System.Web.Mvc;
using System.Web.Script.Serialization;
public class ResourcesController : Controller
{
private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
public ActionResult GetResourcesJavaScript(string resxFileName)
{
var resourceDictionary = new ResXResourceReader(Server.MapPath("~/App_GlobalResources/" + resxFileName + ".resx"))
.Cast<DictionaryEntry>()
.ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
var json = Serializer.Serialize(resourceDictionary);
var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.{0} = {1};", resxFileName, json);
return JavaScript(javaScript);
}
}
// In the RegisterRoutes method in Global.asax:
routes.MapRoute("Resources", "resources/{resxFileName}.js", new { controller = "Resources", action = "GetResourcesJavaScript" });
```
So I can do
```
<script src="/resources/Foo.js"></script>
```
and then my scripts can reference e.g. `window.Resources.Foo.Bar` and get a string. | Use ASP.NET Resource strings from within javascript files | [
"",
"asp.net",
"javascript",
"resources",
""
] |
I've run accorss a really weird issue, in eclipse I've got a codebase I've been working on for a couple of weeks and it's working fine. I did an svn update and all of a sudden one of my classes doesn't compile because it can't resolve an enum which is in the same namespace to a type.
I've checked the Java version and I'm running under Java 6 so enums should be supported.
Also it worked up till yesterday and now it doesn't.
Has anyone else seen this kind of behaviour? I've reloaded eclipse but beyond that I dont know where to start diagnosing it. | I unloaded the project and reloaded it and it just works... No idea what the origianl issue was... | If it does say "Step cannot be resolved to a type", just try and clean the project (Project -> Clean). Eclipse gets confused sometimes, and a clean usually helps. | Eclipse cannot resolve enum in the same namespace? | [
"",
"java",
"eclipse",
""
] |
I'm working on a scientific computing code (written in C++), and in addition to performing unit tests for the smaller components, I'd like to do regression testing on some of the numerical output by comparing to a "known-good" answer from previous revisions. There are a few features I'd like:
* Allow comparing numbers to a specified tolerance (for both roundoff error and looser expectations)
* Ability to distinguish between ints, doubles, etc, and to ignore text if necessary
* Well-formatted output to tell what went wrong and where: in a multi-column table of data, only show the column entry that differs
* Return `EXIT_SUCCESS` or `EXIT_FAILURE` depending on whether the files match
Are there any good scripts or applications out there that do this, or will I have to roll my own in Python to read and compare output files? Surely I'm not the first person with these kind of requirements.
*[The following is not strictly relevant, but it may factor into the decision of what to do. I use CMake and its embedded CTest functionality to drive unit tests that use the Google Test framework. I imagine that it shouldn't be hard to add a few `add_custom_command` statements in my `CMakeLists.txt` to call whatever regression software I need.]* | I ended up writing a Python script to do more or less what I wanted.
```
#!/usr/bin/env python
import sys
import re
from optparse import OptionParser
from math import fabs
splitPattern = re.compile(r',|\s+|;')
class FailObject(object):
def __init__(self, options):
self.options = options
self.failure = False
def fail(self, brief, full = ""):
print ">>>> ", brief
if options.verbose and full != "":
print " ", full
self.failure = True
def exit(self):
if (self.failure):
print "FAILURE"
sys.exit(1)
else:
print "SUCCESS"
sys.exit(0)
def numSplit(line):
list = splitPattern.split(line)
if list[-1] == "":
del list[-1]
numList = [float(a) for a in list]
return numList
def softEquiv(ref, target, tolerance):
if (fabs(target - ref) <= fabs(ref) * tolerance):
return True
#if the reference number is zero, allow tolerance
if (ref == 0.0):
return (fabs(target) <= tolerance)
#if reference is non-zero and it failed the first test
return False
def compareStrings(f, options, expLine, actLine, lineNum):
### check that they're a bunch of numbers
try:
exp = numSplit(expLine)
act = numSplit(actLine)
except ValueError, e:
# print "It looks like line %d is made of strings (exp=%s, act=%s)." \
# % (lineNum, expLine, actLine)
if (expLine != actLine and options.checkText):
f.fail( "Text did not match in line %d" % lineNum )
return
### check the ranges
if len(exp) != len(act):
f.fail( "Wrong number of columns in line %d" % lineNum )
return
### soft equiv on each value
for col in range(0, len(exp)):
expVal = exp[col]
actVal = act[col]
if not softEquiv(expVal, actVal, options.tol):
f.fail( "Non-equivalence in line %d, column %d"
% (lineNum, col) )
return
def run(expectedFileName, actualFileName, options):
# message reporter
f = FailObject(options)
expected = open(expectedFileName)
actual = open(actualFileName)
lineNum = 0
while True:
lineNum += 1
expLine = expected.readline().rstrip()
actLine = actual.readline().rstrip()
## check that the files haven't ended,
# or that they ended at the same time
if expLine == "":
if actLine != "":
f.fail("Tested file ended too late.")
break
if actLine == "":
f.fail("Tested file ended too early.")
break
compareStrings(f, options, expLine, actLine, lineNum)
#print "%3d: %s|%s" % (lineNum, expLine[0:10], actLine[0:10])
f.exit()
################################################################################
if __name__ == '__main__':
parser = OptionParser(usage = "%prog [options] ExpectedFile NewFile")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="Don't print status messages to stdout")
parser.add_option("--check-text",
action="store_true", dest="checkText", default=False,
help="Verify that lines of text match exactly")
parser.add_option("-t", "--tolerance",
action="store", type="float", dest="tol", default=1.e-15,
help="Relative error when comparing doubles")
(options, args) = parser.parse_args()
if len(args) != 2:
print "Usage: numdiff.py EXPECTED ACTUAL"
sys.exit(1)
run(args[0], args[1], options)
``` | You should go for [PyUnit](http://pyunit.sourceforge.net/pyunit.html#USING), which is now part of the standard lib under the name [`unittest`](http://docs.python.org/library/unittest.html). It supports everything you asked for. The tolerance check, e.g., is done with [`assertAlmostEqual()`](http://docs.python.org/library/unittest.html#unittest.TestCase.assertAlmostEqual). | Numerical regression testing | [
"",
"c++",
"unit-testing",
"testing",
"regression-testing",
""
] |
I have been tasked with porting our .NET Desktop application to a mobile device. Our desktop application uses LINQ to SQL to interact with the database. However, LINQ to SQL is not available on mobile devices. We develop for Windows Mobile 5 and 6.
I am debating between suggesting a different ORM that supports both desktop and mobile out of the box (<http://www.entityspaces.net/portal/> seems the best to me). However, since our databases are relatively small (one of them is relatively simple at 10 tables; the other is 27 tables but the associations are more complex), I am leaning more towards just re-coding the domain objects and data access functions myself.
Has anyone else been in this situation? What choice did you make? | My team is using [T4](http://www.olegsych.com/2007/12/text-template-transformation-toolkit/) to generate basic CRUD operations based on the structure of the database and the conventions we use to map our POCO classes and properties to SQL Compact tables and columns. It is a bit of work, but is working out OK. | I can personally recommend LLBLGen. They have CF Framework support for v1.0 & 2.0. It's very quick to map tables and the resulting entities can be used in both mobile and desktop. It's also not expensive, and has a long track record. Based on your requirements, that would be the quickest way there. Doing it in POCOs (Plain Old CLR Objects) and using Linq to Objects would be doable, but would take much longer. | LINQ to SQL replacement in .NET Compact Framework | [
"",
"c#",
".net",
"linq-to-sql",
"compact-framework",
"mobile",
""
] |
Part of why I love Rails is that I hate SQL - I think it's more like an assembly language that should be manipulated with higher level tools such as ActiveRecord. I seem to have hit the limits of this approach, however, and I'm out of my depth with the SQL.
I have a complex model with lots of sub-records. I also have a set 30-40 named\_scopes that implement the business logic from the client. These scopes get chained together conditionally, which is why I have those `joins_` scopes so the joins don't get clobbered.
I've got a couple of them that don't work right, or at least not how the client wants them to work. Here's a rough idea of the model structure, with a few named scopes (not all needed for the example) that illustrate my approach and indicate my problems. *(please forgive any syntax errors)*
```
class Man < ActiveRecord::Base
has_many :wives
named_scope :has_wife_named lambda { |n| { :conditions => { :wives => {:name => n}}}}
named_scope :has_young_wife_named lambda { |n| { :conditions => { :wives => {:name => n, :age => 0..30}}}}
named_scope :has_yw_named_v2 lambda { |n| { :conditions => ["wives.name = ? AND wives.age <= 30", n]}}
named_scope :joins_wives :joins => :wives
named_scope :has_red_cat :conditions => { :cats => {:color => 'red'}}
named_scope :has_cat_of_color lambda { |c| { :conditions => { :cats => {:color => c}}}}
named_scope :has_7yo_cat :conditions => { :cats => {:age => 7}}
named_scope :has_cat_of_age lambda { |a| { :conditions => { :cats => {:age => a}}}}
named_scope :has_cat_older_than lambda { |a| { :conditions => ["cats.age > ?", a] }}
named_scope :has_cat_younger_than lambda { |a| { :conditions => ["cats.age < ?", a] }}
named_scope :has_cat_fatter_than lambda { |w| { :conditions => ["cats.weight > ?", w] } }
named_scope :joins_wives_cats :joins => {:wives => :cats}
end
class Wife < ActiveRecord::Base
belongs_to :man
has_many :cats
end
class Cat < ActiveRecord::Base
belongs_to :wife
end
```
1. I can find men whose wives have cats that are red AND seven years old
```
@men = Man.has_red_cat.has_7yo_cat.joins_wives_cats.scoped({:select => 'DISTINCT men'})
```
And I can even find men whose wives have cats that are over 20 pounds and over 6 years old
```
@men = Man.has_cat_fatter_than(20).has_cat_older_than(5).joins_wives_cats.scoped({:select => 'DISTINCT men'})
```
But that's not what I want. I want to find the men whose wives have amongst them at least one red cat and one seven year old cat, which need not be the same cat, or to find the men whose wives have amongst them at least one cat above a given weight and one cat older than a given age.
*(in subsequent examples, please assume the presence of the appropriate `joins_` and `DISTINCT`)*
2. I can find men with wives named Esther
```
@men = Man.has_wife_named('Esther')
```
I can even find men with wives named Esther, Ruth OR Ada (sweet!)
```
@men = Man.has_wife_named(['Esther', 'Ruth', 'Ada'])
```
but I want to find men with wives named Esther AND Ruth AND Ada.
3. Ha ha, only joking, actually, I need this: I can find men with wives under 30 named Esther
```
@men = Man.has_young_wife_named('Esther')
```
find men with young wives named Esther, Ruth or Ada
```
@men = Man.has_young_wife_named(['Esther', 'Ruth', 'Ada'])
```
but as above I want to find men with young wives named Esther AND Ruth AND Ada. Fortunately, the minimum is fixed in this case, but it would be nice to specify a minimum age as well.
4. is there a way to test for an inequality with a hash syntax, or do you always have to revert to `:conditions => ["", n]` - note the difference between `has_young_wife_named` and `has_yw_named_v2` - I like the first better, but the range only works for finite values. If you're looking for an old wife, I guess you could use `a..100` but then when a wife turns 101 years old she drops off the search. *(hmm. can she cook? j/k)*
5. is there a way to use a scope within a scope? I'd love it if `:has_red_cat` could use `:has_cat_of_color` somehow, or if there was some way to use the scope from a child record in its parent, so I could put the cat related scopes into the `Wife` model.
I really don't want to do this in straight SQL without using `named_scope`, unless there's something else actually nicer - suggestions for plugins and whatnot greatly appreciated, or direction into the sort of SQL I'll need to learn. A friend suggested that UNIONs or sub-searches would work here, but those don't seem to be discussed much in the context of Rails. I don't yet know anything about views - would they be useful? Is there a rails-happy way to make them?
Thank you!
*As I was going to St Ives
I met a man with seven wives
Each wife had seven sacks
Each sack had seven cats
Each cat had seven kits
Kits, cats, sacks, wives
How many were going to St Ives?* | Well, I've had great results with `named_scope`s like these:
```
named_scope :has_cat_older_than lambda { |a| { :conditions => ["men.id in ( select man_id from wives where wives.id in ( select wife_id from cats where age > ? ) )", a] } }
```
and
```
named_scope :has_young_wife_named lambda { |n| { :conditions => ["men.id in ( select man_id from wives where name = ? and age < 30)", n] } }
```
I can now successfully do
```
Member.has_cat_older_than(6).has_young_wife_named('Miriam').has_young_wife_named('Vashti')
```
and get what I'm expecting. These scopes don't require the use of the joins, and they seem to play well with the other styled joins.
w00t!
Commentary elicited on whether this is an efficient way to do this, or if there is a more 'rails-y' way. Some way to include a scope from another model as an sql subquery fragment could be useful... | I've used construct\_finder\_sql to accomplish the subselect of one named\_scope within another. It may not be for everyone, but using it allow us to DRY up a couple of named\_scopes we used for reports.
```
Man.has_cat_older_than(6).send(:construct_finder_sql,{})
```
Try that in your script/console. | Complex rails query - unions? sub-select? can I still used named_scope? | [
"",
"sql",
"mysql",
"ruby-on-rails",
"activerecord",
"union",
""
] |
```
datetime = '0000-00-00 00:00:00'.split('-')
```
Right now it just splits it at the hyphen, but is it possible to split this string at both -'s and :'s ? | One idea would be something like this (untested):
```
years, months, days = the_string.split('-')
days, time = days.split(' ')
time = time.split(':')
```
Or this, which fits your data better.
```
date, time = the_string.split(' ')
years, months, days = date.split('-')
hours, minute, seconds = time.split(":")
``` | I'm guessing you also want to split on the space in the middle:
```
import re
values = re.split(r'[- :]', "1122-33-44 55:66:77")
print values
# Prints ['1122', '33', '44', '55', '66', '77']
``` | Splitting a string @ once using different seps | [
"",
"python",
"string",
"split",
""
] |
Im having a hard time grasping this concepts of objects and how they should interact/exist.
Should I for instance have different objects (well, maybee I mean connections to the database here if there is any difference) for interactions with my database whenever they are not related?
Lets say I have one object that index.php uses to get and display content from the database
and another object that a user use to add/remove things in the database. We can say that the objects are all of the class dbinteract which holds all the functions for messing about with the database.
Or should I maybee divide the classes into something like: dbconnection, dbdisplay, dbinsertion, dbmodification where I send the dbconnection to the other objects?
I feel like im missing something very obvious and it's frustrating trying to move forward not knowing where in the thought process im going wrong, I guess im looking for a question as well as a an answer here.
## index.php
```
$connection = new dbconnection();
$displayer = new dbdisplay();
$activeconnection = $connection->connecttodatabase();
$pagetodisplay = $connection->getcontentofpagetodisplay($query);
$displayer->displayPage($activeconnection, $pagetodisplay);
```
## userinsert.php
```
$inserter = new dbinsert();
$usersdbconnection = new dbconnection();
$inserter->newPost($userdbconnection, $usercredentials, $posttextfromuser);
$usersdbconnection->closedatabaseconnection();
``` | You seem to be think at the wrong level of abstraction. OOP allows you to think about 'users' and 'articles' instead of 'database connections' and 'pages'.
I'm not sure I understand the problem fully - I think your question is 'which object should be responsible for connecting to the database?'. Creating a connection to the database only needs to be done once. This connection can then be shared between all of the objects. To share the connection you will need to create a class which all other classes that connect to the database can inherit from and a `static` variable in that class to ensure that only one connection object exists.
In other languages `static` variables are commonly called `class` variables. | To me, what it seems like you're missing is that object-oriented programming isn't there to make you do extra work following its rules, it's there to make your life easier. If it isn't making your life easier, you're doing it wrong. | Should I instantiate new objects for all different interactions? | [
"",
"php",
"oop",
""
] |
I have a class library and it has a folder. My projects classes are in that folder. I can use the class which is without that folder, but I can't use classes which are in that folder. For example:
**Without that folder:**
```
Example exmp = new Example();
```
I can use exmp normally.
**In the folder:**
```
User user = new User();
```
I'm using asp.net framework 3.5 with c#
> stack trace : at MedulaRADClassLib.MedulaClasses.Kullanici..ctor() at
> KlinikMuhasebe.Giris.f\_GirisYap() in
> C:\Users\cagin\_arslan\Desktop\Medula V3 Gerçek 5 Haziran
> 2009\V3\_Gercek\KlinikMuhasebe\Giris.aspx.cs:line 59
>
> inner exception : An error occurred loading a configuration file:
> Failed to map the path '/'
That problem is only on my computer. The other computers in the team haven't got the same problem. | I started my project with administrator privileges and this solved my problem. | Well it sounds like something either in the `User` constructor or something it calls, or in the User's static initializer, or something that calls. Or possibly in the classloader which is looking for that class (if it's Java).
If you post the *full* stack trace of the exception it's likely to give a lot more of a clue - in particular, which class is throwing the exception!
(You should also say what platform you're on. Is this Java, .NET, something else?)
A [search](http://www.google.com/search?q=%22An+error+occurred+loading+a+configuration+file%22+%22Failed+to+map+the+path%22&btnG=Search) for
```
"An error occurred loading a configuration file" "Failed to map the path"
```
finds quite a few hits suggesting it's ASP.NET, with [one solution](http://cs.rthand.com/blogs/blog_with_righthand/archive/2007/12/01/WebConfigurationManager.OpenWebConfiguration-throws-Failed-to-map-the-path-_27002F0027002E00_.aspx) suggesting running VS2005 as an administrator... | Unable to use classes contained in a class library folder | [
"",
"c#",
"asp.net",
"exception",
"class",
""
] |
I am designing a application where many clients connect to a central server. This server keeps these connections, sending keep-alives every half-hour. The server has a embedded HTTP server, which provides a interface to the client connections (ex. <http://server/isClientConnected?id=id>). I was wondering what is the best way to go about this. My current implementation is in Java, and I just have a Map with ID's as the key, but a thread is started for each connection, and I don't know if this is really the best way to do this. Any pointers would be appreciated.
Thanks,
Isaac Waller | Use the java.nio package, as described on this page: [Building Highly Scalable Servers with Java NIO](http://www.onjava.com/pub/a/onjava/2004/09/01/nio.html). Also read this page very carefully: [Architecture of a Highly Scalable NIO-Based Server](http://today.java.net/cs/user/print/a/350).
Personally I'd not bother with the NIO internals and use a framework like [Apache MINA](http://mina.apache.org/) or [xSocket](http://xsocket.sourceforge.net/). NIO is complicated and easy to get wrong in very obscure ways. If you want it to "just work", then use a framework. | With a single thread per connection you can usually scale up to about 10,000 connections on a single machine. For a Windows 32 machine, you probably will hit a limit around 1,000 connections.
To avoid this, you can either change the design of your program, or you can scale out (horizontal). You have to weight the cost of development with the cost of hardware.
The single thread per user, with a single continuous connection is usually the easiest programming model. I would stick with this model until you reach the limits of your current hardware. At that point, I would decide to either change the code, or add more hardware. | How to design a server with many persistent connections | [
"",
"java",
"sockets",
"client",
"persistent-connection",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.