Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
### ANSWER:
If you ever see these lines and are mistified like I was, here's what they mean.
`Thread[AWT-EventQueue-0] (Suspended (exception NullPointerException))`
`EventDispatchTread.run() line: not available [local variables unavailable]`
It's not that the variables are unavailable because they are lurking behind a shroud of mystery in a library somewhere dank. No no, they just went out of scope! It's still your fault, you still have to find the null, and no you can't blame the library. Important lesson!
### QUESTION:
One of the most frustrating things for me, as a beginner is libraries! It's a love/hate relationship: On the one hand they let me do things I wouldn't normally understand how to do with the code that I do understand, on the other hand because I don't completely understand them, they sometimes throw a wrench in code that is otherwise working fine! It's because I don't understand the errors that can occur when using these libraries, because I didn't write them, and because eclipse doesn't give me a great deal to go with when one of imports starts acting up...
So here's the problem: I've been working with java.awt.event to handle a bunch of JButtons on the screen for this and that. I get an error when I use one of the buttons I've made. The error is:
`Thread[AWT-EventQueue-0] (Suspended (exception NullPointerException))`
`EventDispatchTread.run() line: not available [local variables unavailable]`
What does this mean? What could be causing it? I'm embarrassed to post code, but if you can stand to try to decipher my terrible style, here is the method that seems to cause this error to be thrown.
```
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String name;
code...
if(cmd.equals("Play")) {
name = field.getText();
card = getCard(name);
if(card != null) {
if(rules.zoneHasCard(card, rules.hand)) {
display.updateStatusMessage(rules.play(card));
field.setText("");
display.updateHand(rules.zoneList("hand"));
display.updateDiscard(rules.zoneList("Discard")); // This is the error here! The discard Zone was empty!
}
else {
field.setText("You do not have " + card.getName());
field.selectAll();
}
}
else {
field.setText("That cardname is unused");
field.selectAll();
}
}
}
``` | Welcome to the complexity of writing GUI code.
When you run a Swing program, a background thread called the Event Dispatch Thread is created. When the user clicks on a JButton, for example, JButton creates and fires an event using this Event Dispatch Thread. Hence the name: it's the thread that dispatches events!
Your code:
```
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String name;
// more code...
}
```
is called by this Event Dispatch Thread, so your code can handle the event.
Somewhere within your code you are trying to do something with a variable that is currently equal to null. The error message is telling you, "hey while running some code on the event dispatch thread, I encountered a NullPointerException" **in your code**.
Why are you not receiving more info? Possibly you configured Eclipse not to include debug info when compiling?
For now, I recommend adding some lines to your actionPerformed method to show the state of variables:
```
System.out.println("field = " + field);
System.out.println("rules = " + rules);
System.out.println("display = " + display);
```
See if this shows you any nulls.
Even if the NullPointerException comes from a library, the stack trace will show which line of your code called that library. But only if you've configured Eclipse to generate debugging info.
In the longer term, work through the Sun's Swing Tutorial to learn more about these issues. | Any method call on a null object will raise a null pointer exception.
In your code, *rules, name or display* could be null and cause an exception. | What is this java.awt.event error? | [
"",
"java",
"events",
"awt",
""
] |
I have the following Linq to SQL query, in which I'm trying to do a multi-column GROUP BY:
```
return from revision in dataContext.Revisions
where revision.BranchID == sourceBranch.BranchID-1
&& !revision.HasBeenMerged
group revision by new Task(revision.TaskSourceCode.ToUpper(),
revision.TaskSourceID)
into grouping
orderby grouping.Key ascending
select (ITask)grouping.Key;
```
This throws InvalidOperationException ("Cannot order by type 'Task'.").
Is there an interface that Task must implement (it *already* implements IComparable, IComparable<ITask>)? Does Task need to be a Linq to SQL Entity (it isn't, currently, since there's no corresponding table). Or is this just something that Linq to SQL doesn't support?
Note that I've already tried an anonymous type for the grouping, which failed with a similar InvalidOperationException:
```
...
group revision by new { Code = revision.TaskSourceCode.ToUpper(),
Id = revision.TaskSourceID }
...
```
For what it's worth, note that the Task object is a composite of 2 fields; one is a single character (typically 'S' or 'B') and the other is an int (actually a cross-database "foreign key" if you like). The act of ordering by Tasks just compares their string representations; E.G. Task 'B101' < Task 'S999' | Looks like you already have your solution, but just FYI LINQ to SQL does support `.ToUpper()`.
For instance:
```
NorthwindDataContext dc = new NorthwindDataContext();
Product product = dc.Products.Single(p => p.ProductName.ToUpper() == "CHAI");
```
Is translated into:
```
exec sp_executesql N'SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued]
FROM [dbo].[Products] AS [t0]
WHERE <b>UPPER([t0].[ProductName]) = @p0</b>',N'@p0 nvarchar(4)',@p0=N'CHAI'
```
Hope that helps. | OK, I figured this out. I had two problems; first of all, ToUpper() doesn't translate into SQL, and secondly, I don't think Linq to SQL supports orderby on objects; at least not non-entities. By decomposing the orderby into its constituent columns, everything started to work as planned.
```
return from revision in dataContext.Revisions
where revision.BranchID == sourceBranch.BranchID-1
&& !revision.HasBeenMerged
group revision by new { revision.TaskSourceCode,
revision.TaskSourceID }
into grouping
orderby grouping.Key.TaskSourceCode,
grouping.Key.TaskSourceID ascending
select (ITask)new Task(grouping.Key.TaskSourceCode,
grouping.Key.TaskSourceID);
``` | Linq to SQL: How can I Order By a composite object? | [
"",
"c#",
"linq-to-sql",
"sql-order-by",
""
] |
This is probably not possible, but I have this class:
```
public class Metadata<DataType> where DataType : struct
{
private DataType mDataType;
}
```
There's more to it, but let's keep it simple. The generic type (DataType) is limited to value types by the where statement. What I want to do is have a list of these Metadata objects of varying types (DataType). Such as:
```
List<Metadata> metadataObjects;
metadataObjects.Add(new Metadata<int>());
metadataObjects.Add(new Metadata<bool>());
metadataObjects.Add(new Metadata<double>());
```
Is this even possible? | ```
public abstract class Metadata
{
}
// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
private DataType mDataType;
}
``` | Following leppie's answer, why not make `MetaData` an interface:
```
public interface IMetaData { }
public class Metadata<DataType> : IMetaData where DataType : struct
{
private DataType mDataType;
}
``` | C# - Multiple generic types in one list | [
"",
"c#",
"generics",
""
] |
this seems so silly - i must be missing something obvious. I have the following code (just as a test):
```
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void page_load(object o, EventArgs e)
{
Response.Write(new string(' ', 255));
Response.Flush();
for (int i = 0; i < 10; i++)
{
Response.Write(i + "<BR>");
Response.Flush();
System.Threading.Thread.Sleep(500);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
main div
</div>
</form>
</body>
</html>
```
when i test this locally (vista x64, cassini), i get the desired output.. 1, then 2, then 3, etc are all sent non-buffered to the browser. when i try this on the dev server (2003, iis6) it just buffers it all and sends it all at once. is there something obvious i'm missing?? I've also tried putting buffer=false at the top but that also doesn't change this behaviour.
to further clarify, i've done a test with fiddler to compare two servers. the first server is a local server on the LAN, the second is a public server. fiddler found no discernible difference between the two, except for the host name. the LAN server did not write out the response until the page had finished loading, the public server wrote the response as it happened. i can also confirm this behaviour happens in both firefox and ie. | I put my 2 cents on that when you access the public site, you are running through a web proxy, and that is where the content is being cached. | Try this in Page\_Load:
```
Response.BufferOutput = false;
```
Also get a copy of [Fiddler](http://www.fiddlertool.com/fiddler/) and watch your HTTP conversation to make sure your page is not cached. | How to disable Response.Buffer | [
"",
"c#",
"asp.net",
"buffer",
""
] |
Is there any performance penalty for the following code snippet?
```
for (int i=0; i<someValue; i++)
{
Object o = someList.get(i);
o.doSomething;
}
```
Or does this code actually make more sense?
```
Object o;
for (int i=0; i<someValue; i++)
{
o = someList.get(i);
o.doSomething;
}
```
If in byte code these two are totally equivalent then obviously the first method looks better in terms of style, but I want to make sure this is the case. | In today's compilers, no. I declare objects in the smallest scope I can, because it's a lot more readable for the next guy. | [To quote Knuth, who may be quoting Hoare](http://en.wikipedia.org/wiki/Optimization_(computer_science)#When_to_optimize):
> **Premature optimization is the root of all evil.**
Whether the compiler will produce marginally faster code by defining the variable outside the loop is debatable, and I imagine it won't. I would *guess* it'll produce identical bytecode.
Compare this with the number of errors you'll likely prevent by correctly-scoping your variable using in-loop declaration... | Declare an object inside or outside a loop? | [
"",
"java",
"performance",
""
] |
I've been working with Swing for a while now but the whole model/structure of `JFrame`s, `paint()`, `super`, etc is all murky in my mind.
I need a clear explanation or link that will explain how the whole GUI system is organized. | The same happened to me. Actually to this day I don't quite get 100% how all it works.
Swing is a very flexible framework - perhaps too flexible. With flexibility comes a lot of abstraction and with abstraction comes confusion. :)
I've found the following articles worth reading. They helped me to better understand the big picture of Swing.
* [A Swing Architecture Overview](http://www.oracle.com/technetwork/java/architecture-142923.html)
* [The process of installing a UI delegate](https://web.archive.org/web/20110815102419/http://java.sun.com/products/jfc/tsc/articles/architecture/ui_install/index.html), which is just this image:
[](https://web.archive.org/web/20110815102419/http://java.sun.com/products/jfc/tsc/articles/architecture/ui_install/index.html)
They explain quite well how the model and the delegate work. It always drives me mad when I see those `JLabel`, `LabelUI`, `ui.update`, etc. | Have you looked at the Java Swing Tutorial (click [here](http://java.sun.com/docs/books/tutorial/uiswing/))? It does a pretty good job of covering the basics of developing Swing applications. | Java GUI Swing Model Explanation | [
"",
"java",
"swing",
"user-interface",
"jframe",
""
] |
This may seem like a stupid question, so here goes:
Other than parsing the string of FileInfo.FullPath for the drive letter to then use DriveInfo("c") etc to see if there is enough space to write this file. Is there a way to get the drive letter from FileInfo? | ```
FileInfo f = new FileInfo(path);
string drive = Path.GetPathRoot(f.FullName);
```
This will return "C:\". That's really the only other way. | Well, there's also this:
```
FileInfo file = new FileInfo(path);
DriveInfo drive = new DriveInfo(file.Directory.Root.FullName);
```
And hey, why not an extension method?
```
public static DriveInfo GetDriveInfo(this FileInfo file)
{
return new DriveInfo(file.Directory.Root.FullName);
}
```
Then you could just do:
```
DriveInfo drive = new FileInfo(path).GetDriveInfo();
``` | Get the drive letter from a path string or FileInfo | [
"",
"c#",
"file-io",
""
] |
Is this
```
... T1 join T2 using(ID) where T2.VALUE=42 ...
```
the same as
```
... T1 join T2 on(T1.ID=T2.ID) where T2.VALUE=42 ...
```
for all types of joins?
My understanding of `using(ID)` is that it's just shorthand for `on(T1.ID=T2.ID)`. Is this true?
Now for another question:
Is the above the same as
```
... T1 join T2 on(T1.ID=T2.ID and T2.VALUE=42) ...
```
This I don't think is true, but why? How does conditions in the on clause interact with the join vs if its in the where clause? | I don't use the USING syntax, since
1. most of my joins aren't suited to it (not the same fieldname that is being matched, and/or multiple matches in the join) and
2. it isn't immediately obvious what it translates to in the case with more than two tables
ie assuming 3 tables with 'id' and 'id\_2' columns, does
```
T1 JOIN T2 USING(id) JOIN T3 USING(id_2)
```
become
```
T1 JOIN T2 ON(T1.id=T2.id) JOIN T3 ON(T1.id_2=T3.id_2 AND T2.id_2=T3.id_2)
```
or
```
T1 JOIN T2 ON(T1.id=T2.id) JOIN T3 ON(T2.id_2=T3.id_2)
```
or something else again?
Finding this out for a particular database version is a fairly trivial exercise, but I don't have a large amount of confidence that it is consistent across all databases, and I'm not the only person that has to maintain my code (so the other people will also have to be aware of what it is equivalent to).
An obvious difference with the WHERE vs ON is if the join is outer:
Assuming a T1 with a single ID field, one row containing the value 1, and a T2 with an ID and VALUE field (one row, ID=1, VALUE=6), then we get:
```
SELECT T1.ID, T2.ID, T2.VALUE FROM T1 LEFT OUTER JOIN T2 ON(T1.ID=T2.ID) WHERE T2.VALUE=42
```
gives no rows, since the WHERE is required to match, whereas
```
SELECT T1.ID, T2.ID, T2.VALUE FROM T1 LEFT OUTER JOIN T2 ON(T1.ID=T2.ID AND T2.VALUE=42)
```
will give one row with the values
```
1, NULL, NULL
```
since the ON is only required for matching the join, which is optional due to being outer. | The `USING` clause is shorthand for an equi-join of columns, assuming the columns exist in both tables by the same name:
```
A JOIN B USING (column1)
A JOIN B ON A.column1=B.column1
```
You can also name multiple columns, which makes joins on compound keys pretty straightforward. The following joins should be equivalent:
```
A JOIN B USING (column1, column2)
A JOIN B ON A.column1=B.column1 AND A.column2=B.column2
```
Note that `USING (<columnlist>)` is required to have parentheses, whereas `ON <expr>` is not required to have parentheses (although parens may be used around `<expr>` just they may be included around an expression in any other context).
Also, no other tables joined in the query may have a column by that name, or else the query is ambiguous and you should get an error.
Regarding you question about additional conditions, assuming you use an `INNER JOIN` it should logically give the same result from the query, but the optimization plan may be affected, depending on the RDBMS implementation. Also `OUTER JOIN` gives a different result if you include conditions in the join versus the `WHERE` clause. | What's the difference between "using" and "on" in table joins in MySQL? | [
"",
"mysql",
"sql",
"join",
""
] |
I've found this piece of code on [Koders](http://www.koders.com/csharp/fidACD7502AA845419FF59B7DA804D3C8FCA0E40138.aspx?s=basecodegeneratorwithsite#L76):
```
private ServiceProvider SiteServiceProvider
{
get
{
if (serviceProvider == null)
{
serviceProvider = new ServiceProvider(site as VSOLE.IServiceProvider);
Debug.Assert(serviceProvider != null, "Unable to get ServiceProvider from site object.");
}
return serviceProvider;
}
}
```
I'm wondering, is there *any* possible way the `Debug.Assert(serviceProvider != null` could trigger? I'm under the impression that `new` could only be aborted by an exception, in which case the assert would never be reached. | It's possible that the ServiceProvider overrides the !=/== operator, so that for an *invalid* state the comparison to null returns true.
Looks strange anyway. | I would expect that "test for null" pattern more if it was a factory method - i.e.
```
SomeType provider = SomeFactory.CreateProvider();
if(provider == null) // damn!! no factory implementation loaded...
{ etc }
```
There is one other case worth knowing about, but which doesn't apply here (since we know the type we are creating)... `Nullable<T>`; this is mainly an issue with generics:
```
static void Test<T>() where T : new()
{
T x = new T();
if (x == null) Console.WriteLine("wtf?");
}
static void Main()
{
Test<int?>();
}
```
This is covered more [here](https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-or-net#194671). | Checking C# new() initialisation for null? | [
"",
"c#",
"exception",
"new-operator",
""
] |
I know how to do this using for loops. Is it possible to do something like this using LINQ or lambdas?
```
int[] a = { 10, 20, 30 };
int[] b = { 2, 4, 10 };
int[] c = a * b; //resulting array should be { 20, 80, 300 }
``` | EDIT: The code below will work, but it's not as readable as using an explicit method. LINQ is great where it definitely *adds* to readability... but this isn't one of those cases.
This is a briefer version of CMS's answer - the extra `let` isn't required, and when you're just doing a projection it's simpler to just use dot notation:
```
int[] result = Enumerable.Range(0, a.Length)
.Select(i => a[i] * b[i])
.ToArray();
```
An alternative is to use the form of Select which takes an index:
```
int[] result = a.Select((value, index) => value * b[index])
.ToArray();
``` | Using the Zip function (new to .NET 4.0) details [here](http://bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx):
```
int[] a = { 10, 20, 30 };
int[] b = { 2, 4, 10 };
int[] c = a.Zip(b, (a1, b1) => a1 * b1).ToArray();
```
Until .NET 4 comes out you can use the zip implementation from the link above. | Can you use LINQ or lambdas to perform matrix operations? | [
"",
"c#",
"linq",
"lambda",
""
] |
I noticed C++ will not compile the following:
```
class No_Good {
static double const d = 1.0;
};
```
However it will happily allow a variation where the double is changed to an int, unsigned, or any integral type:
```
class Happy_Times {
static unsigned const u = 1;
};
```
My solution was to alter it to read:
```
class Now_Good {
static double d() { return 1.0; }
};
```
and figure that the compiler will be smart enough to inline where necessary... but it left me curious.
Why would the C++ designer(s) allow me to static const an int or unsigned, but not a double?
Edit: I am using visual studio 7.1 (.net 2003) on Windows XP.
Edit2:
Question has been answered, but for completion, the error I was seeing:
```
error C2864: 'd' : only const static integral data members can be initialized inside a class or struct
``` | The problem is that with an integer, the compiler *usually* doesn't have to ever create a memory address for the constant. It doesn't exist at runtime, and every use of it gets inlined into the surrounding code. It can still decide to give it a memory location - if its address is ever taken (or if it's passed by const reference to a function), that it must. In order to give it an address, it needs to be defined in some translation unit. And in that case, you need to separate the declaration from the definition, since otherwise it would get defined in multiple translation units.
Using g++ with no optimization (`-O0`), it automatically inlines constant integer variables but not constant double values. At higher optimization levels (e.g. `-O1`), it inlines constant doubles. Thus, the following code compiles at `-O1` but NOT at `-O0`:
```
// File a.h
class X
{
public:
static const double d = 1.0;
};
void foo(void);
// File a.cc
#include <stdio.h>
#include "a.h"
int main(void)
{
foo();
printf("%g\n", X::d);
return 0;
}
// File b.cc
#include <stdio.h>
#include "a.h"
void foo(void)
{
printf("foo: %g\n", X::d);
}
```
Command line:
```
g++ a.cc b.cc -O0 -o a # Linker error: ld: undefined symbols: X::d
g++ a.cc b.cc -O1 -o a # Succeeds
```
For maximal portability, you should declare your constants in header files and define them once in some source file. With no optimization, this will not hurt performance, since you're not optimizing anyways, but with optimizations enabled, this can hurt performance, since the compiler can no longer inline those constants into other source files, unless you enable "whole program optimization". | I see no technical reason why
```
struct type {
static const double value = 3.14;
};
```
is forbidden. Any occasion you find where it works is due to non-portable implementation defined features. They also seem to be of only limited use. For integral constants initialized in class definitions, you can use them and pass them to templates as non-type arguments, and use them as the size of array dimensions. But you can't do so for floating point constants. Allowing floating point template parameters would bring its own set of rules not really worth the trouble.
Nonetheless, the next C++ version will allow that using `constexpr`:
```
struct type {
static constexpr double value = 3.14;
static constexpr double value_as_function() { return 3.14; }
};
```
And will make `type::value` a constant expression. In the meantime, your best bet is to follow the pattern also used by `std::numeric_limits`:
```
struct type {
static double value() { return 3.14; }
};
```
It will not return a constant expression (value is not known at compile time), but that only matters theoretical, since practical the value will be inlined anyway. See the [constexpr](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2235.pdf) proposal. It contains
> 4.4
>
> `Floating-point constant expressions`
>
> Traditionally, evaluation of
> floating-point constant expression at
> compile-time is a thorny issue. For
> uniformity and generality, we suggest
> to allow constant-expression data of
> floating point types, initialized with
> any floating-point constant
> expressions. That will also increase
> compatibility with C99 [ISO99, §6.6]
> which allows
>
> [#5] An expression that evaluates to a
> constant is required in several
> contexts. If a floating expression is
> evaluated in the translation envi-
> ronment, the arithmetic precision and
> range shall be at least as great as if
> the expression were being evaluated in
> the execution environ- ment. | Why can't I have a non-integral static const member in a class? | [
"",
"c++",
""
] |
--Edit with more bgnd information--
A (black box) COM object returns me a string.
A 2nd COM object expects this same string as byte[] as input and returns a byte[] with the processed data.
This will be fed to a browser as downloadable, non-human-readable file that will be loaded in a client side stand-alone application.
so I get the string inputString from the 1st COM and convert it into a byte[] as follows
```
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, inputString);
obj = ms.ToArray();
```
I feed it to the 2nd COM and read it back out.
The result gets written to the browser.
```
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment; filename="test.dat");
Response.BinaryWrite(obj);
```
The error occurs in the 2nd COm because the formatting is incorrect.
I went to check the original string and that was perfectly fine. I then pumped the result from the 1st com directly to the browser and watched what came out. It appeared that somewhere along the road extra unreadable characters are added. What are these characters, what are they used for and how can I prevent them from making my 2nd COM grind to a halt?
The unreadable characters are of this kind:
NUL/SOH/NUL/NUL/NUL/FF/FF/FF/FF/SOH/NUL/NUL/NUL etc
Any ideas?
**--Answer--**
Use
```
System.Text.Encoding.UTF8.GetBytes(theString)
```
rather then
```
BinaryFormatter.Serialize()
``` | Okay, with your updated information: your 2nd COM object expects binary data, but you want to create that binary data from a string. Does it treat it as plain binary data?
My guess is that something is going to reverse this process on the client side. If it's eventually going to want to reconstruct the data as a string, you need to pick the right encoding to use, and use it on both sides. UTF-8 is a good bet in most cases, but *if* the client side is just going to write out the data to a file and use it as an XML file, you need to choose the appropriate encoding based on the XML.
You said before that the first few characters of the string were just `"<foo>"` (or something similar) - does that mean there's no XML declaration? If not, choose UTF-8. Otherwise, you should look at the XML declaration and use that to determine your encoding (again defaulting to UTF-8 if the declaration doesn't specify the encoding).
Once you've got the right encoding, use Encoding.GetBytes as mentioned in earlier answers. | BinaryFormatter is almost certainly not what you want to use.
If you just need to convert a string to bytes, use [Encoding.GetBytes](http://msdn.microsoft.com/en-us/library/system.text.encoding.getbytes.aspx) for a suitable encoding, of course. UTF-8 is usually correct, but check whether the document specifies an encoding. | Converting string from memorystream to binary[] contains leading crap | [
"",
"c#",
"stream",
""
] |
Using C#, when a user types a text in a normal textbox, how can you see the Hebrew equivalent of that text?
I want to use this feature on a data entry form, when the secretary puts in the customer name using English characters to have it converted automatically in another textbox to the hebrew representation.
Maybe something with CultureInfo("he-IL")... | I didn't even know there was such a thing as [Hebraization](http://en.wikipedia.org/wiki/Hebraization_of_English) — thanks for asking this question :-)
This functionality is not provided by the .NET Framework, so I'm afraid you'd have to build it yourself. You'd have to know how the English is pronounced to provide the correct Hebrew transliteration — not an easy task, I think. | I'll guess that's next to impossible, I don't know hebrew, but I do know from other languages that the pronounciation (and thus the transliteration) peoples names often (actually more often than not) differs a lot from the general pronounciation of the letters. This is because names change slower than the writing system, wich allso changes slower than the verbal language.
When transliterating you *must* base the transliteration on phonetics not the quirks of the other writing system, so the transliterator must essentially know both languages to some degree, and teaching a computer to understand languages *verbally* is still probably *far* into the future. You could of course just arbitarily select one of the symbols that could represent a sound in both languages, but this wil (undoubtedly) yeld hillarius results, and will probably not be much helpful.
Many languages (especially English) have very complicated and irregular pronounciation rules (in the case of English; apparently totally random\*) and there is never an exact one-to-one relationship between writing systems (if it is you're probably talking about a symbol font not an actual writing system), so unless you have tought your computer to speak both languages fluently there's not much chance of automatic transliteration. | Convert text from English characters to Hebrew characters | [
"",
"c#",
"cultureinfo",
"hebrew",
""
] |
If there will be a small number of files it should be easy with a recursive function to pass through all the files and add the size but what if there are lots of files, and by lots i really mean lots of files. | You mean something like this?
```
import os
for path, dirs, files in os.walk( root ):
for f in files:
print path, f, os.path.getsize( os.path.join( path, f ) )
``` | There is no other way to compute the size than recursively invoking stat. This is independent of Python; the operating system just provides no other way.
The algorithm doesn't have to be recursive; you can use os.walk.
There might be two exceptions to make it more efficient:
1. If all the files you want to measure fill a partition, and the partition has no other files, then you can look at the disk usage of the partition.
2. If you can continuously monitor all files, or are responsible for creating all the files yourself, you can generate an incremental disk usage. | What's the best way to get the size of a folder and all the files inside from python? | [
"",
"python",
""
] |
Rails introduced some core extensions to Ruby like `3.days.from_now` which returns, as you'd expect a date three days in the future. With extension methods in C# we can now do something similar:
```
static class Extensions
{
public static TimeSpan Days(this int i)
{
return new TimeSpan(i, 0, 0, 0, 0);
}
public static DateTime FromNow(this TimeSpan ts)
{
return DateTime.Now.Add(ts);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(
3.Days().FromNow()
);
}
}
```
Or how about:
```
static class Extensions
{
public static IEnumerable<int> To(this int from, int to)
{
return Enumerable.Range(from, to - from + 1);
}
}
class Program
{
static void Main(string[] args)
{
foreach (var i in 10.To(20))
{
Console.WriteLine(i);
}
}
}
```
Is this fundamentally wrong, or are there times when it is a good idea, like in a framework like Rails? | I like extension methods a lot but I do feel that when they are used outside of LINQ that they improve readability at the expense of maintainability.
Take `3.Days().FromNow()` as an example. This is wonderfully expressive and anyone could read this code and tell you exactly what it does. That is a truly beautiful thing. As coders it is our joy to write code that is self-describing and expressive so that it requires almost no comments and is a pleasure to read. This code is paramount in that respect.
However, as coders we are also responsible to posterity, and those who come after us will spend most of their time trying to comprehend how this code works. We must be careful not to be so expressive that debugging our code requires leaping around amongst a myriad of extension methods.
Extension methods veil the "how" to better express the "what". I guess that makes them a double edged sword that is best used (like all things) in moderation. | First, my gut feeling: `3.Minutes.from_now` looks totally cool, but does not demonstrate why extension methods are good. This also reflects my general view: cool, but I've never really missed them.
---
**Question: Is `3.Minutes` a timespan, or an angle?**
Namespaces referenced through a using statement "normally" only affect types, now they suddenly decide what `3.Minutes` means.
So the best is to "not let them escape".
All public extension methods in a likely-to-be-referenced namespace end up being "kind of global" - with all the potential problems associated with that. Keep them internal to your assembly, or put them into a separate namespace that is added to each file separately. | C# Extension Methods - How far is too far? | [
"",
"c#",
"ruby-on-rails",
"extension-methods",
""
] |
I am using CODBCRecordset (a class found on CodeProject) to find a single record in a table with 39 columns. If no record is found then the call to CRecordset::Open is fine. If a record matches the conditions then I get an Out of Memory exception when CRecordset::Open is called. I am selecting all the columns in the query (if I change the query to select only one of the columns with the same where clause then no exception).
I assume this is because of some limitation in CRecordset, but I can't find anything telling me of any limitations. The table only has 39 columns.
Has anyone run into this problem? And if so, do you have a work around / solution?
This is a MFC project using Visual Studio 6.0 if it makes any difference.
Here's the query (formatted here so wold show up without a scrollbar):
```
SELECT `id`, `member_id`, `member_id_last_four`, `card_number`, `first_name`,
`mi`, `last_name`, `participant_title_id`, `category_id`, `gender`,
`date_of_birth`, `address_line_1`, `address_line_2`, `city`, `state`,
`zip`, `phone`, `work_phone`, `mobile_phone`, `fax`, `email`,
`emergency_name`, `emergency_phone`, `job_title`, `mail_code`,
`comments`, `contract_unit`, `contract_length`, `start_date`,
`end_date`, `head_of_household`, `parent_id`, `added_by`, `im_active`,
`ct_active`, `organization`, `allow_members`, `organization_category_id`,
`modified_date`
FROM `participants`
WHERE `member_id` = '27F7D0982978B470C5CF94B1B833CC93F997EE23'
```
Copying and pasting into my query browser gives me only one result.
More info:
Commented out each column in the select statement except for id. Ran the query and no exception.
Then I systematically went through and uncommented each column, one at a time, and re-ran query in between each uncomment.
When I uncomment the comment column then I get the error.
This is defined as the following (Using MySQL): LONGTEXT | Read Pax's response. It gives a you a great understanding about why the problem happens.
Work Around:
This error will only happen if the field defined as (TEXT, LONGTEXT, etc) is NULL (and maybe empty). If there is data in the field then it will only allocate for the size the data in the field and not the max size (thereby causing the error).
So, if there is a case where you absolutely have to have these large fields. Here is a potential solution:
1. Give the field a default value in the database. (ie. `'<blank>'`)
2. Then when displaying the value; you pass NULL/empty if you find default value.
3. Then when updating the value; you pass the default value if you find NULL/empty. | Can we assume you mean you're calling C**ODBC**Recordset::Open(), yes? Or more precisely, something like:
```
CDatabase db;
db.Open (NULL,FALSE,FALSE,"ODBC;",TRUE);
CODBCRecordSet rs (&db);
rs.Open ("select blah, blah, blah from ...");
```
**EDIT after response:**
There are some known bugs with various ODBC drivers that appear to be caused by retrieving invalid field lengths. See these links:
* <http://forums.microsoft.com/msdn/showpost.aspx?postid=2700779&siteid=1>
* <https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=296391>
This particular one seems to have been because CRecordset will allocate a buffer big enough to hold the field. As the column returns a length of zero, it's interpreted as the max 32-bit size (~2G) instead of the max 8-bit size (255 bytes). Needless to say, it can't allocate enough memory for the field.
Microsoft has acknowledged this as a problem, have a look at these for solutions:
* <http://support.microsoft.com/kb/q272951/>
* <http://support.microsoft.com/kb/940895/>
**EDIT after question addenda:**
So, given that your MySQL field is a LONGTEXT, it appears CRecordSet is trying to allocate the max possible size for it (2G). Do you really need 2 gig for a comments field? Typing at 80 wpm, 6cpw would take a typist a little over 7 years to fill that field, working 24 h/day with no rest :-).
It may be a useful exercise to have a look at all the columns in your database to see if they have appropriate data types. I'm not saying that you **can't** have a 2G column, just that you should be certain that it's necessary, especially in light of the fact that the current ODBC classes won't work with a field that big. | "out of memory" exception in CRecordset when selecting a LONGTEXT column from MySQL | [
"",
"c++",
"mysql",
"database",
"mfc",
"recordset",
""
] |
sorry but I do not have the actual code with me, but I will try to explain:
I have a servlet mapped to the following:
```
/admin/*
```
So, this goes to a servlet:
```
public class AdminController extends MainController {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// Do stuf here
}
}
```
Here is MainController:
```
public class MainController extends HttpServlet {
@Override
public void service(ServletRequest request, ServletResponse response) {
String requesturi = ((HttpServletRequest)request).getRequestURI();
reqlist = Arrays.asList(requesturi.substring(requesturi.indexOf(Util.rootPath) + Util.rootPath.length()).split("/"));
reqlist = reqlist.subList(1, reqlist.size());
doPost((HttpServletRequest)request, (HttpServletResponse)response);
}
```
So, the request is passed to AdminController, no problem, but then I reallized something:
**The servlet is being called twice!**. And this is causing me many errors..
Does anybody have a clue on this? It is because I used some kind of heritance?
Thank you for all! | The [HttpServlet.service](http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/http/HttpServlet.html#service(javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse)) method gets called for all request types and what you are seeing is a HEAD request and then a GET or POST request. Instead of implementing service just implement doGet or doPost. What is commonly done is to just implement one of doPost or doGet and then call the other from the one you don't have an implementation for. | Though it is old thread but my answer may help someone.
Today I faced the same issue. My particular servlet is working fine earlier and suddenly it has started calling doGet method twice. On investigation, I found that my chrome browser has html validator extension which is calling the servlet again with same request to do html validation.
After I disabling the extension, the problem got resolved. | Servlet being called twice! | [
"",
"java",
"servlets",
""
] |
I am trying a straightforward remote json call with jquery. I am trying to use the reddit api. <http://api.reddit.com>. This returns a valid json object.
If I call a local file (which is what is returned from the website saved to my local disk) things work fine.
```
$(document).ready(function() {
$.getJSON("js/reddit.json", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div><a href=\"" + url + "\">" + title + "</a><div>");
});
});
});
```
If I then try to convert it to a remote call:
```
$(document).ready(function() {
$.getJSON("http://api.reddit.com", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div><a href=\"" + url + "\">" + title + "</a><div>");
});
});
});
```
it will work fine in Safari, but not Firefox. This is expect as Firefox doesnt do remote calls due to security or something. Fine.
In the jquery docs they say to do it like this (jsonp):
```
$(document).ready(function() {
$.getJSON("http://api.reddit.com?jsoncallback=?", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div><a href=\"" + url + "\">" + title + "</a><div>");
});
});
});
```
however it now stops working on both safari and firefox. The request is made but what is return from the server appears to be ignored.
Is this a problem with the code I am writing or with something the server is returning? How can I diagnose this problem?
*EDIT* Changed the address to the real one. | The URL you are pointing to (www.redit.com...) is not returning JSON! Not sure where the JSON syndication from reddit comes but you might want to start with the example from the [docs](http://docs.jquery.com/Ajax/jQuery.getJSON):
```
$(document).ready(function() {
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function (data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#redditbox");
if ( i == 4 ) return false;
});
});
```
});
(apologies for formatting)
**EDIT** Now I re read your post, I see you intended to go to api.reddit.com unfortunately you haven't got the right parameter name for the json callback parameter. You might need to further consult the reddit documentation to see if they support JSONP and what the name of the callback param should be. | JSONP is something that needs to be supported on the server. I can't find the documentation, but it appears that, if Reddit supports JSONP, it's not with the jsoncallback query variable.
What JSONP does, is wrap the JSON text with a JavaScript Function call, this allows the JSON text to be processed by any function you've already defined in your code. This function does need to be available from the Global scope, however. It appears that the JQuery getJSON method generates a function name for you, and assigns it to the jsoncallback query string variable. | jsonp request not working in firefox | [
"",
"javascript",
"jquery",
"json",
""
] |
When I pass an immutable type object(String, Integer,.. ) as final to a method I can achieve the characters of a C++ constant pointer. But how can I enforce such behavior in objects which are mutable?
```
public void someMethod(someType someObject){
/*
* code that modifies the someObject's state
*
*/
}
```
All I want is to prevent someMethod from modifying the state of someObject without making any change in someType. Is this possible? | No, I don't think this is possible. The normal approach is to create an adapter for SomeType where all the methods changing state throws UnsupportedOperationException. This is used by for instance java.util.Collections.unmodifiable\*-functions.
There are several approaches to this:
* you can let SomeType be an interface, and when you need it to be read only, just create a wrapper delegating all the read-methods to the original object and implementing all the write-methods to throw an exception.
* or you can create a subclass of SomeType overriding all the write methods
This will of course only give you run-time checking, not compiletime. If you want compile-time, you can let SomeType be an interface (or a superclass) with no write-methods, only read. | In the general case, no, it's not possible. In a very limited case, you can wrap someType in a class that provides the same interface (see Collections.unmodifiableList() for an example).
However, there's no equivalent to "pass a const pointer and the compiler will only allow you to call const functions on it". | How to get a c++ constant pointer equivalent in Java? | [
"",
"java",
"immutability",
"final",
"constants",
""
] |
I'm using SQL Server 2005.
I have a field that must either contain a unique value or a NULL value. I think I should be enforcing this with either a `CHECK CONSTRAINT` or a `TRIGGER for INSERT, UPDATE`.
Is there an advantage to using a constraint here over a trigger (or vice-versa)? What might such a constraint/trigger look like?
Or is there another, more appropriate option that I haven't considered? | Here is an alternative way to do it with a constraint. In order to enforce this constraint you'll need a function that counts the number of occurrences of the field value. In your constraint, simply make sure this maximum is 1.
Constraint:
```
field is null or dbo.fn_count_maximum_of_field(field) < 2
```
**EDIT I can't remember right now -- and can't check it either -- whether the constraint check is done before the insert/update or after. I think after with the insert/update being rolled back on failure. If it turns out I'm wrong, the 2 above should be a 1.**
Table function returns an int and uses the following select to derive it
```
declare @retVal int
select @retVal = max(occurrences)
from (
select field, count(*) as occurrences
from dbo.tbl
where field = @field
group by field
) tmp
```
This should be reasonably fast if your column as a (non-unique) index on it. | I create a view with the an index that ignores the nulls through the where clause...i.e. if you insert null into the table the view doesn't care but if you insert a non null value the view will enforce the constraint.
```
create view dbo.UniqueAssetTag with schemabinding
as
select asset_tag
from dbo.equipment
where asset_tag is not null
GO
create unique clustered index ix_UniqueAssetTag
on UniqueAssetTag(asset_tag)
GO
```
So now my equipment table has an asset\_tag column that allows multiple nulls but only unique non null values.
Note:
If using mssql 2000, you'll need to "[SET ARITHABORT ON](http://support.microsoft.com/kb/305333)" right before any insert, update or delete is performed on the table. Pretty sure this is not required on mssql 2005 and up. | Field value must be unique unless it is NULL | [
"",
"sql",
"sql-server",
"sql-server-2005",
"null",
""
] |
I've always been one to simply use:
```
List<String> names = new ArrayList<>();
```
I use the interface as the type name for *portability*, so that when I ask questions such as this, I can rework my code.
When should [`LinkedList`](https://docs.oracle.com/javase/9/docs/api/java/util/LinkedList.html) be used over [`ArrayList`](https://docs.oracle.com/javase/9/docs/api/java/util/ArrayList.html) and vice-versa? | **Summary** `ArrayList` with `ArrayDeque` are preferable in *many* more use-cases than `LinkedList`. If you're not sure — just start with `ArrayList`.
---
TLDR, in `ArrayList` accessing an element takes constant time [O(1)] and adding an element takes O(n) time [worst case]. In `LinkedList` inserting an element takes O(n) time and accessing also takes O(n) time but `LinkedList` uses more memory than `ArrayList`.
`LinkedList` and `ArrayList` are two different implementations of the `List` interface. `LinkedList` implements it with a doubly-linked list. `ArrayList` implements it with a dynamically re-sizing array.
As with standard linked list and array operations, the various methods will have different algorithmic runtimes.
For [`LinkedList<E>`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/LinkedList.html)
* `get(int index)` is *O(n)* (with *n/4* steps on average), but *O(1)* when `index = 0` or `index = list.size() - 1` (in this case, you can also use `getFirst()` and `getLast()`). **One of the main benefits of** `LinkedList<E>`
* `add(int index, E element)` is *O(n)* (with *n/4* steps on average), but *O(1)* when `index = 0` or `index = list.size() - 1` (in this case, you can also use `addFirst()` and `addLast()`/`add()`). **One of the main benefits of** `LinkedList<E>`
* `remove(int index)` is *O(n)* (with *n/4* steps on average), but *O(1)* when `index = 0` or `index = list.size() - 1` (in this case, you can also use `removeFirst()` and `removeLast()`). **One of the main benefits of** `LinkedList<E>`
* `Iterator.remove()` is *O(1)*. **One of the main benefits of** `LinkedList<E>`
* `ListIterator.add(E element)` is *O(1)*. **One of the main benefits of** `LinkedList<E>`
Note: Many of the operations need *n/4* steps on average, *constant* number of steps in the best case (e.g. index = 0), and *n/2* steps in worst case (middle of list)
For [`ArrayList<E>`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html)
* `get(int index)` is *O(1)*. **Main benefit of** `ArrayList<E>`
* `add(E element)` is *O(1)* amortized, but *O(n)* worst-case since the array must be resized and copied
* `add(int index, E element)` is *O(n)* (with *n/2* steps on average)
* `remove(int index)` is *O(n)* (with *n/2* steps on average)
* `Iterator.remove()` is *O(n)* (with *n/2* steps on average)
* `ListIterator.add(E element)` is *O(n)* (with *n/2* steps on average)
Note: Many of the operations need *n/2* steps on average, *constant* number of steps in the best case (end of list), *n* steps in the worst case (start of list)
`LinkedList<E>` allows for constant-time insertions or removals *using iterators*, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but finding a position in the list takes time proportional to the size of the list. Javadoc says *"operations that index into the list will traverse the list from the beginning or the end, whichever is closer"*, so those methods are *O(n)* (*n/4* steps) on average, though *O(1)* for `index = 0`.
`ArrayList<E>`, on the other hand, allow fast random read access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap. Also, if you add more elements than the capacity of the underlying array, a new array (1.5 times the size) is allocated, and the old array is copied to the new one, so adding to an `ArrayList` is *O(n)* in the worst case but constant on average.
So depending on the operations you intend to do, you should choose the implementations accordingly. Iterating over either kind of List is practically equally cheap. (Iterating over an `ArrayList` is technically faster, but unless you're doing something really performance-sensitive, you shouldn't worry about this -- they're both constants.)
The main benefits of using a `LinkedList` arise when you re-use existing iterators to insert and remove elements. These operations can then be done in *O(1)* by changing the list locally only. In an array list, the remainder of the array needs to be *moved* (i.e. copied). On the other side, seeking in a `LinkedList` means following the links in *O(n)* (*n/2* steps) for worst case, whereas in an `ArrayList` the desired position can be computed mathematically and accessed in *O(1)*.
Another benefit of using a `LinkedList` arises when you add or remove from the head of the list, since those operations are *O(1)*, while they are *O(n)* for `ArrayList`. Note that `ArrayDeque` may be a good alternative to `LinkedList` for adding and removing from the head, but it is not a `List`.
Also, if you have large lists, keep in mind that memory usage is also different. Each element of a `LinkedList` has more overhead since pointers to the next and previous elements are also stored. `ArrayLists` don't have this overhead. However, `ArrayLists` take up as much memory as is allocated for the capacity, regardless of whether elements have actually been added.
The default initial capacity of an `ArrayList` is pretty small (10 from Java 1.4 - 1.8). But since the underlying implementation is an array, the array must be resized if you add a lot of elements. To avoid the high cost of resizing when you know you're going to add a lot of elements, construct the `ArrayList` with a higher initial capacity.
If the data structures perspective is used to understand the two structures, a LinkedList is basically a sequential data structure which contains a head Node. The Node is a wrapper for two components : a value of type T [accepted through generics] and another reference to the Node linked to it. So, we can assert it is a recursive data structure (a Node contains another Node which has another Node and so on...). Addition of elements takes linear time in LinkedList as stated above.
An ArrayList is a growable array. It is just like a regular array. Under the hood, when an element is added, and the ArrayList is already full to capacity, it creates another array with a size which is greater than previous size. The elements are then copied from previous array to new one and the elements that are to be added are also placed at the specified indices. | Thus far, nobody seems to have addressed the memory footprint of each of these lists besides the general consensus that a `LinkedList` is "lots more" than an `ArrayList` so I did some number crunching to demonstrate exactly how much both lists take up for N null references.
Since references are either 32 or 64 bits (even when null) on their relative systems, I have included 4 sets of data for 32 and 64 bit `LinkedLists` and `ArrayLists`.
**Note:** The sizes shown for the `ArrayList` lines are for *trimmed lists* - In practice, the capacity of the backing array in an `ArrayList` is generally larger than its current element count.
**Note 2:** *(thanks BeeOnRope)* As CompressedOops is default now from mid JDK6 and up, the values below for 64-bit machines will basically match their 32-bit counterparts, unless of course you specifically turn it off.
---

---
The result clearly shows that `LinkedList` is a whole lot more than `ArrayList`, especially with a very high element count. If memory is a factor, steer clear of `LinkedLists`.
The formulas I used follow, let me know if I have done anything wrong and I will fix it up. 'b' is either 4 or 8 for 32 or 64 bit systems, and 'n' is the number of elements. Note the reason for the mods is because all objects in java will take up a multiple of 8 bytes space regardless of whether it is all used or not.
**ArrayList:**
`ArrayList object header + size integer + modCount integer + array reference + (array oject header + b * n) + MOD(array oject, 8) + MOD(ArrayList object, 8) == 8 + 4 + 4 + b + (12 + b * n) + MOD(12 + b * n, 8) + MOD(8 + 4 + 4 + b + (12 + b * n) + MOD(12 + b * n, 8), 8)`
**LinkedList:**
`LinkedList object header + size integer + modCount integer + reference to header + reference to footer + (node object overhead + reference to previous element + reference to next element + reference to element) * n) + MOD(node object, 8) * n + MOD(LinkedList object, 8) == 8 + 4 + 4 + 2 * b + (8 + 3 * b) * n + MOD(8 + 3 * b, 8) * n + MOD(8 + 4 + 4 + 2 * b + (8 + 3 * b) * n + MOD(8 + 3 * b, 8) * n, 8)` | When to use LinkedList over ArrayList in Java? | [
"",
"java",
"arraylist",
"collections",
"linked-list",
""
] |
I am modifying a SQL table through C# code and I need to drop a NOT NULL constraint if it exists. How do I check to see if it exists first? | ```
select is_nullable
from sys.columns
where object_id = OBJECT_ID('tablename')
and name = 'columnname';
``` | Well, you could check `syscolumns.isnullable` flag? Or more recently:
```
COLUMNPROPERTY(@tableId, 'ColumnName', 'AllowsNull')
```
Where @tableId is OBJECT\_ID('TableName') | How to check if NOT NULL constraint exists | [
"",
"c#",
"sql-server",
""
] |
```
public class doublePrecision {
public static void main(String[] args) {
double total = 0;
total += 5.6;
total += 5.8;
System.out.println(total);
}
}
```
The above code prints:
```
11.399999999999
```
How would I get this to just print (or be able to use it as) 11.4? | As others have mentioned, you'll probably want to use the [`BigDecimal`](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html) class, if you want to have an exact representation of 11.4.
Now, a little explanation into why this is happening:
The `float` and `double` primitive types in Java are [floating point](http://en.wikipedia.org/wiki/Floating_point) numbers, where the number is stored as a binary representation of a fraction and a exponent.
More specifically, a double-precision floating point value such as the `double` type is a 64-bit value, where:
* 1 bit denotes the sign (positive or negative).
* 11 bits for the exponent.
* 52 bits for the significant digits (the fractional part as a binary).
These parts are combined to produce a `double` representation of a value.
(Source: [Wikipedia: Double precision](http://en.wikipedia.org/wiki/Double_precision))
For a detailed description of how floating point values are handled in Java, see the [Section 4.2.3: Floating-Point Types, Formats, and Values](http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.3) of the Java Language Specification.
The `byte`, `char`, `int`, `long` types are [fixed-point](http://en.wikipedia.org/wiki/Fixed-point_arithmetic) numbers, which are exact representions of numbers. Unlike fixed point numbers, floating point numbers will some times (safe to assume "most of the time") not be able to return an exact representation of a number. This is the reason why you end up with `11.399999999999` as the result of `5.6 + 5.8`.
When requiring a value that is exact, such as 1.5 or 150.1005, you'll want to use one of the fixed-point types, which will be able to represent the number exactly.
As has been mentioned several times already, Java has a [`BigDecimal`](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html) class which will handle very large numbers and very small numbers.
From the Java API Reference for the `BigDecimal` class:
> Immutable,
> arbitrary-precision signed decimal
> numbers. A BigDecimal consists of an
> arbitrary precision integer unscaled
> value and a 32-bit integer scale. If
> zero or positive, the scale is the
> number of digits to the right of the
> decimal point. If negative, the
> unscaled value of the number is
> multiplied by ten to the power of the
> negation of the scale. The value of
> the number represented by the
> BigDecimal is therefore (unscaledValue
> × 10^-scale).
There has been many questions on Stack Overflow relating to the matter of floating point numbers and its precision. Here is a list of related questions that may be of interest:
* [Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?](https://stackoverflow.com/questions/177506/why-do-i-see-a-double-variable-initialized-to-some-value-like-214-as-2139999961)
* [How to print really big numbers in C++](https://stackoverflow.com/questions/240876/print-really-big-numbers)
* [How is floating point stored? When does it matter?](https://stackoverflow.com/questions/56947/how-is-floating-point-stored-when-does-it-matter)
* [Use float or decimal for accounting application dollar amount?](https://stackoverflow.com/questions/61872/use-float-or-decimal-for-accounting-application-dollar-amount)
If you really want to get down to the nitty gritty details of floating point numbers, take a look at [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). | When you input a double number, for example, `33.33333333333333`, the value you get is actually the closest representable double-precision value, which is exactly:
```
33.3333333333333285963817615993320941925048828125
```
Dividing that by 100 gives:
```
0.333333333333333285963817615993320941925048828125
```
which also isn't representable as a double-precision number, so again it is rounded to the nearest representable value, which is exactly:
```
0.3333333333333332593184650249895639717578887939453125
```
When you print this value out, it gets rounded *yet again* to 17 decimal digits, giving:
```
0.33333333333333326
``` | Retain precision with double in Java | [
"",
"java",
"floating-point",
"double",
"precision",
""
] |
Is it worth changing my code to be "more portable" and able to deal with the horror of magic quotes, or should I just make sure that it's always off via a .htaccess file?
```
if (get_magic_quotes_gpc()) {
$var = stripslashes($_POST['var']);
} else {
$var = $_POST['var'];
}
```
Versus
```
php_flag magic_quotes_gpc off
``` | Don't accommodate both situations. Two code paths = twice the headaches, plus there's a good chance you'll slip up and forget to handle both situations somewhere.
I used to check if magic quotes were on or off, and if they were on, undo their magic (as others in the thread have suggested). The problem with this is, you're changing the configured environment (no matter how stupid) that another programmer may expect.
These days I write code as though magic quotes are off, and in my main include/bootstrap/always-runs file I check if magic quotes are on or off. If they're on I throw an Exception that explains why this is a *bad thing*, and provide instructions on how they can be turned off.
This approach allows you to code to a single behavior, encourages other folks using your code to configure their servers correctly (magic quotes is going away in PHP 6), and if someone **really** needs magic quotes on they can handle your exception and take their lives into their own hands. | I would check the setting using `get_magic_quotes_gpc()` and do a big noisy exit with error. In the error inform the administrator of the proper setting. | Work around magic quotes, or just make sure they're off? | [
"",
"php",
"magic-quotes-gpc",
""
] |
I've been working on a program to read a dbf file, mess around with the data, and save it back to dbf. The problem that I am having is specifically to do with the writing portion.
```
private const string constring = "Driver={Microsoft dBASE Driver (*.dbf)};"
+ "SourceType=DBF;"
+ "DriverID=277;"
+ "Data Source=¿;"
+ "Extended Properties=dBASE IV;";
private const string qrystring = "SELECT * FROM [¿]";
public static DataTable loadDBF(string location)
{
string filename = ConvertLongPathToShort(Path.GetFileName(location));
DataTable table = new DataTable();
using(OdbcConnection conn = new OdbcConnection(RTN(constring, filename)))
{
conn.Open();
table.Load(new OdbcCommand(RTN(qrystring, filename), conn).ExecuteReader());
conn.Close();
}
return table;
}
private static string RTN(string stmt, string tablename)
{ return stmt.Replace("¿", tablename); }
[DllImport("Kernel32", CharSet = CharSet.Auto)]
static extern Int32 GetShortPathName(
String path, // input string
StringBuilder shortPath, // output string
Int32 shortPathLength); // StringBuilder.Capacity
public static string ConvertLongPathToShort(string longPathName)
{
StringBuilder shortNameBuffer;
int size;
shortNameBuffer = new StringBuilder();
size = GetShortPathName(longPathName, shortNameBuffer, shortNameBuffer.Capacity);
if (size >= shortNameBuffer.Capacity)
{
shortNameBuffer.Capacity = size + 1;
GetShortPathName(longPathName, shortNameBuffer, shortNameBuffer.Capacity);
}
return shortNameBuffer.ToString();
}
```
This is what I'm working with. I've tried a number of methods to write a new file, none of them productive. To be honest, while normally I would be an advocate of form and function, I just want the damn thing to work, this app is supposed to do one very specific thing, it's not going to simulate weather.
-=# Edit #=-
I've since discontinued the app due to time pressure, but before I scrapped it I realised that the particular format of dbf I was working with had no primary key information. This of course meant that I had to essentially read the data out to DataTable, mess with it, then wipe all the records in the dbf and insert everything from scratch.
Screw that for a lark. | For people coming here in the future: I wrote this today and it works well. The filename is without the extension (.dbf). The path (used for connection) is the directory path only (no file). You can add your datatable to a dataset and pass it in. Also, some of my datatypes are foxpro data types and may not be compatible with all DBF files. Hope this helps.
```
public static void DataSetIntoDBF(string fileName, DataSet dataSet)
{
ArrayList list = new ArrayList();
if (File.Exists(Path + fileName + ".dbf"))
{
File.Delete(Path + fileName + ".dbf");
}
string createSql = "create table " + fileName + " (";
foreach (DataColumn dc in dataSet.Tables[0].Columns)
{
string fieldName = dc.ColumnName;
string type = dc.DataType.ToString();
switch (type)
{
case "System.String":
type = "varchar(100)";
break;
case "System.Boolean":
type = "varchar(10)";
break;
case "System.Int32":
type = "int";
break;
case "System.Double":
type = "Double";
break;
case "System.DateTime":
type = "TimeStamp";
break;
}
createSql = createSql + "[" + fieldName + "]" + " " + type + ",";
list.Add(fieldName);
}
createSql = createSql.Substring(0, createSql.Length - 1) + ")";
OleDbConnection con = new OleDbConnection(GetConnection(Path));
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = createSql;
cmd.ExecuteNonQuery();
foreach (DataRow row in dataSet.Tables[0].Rows)
{
string insertSql = "insert into " + fileName + " values(";
for (int i = 0; i < list.Count; i++)
{
insertSql = insertSql + "'" + ReplaceEscape(row[list[i].ToString()].ToString()) + "',";
}
insertSql = insertSql.Substring(0, insertSql.Length - 1) + ")";
cmd.CommandText = insertSql;
cmd.ExecuteNonQuery();
}
con.Close();
}
private static string GetConnection(string path)
{
return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=dBASE IV;";
}
public static string ReplaceEscape(string str)
{
str = str.Replace("'", "''");
return str;
}
``` | What kind of dbf file are you working with? (There are several, e.g. dBase, FoxPro etc that are not 100% compatible.) I have gotten this to work with the Microsoft Visual FoxPro OleDB Provider from C#, you might give that a shot instead of using the dBase ODBC driver. | How can I save a DataTable to a .DBF? | [
"",
"c#",
"odbc",
"dbf",
""
] |
Let's say I have a class like this:
```
class ApplicationDefs{
public static final String configOption1 = "some option";
public static final String configOption2 = "some other option";
public static final String configOption3 = "yet another option";
}
```
Many of the other classes in my application are using these options. Now, I want to change one of the options alone and deploy just the compiled class.
But if these fields are in-lined in the consumer classes this becomes impossible right?
Is there any option to disable the in-lining of compile time constants? | You can use String.intern() to get the desired effect, but should comment your code, because not many people know about this. i.e.
```
public static final String configOption1 = "some option".intern();
```
This will prevent the compile time inline. Since it is referring to the exact same string that the compiler will place in the perm, you aren't creating anything extra.
As an alternative you could always do
```
public static final String configOption1 = "some option".toString();
```
which might be easier to read. Either way, since this is a bit odd you should comment the code to inform those maintaining it what you are doing.
**Edit:**
Found another SO link that gives references to the JLS, for more information on this.
[When to use intern() on String literals](https://stackoverflow.com/questions/1833581/when-to-use-intern) | No, it's part of the JLS, I'm afraid. This is touched upon, briefly, in Java Puzzlers but I don't have my copy to hand.
I guess you might consider having these constants defined in a properties file, and have the class that loads them periodically.
Reference: <http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313> | Are all compile-time constants inlined? | [
"",
"java",
"inlining",
"compile-time-constant",
""
] |
How to query to get count of matching words in a field, specifically in MySQL.
simply i need to get how many times a "search terms"appear in the field value.
for example, the value is "one two one onetwo" so when i search for word "one" it should give me 3
is it possible? because currently i just extract the value out of database and do the counting with server side language.
Thank you | You could create a function to be used directly within SQL, in order to do it all in one step.
Here is [a function which I found on the MySQL website](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html) :
```
delimiter ||
DROP FUNCTION IF EXISTS substrCount||
CREATE FUNCTION substrCount(s VARCHAR(255), ss VARCHAR(255)) RETURNS TINYINT(3) UNSIGNED LANGUAGE SQL NOT DETERMINISTIC READS SQL DATA
BEGIN
DECLARE count TINYINT(3) UNSIGNED;
DECLARE offset TINYINT(3) UNSIGNED;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET s = NULL;
SET count = 0;
SET offset = 1;
REPEAT
IF NOT ISNULL(s) AND offset > 0 THEN
SET offset = LOCATE(ss, s, offset);
IF offset > 0 THEN
SET count = count + 1;
SET offset = offset + 1;
END IF;
END IF;
UNTIL ISNULL(s) OR offset = 0 END REPEAT;
RETURN count;
END;
||
delimiter ;
```
You should use it like this :
```
SELECT substrCount('one two one onetwo', 'one') `count`; // Returns 3
``` | Are you looking to find a query that, given a list of words, returns the number of matching words in a database field?
eg:
Database table has
```
ID Terms
1 cat, dog, bird, horse
```
then running a check on the words "cat, horse" returns 2?
If so, I suggest you do your checking *outside* of SQL, in whatever language you're doing the rest of your processing in. SQL isn't designed for this level of processing.
You could *possibly* use a stored procedure to cycle through what words you're needing to check, but I doubt it would be efficient or highly effective.
Of course, if I'm misinterpreting your request, I could be all wrong =) | MySQL count matching words | [
"",
"sql",
"mysql",
"database",
""
] |
OK, this is an odd request, and it might not even be fully true... but I'm upgrading someone's system ... and they are using OSCommerce (from a long time ago).
It appears their variables are referrenced without a dollar sign in front of them (which is new to me). I haven't done PHP in about 7 years, and I've always used dollar signs.
Is there a setting that I can throw in PHP 5 that says to assume these are variables?
Example:
```
mysql_connect(DB_SERVER, DB_UserName, DB_Password);
```
in my day, that would be:
```
mysql_connect($DB_Server, etc, etc);
```
Their site has THOUSANDS of files... no I don't want to go put dollar signs in front of everything.
HELP!
Thanks, | I believe OSCommerce actually DEFINES these values, so the usage is correct (without the $).
Look for
```
define("DB_SERVER", "localhost");
```
or something similar.
In other words, do *not* go through and update these with a $ before if they're actually defined constants. | If i remember correctly a big difference is the lack of 'register\_globals' being default to 'ON'. You might need to change a lot of instances here $var should be $\_REQUEST['var'] or the appropriate $\_GET/$\_POST super globals.
And as far as constants are concerned you should access them as such:
```
constant('MY_CONSTANT')
```
This avoids PHP assuming that MY\_CONSTANT is a string if the constant is not defined. | PHP 3 to PHP 5 Upgrade... Variables in 3 didn't have $ in front... is there a setting for back compat? | [
"",
"php",
"variables",
""
] |
One of the core fields present on several of my app's major database tables needs to be changed from varchar(5) to varchar(8). The list of stored procedures that depend on these tables is extremely long, not to mention the changes that would have to be made in my Data Access Layer (ASP.NET 2.0 DataSet with TableAdapters).
Is there any way to automatically (and *safely*) change the Type of the all-important field and have the changes propagate to all the stored procedures / Data Access Layer calls that depend on it?
I'm using a SQL Server 2005 database. | You might be interested in this [essay](http://www.agiledata.org/essays/databaseRefactoring.html) by Scott Ambler on Database Refactoring. I think he also has a book on it. The basic idea, I believe, will be to introduce a new column with the proper width, copy existing data to the new column, implement a trigger to synchronize any new inserts/updates, migrate your SP/DAL to use the new column, then remove the old column when you are completely done. All new code uses the new column, obviously. I don't know of any automated way to do the updates to your SP/DAL, unfortunately. | While it doesn't help you much now you could (in the future) look to use a code generation tool that generates data access layers and any necessary (non-custom) stored procedures for you. I use .netTiers and changing something like a field name, data type or column size (like your situation) is very simple.
If you're interested in something like .netTiers you can check out their site [here](http://www.nettiers.com).
Unfortunately I don't know of a way to easily update everything you have. You may however be able to take care of all the database changes by using a tool like SQL Refactor from Redgate (see [here](http://www.red-gate.com/products/SQL_Refactor/index.htm)). | What's the best way to update my asp.net application / database after changing the schema? | [
"",
"c#",
"asp.net",
"sql-server-2005",
""
] |
My program will take arbitrary strings from the internet and use them for file names. Is there a simple way to remove the bad characters from these strings or do I need to write a custom function for this? | Ugh, I hate it when people try to guess at which characters are valid. Besides being completely non-portable (always thinking about Mono), both of the earlier comments missed more 25 invalid characters.
```
foreach (var c in Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(c, '-');
}
```
Or in VB:
```
'Clean just a filename
Dim filename As String = "salmnas dlajhdla kjha;dmas'lkasn"
For Each c In IO.Path.GetInvalidFileNameChars
filename = filename.Replace(c, "")
Next
'See also IO.Path.GetInvalidPathChars
``` | To strip invalid characters:
```
static readonly char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
// Builds a string out of valid chars
var validFilename = new string(filename.Where(ch => !invalidFileNameChars.Contains(ch)).ToArray());
```
To replace invalid characters:
```
static readonly char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
// Builds a string out of valid chars and an _ for invalid ones
var validFilename = new string(filename.Select(ch => invalidFileNameChars.Contains(ch) ? '_' : ch).ToArray());
```
To replace invalid characters (and avoid potential name conflict like Hell\* vs Hell$):
```
static readonly IList<char> invalidFileNameChars = Path.GetInvalidFileNameChars();
// Builds a string out of valid chars and replaces invalid chars with a unique letter (Moves the Char into the letter range of unicode, starting at "A")
var validFilename = new string(filename.Select(ch => invalidFileNameChars.Contains(ch) ? Convert.ToChar(invalidFileNameChars.IndexOf(ch) + 65) : ch).ToArray());
``` | Is there a way of making strings file-path safe in c#? | [
"",
"c#",
".net",
"string",
"filepath",
""
] |
How to truncate and shrink large log files in SQL Server 2005? How to apply truncation at regular intervals?
Is there any difference between truncation and shrinking?
Thanks in advance | Use DBCC SHRINKFILE and schedule it as a job that runs regularly (preferably during off-hours).
Just be aware that there is a performance hit from regularly growing and shrinking the log file. If you have the space, you may want to set the file size to the maximum that it normally grows to and just leave it. | Reliable shrinking is achieved by
* Backup (can be truncate only)
* Checkpoint
* Shrink | How to truncate and shrink log files? | [
"",
"sql",
"sql-server-2005",
"transaction-log",
""
] |
So I have this GIF file on my desktop (it's a 52 card deck of poker cards). I have been working on a program that cuts it up into little acm.graphics.GImages of each card. Now, however, I want to write those GImages or pixel arrays to a file so that I can use them later. I thought it would be as straight forward as writing .txt files, but a couple of Google searches later I am more confused than before.
So how do I go about making .gif files out of pixel arrays or GImages (I've got loads of both)? | Something along these lines should do the trick (modify the image type, dimensions and pixel array as appropriate):
```
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
WritableRaster raster = image.getRaster();
for ( i=0; i<width; i++ ) {
for ( j=0; j<height; j++ ) {
int[] colorArray = getColorForPixel(pixels[i][j]);
raster.setPixel(i, j, colorArray);
}
}
ImageIO.write(image, "gif", new File("CardImage"));
```
'getColorForPixel' will need to return an array representing the color for this pixel. In this case, using RGB, the colorArray will have three integers [red][green][blue].
Relevant javadoc: [WritableRaster](http://java.sun.com/javase/6/docs/api/java/awt/image/WritableRaster.html), [BufferedImage](http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html) and [ImageIO](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html). | I had to create GIF's out of Java Images for a university project, and I found this.
I would recommend Acme's Open-Source GifEncoder Class. Nice and easy to use, I still remember it over 2 years later.
Here's the link: [<http://www.acme.com/java/software/Acme.JPM.Encoders.GifEncoder.html>](http://www.acme.com/java/software/Acme.JPM.Encoders.GifEncoder.html)
And here's the G-Link: [<http://www.google.com/search?hl=en&q=acme+java+gif&btnG=Search>](http://www.google.com/search?hl=en&q=acme+java+gif&btnG=Search) | Writing a GIF file in Java | [
"",
"java",
"gif",
""
] |
I am writing a JSR-168 portlet that can be added to a container multiple times. Each container (Liferay, JBoss, etc.) has its own internal way of differentiating between multiple instantiations of the same portlet.
I, however, would like to uniquely identify my portlet instance inside the `doView()` method itself.
Is there any standard, JSR-168 mechanism to retrieve some unique identifier that's different for each instance of my portlet? I've seen various solutions where people [randomly](http://mus.purplecloud.net/portlets/portlet_messaging_1/documentation.php) [generate](http://www.archivum.info/jetspeed-dev@portals.apache.org/2008-08/msg00003.html) unique IDs and save them in the session, but I'd prefer a standard mechanism if one exists. | Portlet 1.0 (168) provides the [RenderResponse.getNamespace()](http://portals.apache.org/pluto/portlet-1.0-apidocs/javax/portlet/RenderResponse.html) method, which should be unique per portlet instance.
From spec: **PLT.12.3.4 Namespace encoding**:
> The getNamespace method must provide
> the portlet with a mechanism that
> ensures the uniqueness of the returned
> string in the whole portal page. For
> example, the getNamespace method would
> return a unique string that could be
> prefixed to a JavaScript variable name
> within the content generated by the
> portlet, ensuring its 5 uniqueness in
> the whole page. The getNamespace
> method must return the same value if
> invoked multiple times within a render
> request.
If you want to access it in *processAction*, you'll probably want to store it in the session or as an *actionURL* parameter.
If upgrading is an option, Portlet 2.0 (286) changes the underlying *PortletResponse* interface to provide the *getNamespace()* method and also adds a *PortletRequest.getWindowID()* method which might be of some use to you. | No, there is no common ID for the instance. I have implemented a portlet container myself, there is no per instance id in the public api - the container has one, of cause. The portlet session (`javax.portlet.PortletRequest#getPortletSession()`) is unique for one portlet (definition by tag in `portlet.xml`) and one user (`javax.servlet.http.HttpSession`), that is not enough for you.
So imho an id generated (can also be a simple (sync) counter in the portletl class) and stored in the portlet session is the only portable way. THe portlet class itself is typically shared beween instances, so the `java.lang.System#identityHashCode(Object x)` is also useless.
Why do you need it? | Uniquely identify an instance of a JSR-168 portlet | [
"",
"java",
"portlet",
""
] |
I'm using version 3.3.2, I know that regular Eclipse for Java does variable highlighting.
Notepad++ does it regardless of what language you're using (if you select any text, it highlights similar text)
I know it's not critically important, and a back/forward incremental search is an adequate workaround, but it would be nice to have.
**Update** Looks like I had PDT 1.03, (current version is 2.0), I have Eclipse 3.2.2. Needed to look in "Help -> Software Updates -> Manage Configuration", not just "Help -> About". | You can download new PDT 2.0 All-in-one together with Eclipse 3.4 - this feature as "mark occurences" is here an there is some new features. I use it now and found it stable.
<http://www.eclipse.org/pdt/downloads/> | I believe 'mark occurrences' is the option which is the closest of what you call 'syntax highlighting'
But [PHP Development Tools](http://www.eclipse.org/pdt/) (PDT) had not that feature in 2007, according to [this discussion](http://dev.eclipse.org/newslists/news.eclipse.tools.php/msg01188.html).
However [this bug](https://bugs.eclipse.org/bugs/show_bug.cgi?id=166178) says PDT1.1 has now the ability to mark occurrences.
Full description in this [pdf document](http://wiki.eclipse.org/images/c/c2/MarkOccurrences_(Dev2QA).pdf). | Can you enable variable highlighting with Eclipse PDT? | [
"",
"php",
"eclipse",
"ide",
"eclipse-pdt",
""
] |
I am trying to use the `System.Net.Mail.MailMessage` class in C# to create an email that is sent to a list of email addresses all via `BCC`. I do not want to include a `TO` address, but it seems that I must because I get an exception if I use an empty string for the `TO` address in the `MailMessage` constructor. The error states:
```
ArgumentException
The parameter 'addresses' cannot be an empty string.
Parameter name: addresses
```
Surely it is possible to send an email using only `BCC` as this is not a limitation of SMTP.
**Is there a way around this?** | I think if you comment out the whole `emailMessage.To.Add(sendTo);` line , it will send the email with `To` field empty. | Do the same thing you do for internal mail blasts where you don't want people to reply-to-all all the time.
Send it **to** yourself (or a dummy account), then add your BCC list. | Sending Mail via SMTP in C# using BCC without TO | [
"",
"c#",
"email",
"smtp",
"bcc",
""
] |
I have a MySQL query in which I want to include a list of ID's from another table. On the website, people are able to add certain items, and people can then add those items to their favourites. I basically want to get the list of ID's of people who have favourited that item (this is a bit simplified, but this is what it boils down to).
Basically, I do something like this:
```
SELECT *,
GROUP_CONCAT((SELECT userid FROM favourites WHERE itemid = items.id) SEPARATOR ',') AS idlist
FROM items
WHERE id = $someid
```
This way, I would be able to show who favourited some item, by splitting the idlist later on to an array in PHP further on in my code, however I am getting the following MySQL error:
> *1242 - Subquery returns more than 1 row*
I thought that was kind of the point of using `GROUP_CONCAT` instead of, for example, `CONCAT`? Am I going about this the wrong way?
---
Ok, thanks for the answers so far, that seems to work. However, there is a catch. Items are also considered to be a favourite if it was added by that user. So I would need an additional check to check if creator = userid. Can someone help me come up with a smart (and hopefully efficient) way to do this?
Thank you!
Edit: I just tried to do this:
```
SELECT [...] LEFT JOIN favourites ON (userid = itemid OR creator = userid)
```
And **idlist** is empty. Note that if I use `INNER JOIN` instead of `LEFT JOIN` I get an empty result. Even though I am sure there are rows that meet the ON requirement. | You can't access variables in the outer scope in such queries (can't use `items.id` there). You should rather try something like
```
SELECT
items.name,
items.color,
CONCAT(favourites.userid) as idlist
FROM
items
INNER JOIN favourites ON items.id = favourites.itemid
WHERE
items.id = $someid
GROUP BY
items.name,
items.color;
```
Expand the list of fields as needed (name, color...). | OP almost got it right. `GROUP_CONCAT` should be wrapping the columns in the subquery and not the [complete subquery](https://stackoverflow.com/a/4455991/838733) (I'm dismissing the separator because comma is the default):
```
SELECT i.*,
(SELECT GROUP_CONCAT(userid) FROM favourites f WHERE f.itemid = i.id) AS idlist
FROM items i
WHERE i.id = $someid
```
This will yield the desired result and also means that the accepted answer is partially wrong, because you can access outer scope variables in a subquery. | Using GROUP_CONCAT on subquery in MySQL | [
"",
"mysql",
"sql",
"group-concat",
"mysql-error-1242",
""
] |
We are experiencing an exceedingly hard to track down issue where we are seeing ClassCastExceptions *sometimes* when trying to iterate over a list of unmarshalled objects. The important bit is *sometimes*, after a reboot the particular code works fine. This seems to point in the direction of concurrency/timing/race condition. I can confirm that neither the JAXBContext, nor the marshallers and unmarshallers are being used concurrently. We've gone as far as serializing access to them through locking.
However, since we run on an OSGi platform where individual bundles are getting initialized asynchronously through Spring DM it can be that 2 different bundles are creating their JAXBContext at the same time.
In any case I would appreciate any pointers towards an explanation for what could cause these *intermittent* ClassCastExceptions. The intermittent is important since they indicate that the code itself is normally working fine but that some external factor seems to influence the behaviour.
Here's a specific example of the exception (note I removed the company specific stuff):
```
Caused by: java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to com.foobar.TunnelType
at com.foobar.NetMonitorImpl.getVpnStatus(NetMonitorImpl.java:180)
```
That method at line 180 is a for() construct looping over a Collection of TunnelType objects inside of an unmarshalled object (said unmarshalling works fine BTW).
Given that the actual object unmarshalling went fine, is it even physically possible for JAXB to leave ElementNSImpl objects inside of nested collections?
Runtime environment:
* JAXB 2.1
* OSGi
* Spring DM
* The JAXBContext is initialised with the ClassLoader of the bundle containing the classes to be marshalled/unmarshalled | Out of despair we turned to synchronizing on the `JAXBContext.class` object, seeing this as the only remaining possibility for some race condition and at least we have not been able to reproduce this issue again. Here's the critical code:
```
synchronized (JAXBContext.class) {
context = JAXBContext.newInstance(packageList, classLoader);
}
``` | I get this exception ONLY when I forget to tell JAXBContext
about ALL to-be-marshalled types it could be dealing with.
```
JAXBContext.newInstance(MyClass1.class,MyClass2.class, [...]);
``` | Intermittent ClassCastException from ElementNSImpl to own type during unmarshalling | [
"",
"java",
"exception",
"jaxb",
"race-condition",
"unmarshalling",
""
] |
Java 5 introduced generics, and they were added to many interfaces in the `java.lang` package. However, `Cloneable` did not get generics. I wonder why?
---
**Edit:** In reply to the answers of @Jon and @litb, and the comment of @Earwicker, I was thinking `Cloneable` might be:
```
public interface Cloneable<T> {
public T clone();
}
```
Here `T clone();` overrides `Object.clone()`, giving it a covariant type. I believe this would still be backwards compatible and increase type safety. So why not?
---
**Edit 2:** As can be seen in the answers (and comments) below, the interface suggested above would break backwards-compatibility. Since `Object.clone()` is `protected`, rewriting it in the interface would force all implementers to provide a `public` implementation, which class designers might not want to (i.e. they might opt to keep it `protected`). | The Cloneable interface doesn't contain any members. What would be the point of making it generic?
(If Cloneable contained the clone() method, it would make sense - but that's declared in java.lang.Object.)
EDIT: clone() is in java.lang.Object as it has an implementation (which does a field-by-field copy). A better design would be to have something like .NET's [MemberwiseClone()](http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx) as a protected method in Object, and then a public clone() method within the interface itself. I don't know why that design wasn't chosen.
(In .NET, [ICloneable](http://msdn.microsoft.com/en-us/library/system.icloneable.aspx) isn't generic because it existed before generics - the different nature of .NET generics prevents a previously non-generic type from becoming generic.)
In both Java and .NET, however, the "normal" cloning API is generally regarded as a bad thing, as it says nothing about what depth of cloning should be performed. | If `Cloneable` was `Cloneable<T>`, then it would be impossible to do this:
```
class A extends B implements Cloneable<A>
class B implements Cloneable<B>
```
You can't implement the same interface with different parameters, and class `A` implements `Cloneable<A>` and `Cloneable<B>`. | Why is Java's Cloneable Interface Not Generic? | [
"",
"java",
"generics",
""
] |
Is there some easy way to pad Strings in Java?
Seems like something that should be in some StringUtil-like API, but I can't find anything that does this. | Apache [`StringUtils`](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html) has several methods: [`leftPad`](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#leftPad(java.lang.String,%20int)), [`rightPad`](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#rightPad(java.lang.String,%20int)), [`center`](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#center(java.lang.String,%20int)) and [`repeat`](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#repeat(java.lang.String,%20int)).
But please note that — as others have mentioned and demonstrated in [this answer](https://stackoverflow.com/a/391978/1725096) — `String.format()` and the `Formatter` classes in the JDK are better options. Use them over the commons code. | Since Java 1.5, [`String.format()`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-) can be used to left/right pad a given string.
```
public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%" + n + "s", s);
}
...
public static void main(String args[]) throws Exception {
System.out.println(padRight("Howto", 20) + "*");
System.out.println(padLeft("Howto", 20) + "*");
}
```
And the output is:
```
Howto *
Howto*
``` | How can I pad a String in Java? | [
"",
"java",
"string",
"padding",
""
] |
I've trying to achieve something like this:
```
class Base
{
public:
Base(string S)
{
...
};
}
class Derived: Base
{
public:
int foo;
string bar()
{
return stringof(foo); // actually, something more complex
};
Derived(int f) : foo(f), Base(bar())
{
};
}
```
Now, this doesn't work as I want, because bar() is called in the Derived constructor before foo is initialized.
I considered adding a static function similar to bar() which takes foo as a parameter - and using that in the initialization list, but thought I'd ask if there were any other techniques that could be used to dig myself out of this one...
**Edit**: Thanks for feedback - here's how I was going to handle the static function. Not sure if the overload between a static and non-static function is too clever, but...
```
class Derived: Base
{
public:
int foo;
static string bar(int f)
{
return stringof(f); // actually, something more complex
}
string bar()
{
return bar(foo);
};
Derived(int f) : Base(bar(f)) , foo(f)
{
};
}
``` | Yes, using a function (static class method or regular function) that takes *foo* as a parameter and returns a string is a good solution. You can call this same function from Derived::bar to prevent code duplication. So, your constructor would look like this:
```
Derived(int f) : Base(stringof(f)), foo(f) {}
```
I place the call to the Base constructor first in the list to emphasize the order in which the initializations occur. The ordering of the initializer list has no effect as all class members are initialized in the order that they are declared in the class body.
This is a very clean, [functional](http://en.wikipedia.org/wiki/Functional_programming) approach to the problem. However, if you still would like to weigh alternatives then consider using [composition](http://en.wikipedia.org/wiki/Object_composition) instead of inheritance for the relationship between the Derived and Base classes:
```
class Base {
public:
Base(string S) { ... }
void bat() { ... }
};
class Derived {
Base *base;
int foo;
public:
Derived(int f) : base(NULL), foo(f) {
base = new Base(bar());
}
~Derived() {
delete base;
}
string bar() {
return stringof(foo); // actually, something more complex
}
void bat() {
base->bat();
}
};
```
You will need to consider the [pros](http://blogs.msdn.com/steverowe/archive/2008/04/28/prefer-composition-over-inheritance.aspx) and cons for your specific situation. With Derived holding a reference to Base you gain greater control over the initialization order. | You can only call static functions in the initializer list. The way you have it in your code:
```
class Derived: Base
{
public:
int foo;
string bar()
{
return stringof(foo); // actually, something more complex
};
Derived(int f) : foo(f), Base(bar())
{
};
}
```
Will still initialize Base first, and then foo. The order of how you write things in an constructor initializer list does not matter in any way. It will always construct in this order:
1. First, all virtual base classes
2. Then the non-virtual base classes in the order they appear in the base-classes list
3. Then all member objects in the order they are defined in the class definition.
Thus, you end up calling `stringof` with an uninitialized value. This problem is solved in [`boost::base_from_member`](http://www.boost.org/doc/libs/1_37_0/libs/utility/base_from_member.html). Also note that calling any nonstatic member function before all the constructor initializers of all base-classes completed is undefined behavior.
Calling static functions, however, is totally fine:
```
class Derived: Base
{
public:
int foo;
static string bar(int f)
{
return stringof(f); // actually, something more complex
};
Derived(int f) : Base(bar(f)), foo(f)
{
};
}
``` | How to pass method result as parameter to base class constructor in C++? | [
"",
"c++",
"inheritance",
"constructor",
"initialization",
"composition",
""
] |
I'm creating a function where I need to pass an object so that it can be modified by the function. What is the difference between:
```
public void myFunction(ref MyClass someClass)
```
and
```
public void myFunction(out MyClass someClass)
```
Which should I use and why? | `ref` tells the compiler that the object is initialized before entering the function, while `out` tells the compiler that the object will be initialized inside the function.
So while `ref` is two-ways, `out` is out-only. | The `ref` modifier means that:
1. The value is already set and
2. The method can read and modify it.
The `out` modifier means that:
1. The Value isn't set and can't be read by the method *until* it is set.
2. The method *must* set it before returning. | What's the difference between the 'ref' and 'out' keywords? | [
"",
"c#",
"reference",
"keyword",
"out",
"ref",
""
] |
I'm trying to use the `Html.DropDownList` extension method but can't figure out how to use it with an enumeration.
Let's say I have an enumeration like this:
```
public enum ItemTypes
{
Movie = 1,
Game = 2,
Book = 3
}
```
How do I go about creating a dropdown with these values using the `Html.DropDownList` extension method?
Or is my best bet to simply create a for loop and create the Html elements manually? | ## For MVC v5.1 use Html.EnumDropDownListFor
```
@Html.EnumDropDownListFor(
x => x.YourEnumField,
"Select My Type",
new { @class = "form-control" })
```
---
## For MVC v5 use EnumHelper
```
@Html.DropDownList("MyType",
EnumHelper.GetSelectList(typeof(MyType)) ,
"Select My Type",
new { @class = "form-control" })
```
---
## For MVC 5 and lower
I rolled Rune's answer into an extension method:
```
namespace MyApp.Common
{
public static class MyExtensions{
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
where TEnum : struct, IComparable, IFormattable, IConvertible
{
var values = from TEnum e in Enum.GetValues(typeof(TEnum))
select new { Id = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name", enumObj);
}
}
}
```
This allows you to write:
```
ViewData["taskStatus"] = task.Status.ToSelectList();
```
by `using MyApp.Common` | I know I'm late to the party on this, but thought you might find this variant useful, as this one also allows you to use descriptive strings rather than enumeration constants in the drop down. To do this, decorate each enumeration entry with a [System.ComponentModel.Description] attribute.
For example:
```
public enum TestEnum
{
[Description("Full test")]
FullTest,
[Description("Incomplete or partial test")]
PartialTest,
[Description("No test performed")]
None
}
```
Here is my code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;
...
private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
{
Type realModelType = modelMetadata.ModelType;
Type underlyingType = Nullable.GetUnderlyingType(realModelType);
if (underlyingType != null)
{
realModelType = underlyingType;
}
return realModelType;
}
private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };
public static string GetEnumDescription<TEnum>(TEnum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if ((attributes != null) && (attributes.Length > 0))
return attributes[0].Description;
else
return value.ToString();
}
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
{
return EnumDropDownListFor(htmlHelper, expression, null);
}
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Type enumType = GetNonNullableModelType(metadata);
IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();
IEnumerable<SelectListItem> items = from value in values
select new SelectListItem
{
Text = GetEnumDescription(value),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
};
// If the enum is nullable, add an 'empty' item to the collection
if (metadata.IsNullableValueType)
items = SingleEmptyItem.Concat(items);
return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
}
```
You can then do this in your view:
```
@Html.EnumDropDownListFor(model => model.MyEnumProperty)
```
\*\*EDIT 2014-JAN-23: Microsoft have just released MVC 5.1, which now has an EnumDropDownListFor feature. Sadly it does not appear to respect the [Description] attribute so the code above still stands.See [Enum section in](https://learn.microsoft.com/en-us/aspnet/mvc/overview/releases/mvc51-release-notes#Enum) Microsoft's release notes for MVC 5.1.
**Update: It does support the [Display](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.displayattribute) attribute `[Display(Name = "Sample")]` though, so one can use that.**
[Update - just noticed this, and the code looks like an extended version of the code here: https://blogs.msdn.microsoft.com/stuartleeks/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums/, with a couple of additions. If so, attribution would seem fair ;-)] | How do you create a dropdownlist from an enum in ASP.NET MVC? | [
"",
"c#",
"asp.net",
"asp.net-mvc",
""
] |
The `JFileChooser` seems to be missing a feature: a way to suggest the file name when saving a file (the thing that usually gets selected so that it would get replaced when the user starts typing).
Is there a way around this? | If I understand you correctly, you need to use the `setSelectedFile` method.
```
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setSelectedFile(new File("fileToSave.txt"));
jFileChooser.showSaveDialog(parent);
```
The file doesn't need to exist.
If you pass a File with an absolute path, `JFileChooser` will try to position itself in that directory (if it exists). | setSelectedFile doesn't work with directories as mentioned above, a solution is
```
try {
FileChooserUI fcUi = fileChooser.getUI();
fcUi.setSelectedFile(defaultDir);
Class<? extends FileChooserUI> fcClass = fcUi.getClass();
Method setFileName = fcClass.getMethod("setFileName", String.class);
setFileName.invoke(fcUi, defaultDir.getName());
} catch (Exception e) {
e.printStackTrace();
}
```
Unfortunately, `setFileName` is not included in the UI interface, thus the need to call it dynamically. Only tested on Mac. | How do I set a suggested file name using JFileChooser.showSaveDialog(...)? | [
"",
"java",
"swing",
"jfilechooser",
""
] |
I have a query which is meant to show me any rows in table A which have not been updated recently enough. (Each row should be updated within 2 months after "month\_no".):
```
SELECT A.identifier
, A.name
, TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL)) as MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
, table_b B
WHERE A.identifier = B.identifier
AND MONTH_NO > UPD_DATE
```
The last line in the WHERE clause causes an "ORA-00904 Invalid Identifier" error. Needless to say, I don't want to repeat the entire DECODE function in my WHERE clause. Any thoughts? (Both fixes and workarounds accepted...) | This is not possible directly, because chronologically, WHERE happens *before* SELECT, which always is the last step in the execution chain.
You can do a sub-select and filter on it:
```
SELECT * FROM
(
SELECT A.identifier
, A.name
, TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL)) as MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
, table_b B
WHERE A.identifier = B.identifier
) AS inner_table
WHERE
MONTH_NO > UPD_DATE
```
Interesting bit of info moved up from the comments:
> There should be no performance hit.
> Oracle does not need to materialize
> inner queries before applying outer
> conditions -- Oracle will consider
> transforming this query internally and
> push the predicate down into the inner
> query and will do so if it is cost
> effective. – [Justin Cave](https://stackoverflow.com/users/10397/justin-cave) | ```
SELECT A.identifier
, A.name
, TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL)) as MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A, table_b B
WHERE .identifier = B.identifier
HAVING MONTH_NO > UPD_DATE
``` | Using an Alias in a WHERE clause | [
"",
"sql",
"oracle",
"alias",
"decode",
"ora-00904",
""
] |
How can I remove duplicate values from an array in PHP? | Use [`array_unique()`](http://php.net/array_unique) for a one-dimensional array. From the PHP manual:
> Takes an input array and returns a new array without duplicate values.
>
> Note that keys are preserved. If multiple elements compare equal under the given flags, then the key and value of the first equal element will be retained.
>
> Note that `array_unique()` is not intended to work on multi dimensional arrays.
Example:
```
$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
```
If you want the values re-indexed, in addition, you should apply [`array_values`](https://php.net/manual/en/function.array-values.php). | Use `array_values(array_unique($array));`
`array_unique`: for unique array
`array_values`: for reindexing | How to remove duplicate values from an array in PHP | [
"",
"php",
"arrays",
"duplicate-data",
""
] |
I'm implementing a JAX-WS webservice that will be consumed by external Java and PHP clients.
The clients have to authenticate with a username and password stored in a database per client.
What authentication mechanism is best to use to make sure that misc clients can use it? | Basic WS-Security would work with both Java and PHP clients (amongst others) plugged in to JAAS to provide a database backend . How to implement that kind of depends on your container. Annotate your web service methods with the @RolesAllowed annotation to control which roles the calling user must have. All J2EE containers will provide some mechanism to specify against which JAAS realm users should be authenticated. In Glassfish for example, you can use the admin console to manage realms, users and groups. In your application.xml you then specify the realm and the group to role mappings.
[Here](http://docs.sun.com/app/docs/doc/819-3669/bnccv?a=view) are some details of how to achieve this on Glassfish
With [JBoss WS](http://jbossws.jboss.org/mediawiki/index.php?title=Authentication) in JBoss, it's even easier.
What JAX-WS implementation are you using and in which container? | For our Web Service authentication we are pursuing a twofold approach, in order to make sure that clients with different prerequisites are able to authenticate.
* Authenticate using a username and password parameter in the HTTP Request Header
* Authenticate using HTTP Basic Authentication.
Please note, that all traffic to our Web Service is routed over an SSL secured connection. Thus, sniffing the passwords is not possible. Of course one may also choose HTTP authentication with digest - see [this interesting site](http://java.boot.by/wcd-guide/ch05s03.html) for more information on this.
But back to our example:
```
//First, try authenticating against two predefined parameters in the HTTP
//Request Header: 'Username' and 'Password'.
public static String authenticate(MessageContext mctx) {
String s = "Login failed. Please provide a valid 'Username' and 'Password' in the HTTP header.";
// Get username and password from the HTTP Header
Map httpHeaders = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
String username = null;
String password = null;
List userList = (List) httpHeaders.get("Username");
List passList = (List) httpHeaders.get("Password");
// first try our username/password header authentication
if (CollectionUtils.isNotEmpty(userList)
&& CollectionUtils.isNotEmpty(passList)) {
username = userList.get(0).toString();
password = passList.get(0).toString();
}
// No username found - try HTTP basic authentication
if (username == null) {
List auth = (List) httpHeaders.get("Authorization");
if (CollectionUtils.isNotEmpty(auth)) {
String[] authArray = authorizeBasic(auth.get(0).toString());
if (authArray != null) {
username = authArray[0];
password = authArray[1];
}
}
}
if (username != null && password != null) {
try {
// Perform the authentication - e.g. against credentials from a DB, Realm or other
return authenticate(username, password);
} catch (Exception e) {
LOG.error(e);
return s;
}
}
return s;
}
/**
* return username and password for basic authentication
*
* @param authorizeString
* @return
*/
public static String[] authorizeBasic(String authorizeString) {
if (authorizeString != null) {
StringTokenizer st = new StringTokenizer(authorizeString);
if (st.hasMoreTokens()) {
String basic = st.nextToken();
if (basic.equalsIgnoreCase("Basic")) {
String credentials = st.nextToken();
String userPass = new String(
Base64.decodeBase64(credentials.getBytes()));
String[] userPassArray = userPass.split(":");
if (userPassArray != null && userPassArray.length == 2) {
String userId = userPassArray[0];
String userPassword = userPassArray[1];
return new String[] { userId, userPassword };
}
}
}
}
return null;
}
```
The first authentication using our predefined "Username" and "Password" parameters is in particular useful for our integration testers, who are using [SOAP-UI](http://www.soapui.org/) (Although I am not entirely sure whether one cannot get to work SOAP-UI with HTTP Basic Authentication too). The second authentication attempt then uses the parameters which are provided by HTTP Basic authentication.
In order to intercept every call to the Web Service, we define a handler on every endpoint:
```
@HandlerChain(file = "../../../../../handlers.xml")
@SchemaValidation(handler = SchemaValidationErrorHandler.class)
public class DeliveryEndpointImpl implements DeliveryEndpoint {
```
The handler.xml looks like:
```
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee">
<handler-chain>
<handler>
<handler-name>AuthenticationHandler</handler-name>
<handler-class>mywebservice.handler.AuthenticationHandler</handler-class>
</handler>
</handler-chain>
</handler-chains>
```
As you can see, the handler points to an AuthenticationHandler, which intercepts every call to the Web Service endpoint. Here's the Authentication Handler:
```
public class AuthenticationHandler implements SOAPHandler<SOAPMessageContext> {
/**
* Logger
*/
public static final Log log = LogFactory
.getLog(AuthenticationHandler.class);
/**
* The method is used to handle all incoming messages and to authenticate
* the user
*
* @param context
* The message context which is used to retrieve the username and
* the password
* @return True if the method was successfully handled and if the request
* may be forwarded to the respective handling methods. False if the
* request may not be further processed.
*/
@Override
public boolean handleMessage(SOAPMessageContext context) {
// Only inbound messages must be authenticated
boolean isOutbound = (Boolean) context
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!isOutbound) {
// Authenticate the call
String s = EbsUtils.authenticate(context);
if (s != null) {
log.info("Call to Web Service operation failed due to wrong user credentials. Error details: "
+ s);
// Return a fault with an access denied error code (101)
generateSOAPErrMessage(
context.getMessage(),
ServiceErrorCodes.ACCESS_DENIED,
ServiceErrorCodes
.getErrorCodeDescription(ServiceErrorCodes.ACCESS_DENIED),
s);
return false;
}
}
return true;
}
/**
* Generate a SOAP error message
*
* @param msg
* The SOAP message
* @param code
* The error code
* @param reason
* The reason for the error
*/
private void generateSOAPErrMessage(SOAPMessage msg, String code,
String reason, String detail) {
try {
SOAPBody soapBody = msg.getSOAPPart().getEnvelope().getBody();
SOAPFault soapFault = soapBody.addFault();
soapFault.setFaultCode(code);
soapFault.setFaultString(reason);
// Manually crate a failure element in order to guarentee that this
// authentication handler returns the same type of soap fault as the
// rest
// of the application
QName failureElement = new QName(
"http://yournamespacehere.com", "Failure", "ns3");
QName codeElement = new QName("Code");
QName reasonElement = new QName("Reason");
QName detailElement = new QName("Detail");
soapFault.addDetail().addDetailEntry(failureElement)
.addChildElement(codeElement).addTextNode(code)
.getParentElement().addChildElement(reasonElement)
.addTextNode(reason).getParentElement()
.addChildElement(detailElement).addTextNode(detail);
throw new SOAPFaultException(soapFault);
} catch (SOAPException e) {
}
}
/**
* Handles faults
*/
@Override
public boolean handleFault(SOAPMessageContext context) {
// do nothing
return false;
}
/**
* Close - not used
*/
@Override
public void close(MessageContext context) {
// do nothing
}
/**
* Get headers - not used
*/
@Override
public Set<QName> getHeaders() {
return null;
}
}
```
In the AuthenticationHandler we are calling the authenticate() method, defined further above. Note that we create a manual SOAP fault called "Failure" in case something goes wrong with the authentication. | JAX-WS authentication against a database | [
"",
"java",
"web-services",
"security",
""
] |
As the title says, whats the difference between
```
MyFunction = function() {
}
```
and
```
function MyFunction() {
}
```
Nothing?
**Duplicate:** [var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname) | The first form is actually a variable with an **anonymous function** assigned to it, the second is a **declared function**.
They're *almost* interchangeable, but have some differences: debuggers have a harder time with anons (because they lack a name) and the JS engine can directly access declared functions wherever they exist in the script, but anons can't be accessed until they have been assigned. | I think you mean
```
var MyFunction = function() {
}
```
And in many cases, there is little difference.
The var syntax is sometimes useful when you are inside some sort of wrapping class and want to be sure of your namespace (like in greasemonkey).
Also, I believe the function-are-constructors stuff (with .prototype, etc) do not work with the var syntax. | What is the difference between these 2 function syntax types | [
"",
"javascript",
""
] |
Assuming the file exists (using `os.path.exists(filename)` to first make sure that it does), how do I display the time a file was last modified? This is on Linux if that makes any difference. | [os.stat()](http://docs.python.org/library/os.html#os.stat)
```
import os
filename = "/etc/fstab"
statbuf = os.stat(filename)
print("Modification time: {}".format(statbuf.st_mtime))
```
Linux does not record the creation time of a file ([for most fileystems](https://unix.stackexchange.com/q/24441/61642)). | ```
>>> import os
>>> f = os.path.getmtime('test1.jpg')
>>> f
1223995325.0
```
since the beginning of (epoch) | How do I get the time a file was last modified in Python? | [
"",
"python",
"file",
"time",
""
] |
I am attempting to mock a call to an indexed property. I.e. I would like to moq the following:
```
object result = myDictionaryCollection["SomeKeyValue"];
```
and also the setter value
```
myDictionaryCollection["SomeKeyValue"] = myNewValue;
```
I am doing this because I need to mock the functionality of a class my app uses.
Does anyone know how to do this with MOQ? I've tried variations on the following:
```
Dictionary<string, object> MyContainer = new Dictionary<string, object>();
mock.ExpectGet<object>( p => p[It.IsAny<string>()]).Returns(MyContainer[(string s)]);
```
But that doesn't compile.
Is what I am trying to achieve possible with MOQ, does anyone have any examples of how I can do this? | It appears that what I was attempting to do with MOQ is not possible.
Essentially I was attempting to MOQ a HTTPSession type object, where the key of the item being set to the index could only be determined at runtime. Access to the indexed property needed to return the value which was previously set. This works for integer based indexes, but string based indexes do not work. | It's not clear what you're trying to do because you don't show the declaration of the mock. Are you trying to mock a dictionary?
`MyContainer[(string s)]` isn't valid C#.
This compiles:
```
var mock = new Mock<IDictionary>();
mock.SetupGet( p => p[It.IsAny<string>()]).Returns("foo");
``` | How to MOQ an Indexed property | [
"",
"c#",
"tdd",
"mocking",
"moq",
""
] |
Using jQuery, **how do you match elements that are prior to the current element in the DOM tree?** Using `prevAll()` only matches previous siblings.
eg:
```
<table>
<tr>
<td class="findme">find this one</td>
</tr>
<tr>
<td><a href="#" class="myLinks">find the previous .findme</a></td>
</tr>
<tr>
<td class="findme">don't find this one</td>
</tr>
</table>
```
In my specific case, I'll be searching for the *first* `.findme` element prior to the link clicked. | Ok, here's what I've come up with - hopefully it'll be useful in many different situations. It's 2 extensions to jQuery that I call `prevALL` and `nextALL`. While the standard `prevAll()` matches previous siblings, `prevALL()` matches ALL previous elements all the way up the DOM tree, similarly for `nextAll()` and `nextALL()`.
I'll try to explain it in the comments below:
```
// this is a small helper extension i stole from
// http://www.texotela.co.uk/code/jquery/reverse/
// it merely reverses the order of a jQuery set.
$.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
// create two new functions: prevALL and nextALL. they're very similar, hence this style.
$.each( ['prev', 'next'], function(unusedIndex, name) {
$.fn[ name + 'ALL' ] = function(matchExpr) {
// get all the elements in the body, including the body.
var $all = $('body').find('*').andSelf();
// slice the $all object according to which way we're looking
$all = (name == 'prev')
? $all.slice(0, $all.index(this)).reverse()
: $all.slice($all.index(this) + 1)
;
// filter the matches if specified
if (matchExpr) $all = $all.filter(matchExpr);
return $all;
};
});
```
usage:
```
$('.myLinks').click(function() {
$(this)
.prevALL('.findme:first')
.html("You found me!")
;
// set previous nodes to blue
$(this).prevALL().css('backgroundColor', 'blue');
// set following nodes to red
$(this).nextALL().css('backgroundColor', 'red');
});
```
---
*edit* - function rewritten from scratch. I just thought of a much quicker and simpler way to do it. Take a look at the edit history to see my first iteration.
*edit again* - found an easier way to do it! | Presumably you are doing this inside an onclick handler so you have access to the element that was clicked. What I would do is do a prevAll to see if it is at the same level. If not, then I would do a parent().prevAll() to get the previous siblings of the parent element, then iterate through those backwards, checking their contents for the desired element. Continue going up the DOM tree until you find what you want or hit the root of the DOM. This a general algorithm.
If you know that it is inside a table, then you can simply get the row containing the element clicked and iterate backwards through the rows of the table from that row until you find one that contains the element desired.
I don't think there is a way to do it in one (chained) statement. | jQuery to find all previous elements that match an expression | [
"",
"javascript",
"jquery",
""
] |
i wind up having about 20 different parameters in the constructor of the model class, one for each service? Is this normal or a sign that something is off. | I think, categorically, that your controller is interacting with too many services. I've not seen your code - so I'm going off assumptions - but it seems to me that your controller is composing business logic by calling numerous "small" services, rather than drawing on fewer, "larger" services that compose business logic from the smaller services.
Have a look around for information about "orchestration services" vs "entity" or "capability" services and you'll see what I mean. If you create orchestration services that provide your controllers with the logic they require, your architecture is improved because your controllers really should not contain any business logic at all.
I really think that the number of services you consume is the issue here. IoC containers may go some way to resolve how you bind types to your injection parameters etc., but I think the problem is your architecture at this point. | You might try consolidating some services or think about refactoring the controller-view parts in to smaller scoped components. Also, a dependency injection style framework like Spring can help with things like this. | MVC lots of services make the controller constructor very large . | [
"",
"c#",
"mvp",
""
] |
I'm tackling project euler's [problem 220](http://projecteuler.net/index.php?section=problems&id=220) (looked easy, in comparison to some of the
others - thought I'd try a higher numbered one for a change!)
So far I have:
```
D = "Fa"
def iterate(D,num):
for i in range (0,num):
D = D.replace("a","A")
D = D.replace("b","B")
D = D.replace("A","aRbFR")
D = D.replace("B","LFaLb")
return D
instructions = iterate("Fa",50)
print instructions
```
Now, this works fine for low values, but when you put it to repeat higher then you just get a "Memory error". Can anyone suggest a way to overcome this? I really want a string/file that contains instructions for the next step. | Python strings are not going to be the answer to this one. Strings are stored as immutable arrays, so each one of those replacements creates an entirely new string in memory. Not to mention, the set of instructions after 10^12 steps will be at least 1TB in size if you store them as characters (and that's with some minor compressions).
Ideally, there should be a way to mathematically (hint, there is) generate the answer on the fly, so that you never need to store the sequence.
Just use the string as a guide to determine a method which creates your path. | The trick is in noticing which patterns emerge as you run the string through each iteration. Try evaluating `iterate(D,n)` for n between 1 and 10 and see if you can spot them. Also feed the string through a function that calculates the end position and the number of steps, and look for patterns there too.
You can then use this knowledge to simplify the algorithm to something that doesn't use these strings at all. | How to work with very long strings in Python? | [
"",
"python",
""
] |
Is there anything better than a [Trie](http://en.wikipedia.org/wiki/Trie) for this situation?
* Storing a list of ~100k English words
* Needs to use minimal memory
* Lookups need to be reasonable, but don't have to be lightning fast
I'm working with Java, so my first attempt was to just use a Set<String>. However, I'm targeting a mobile device and already running low on memory. Since many English words share common prefixes, a trie seems like a decent bet to save some memory -- anyone know some other good options?
EDIT - More info - The data structure will be used for two operations
* Answering: Is some word XYZ in the list?
* Generating the neighborhood of words around XYZ with one letter different
Thanks for the good suggestions | What are you doing? If it's spell checking, you could use a bloom filter - see this [code kata](http://codekata.pragprog.com/2007/01/kata_five_bloom.html). | One structure I saw for minimizing space in a spelling dictionary was to encode each word as:
* the number of characters (a byte) in common with the last; and
* the new ending.
So the word list
```
HERE would encode as THIS
sanctimonious 0,sanctimonious
sanction 6,on
sanguine 3,guine
trivial 0,trivial
```
You're saving 7 bytes straight up there (19%), I suspect the saving would be similar for a 20,000 word dictionary just due to the minimum distances between (common prefixes of) adjacent words.
For example, I ran a test program over a sorted dictionary and calculated old storage space as the word length plus one (for terminator), and the new storage space as one for the common length, the uncommon suffix length and one for a terminator. Here's the final part of that test program showing that you could well over 50%:
```
zwiebacks -> zygote common= old=1044662 new=469762 55.0%
zygote -> zygotes common=zygote old=1044670 new=469765 55.0%
zygotes -> zygotic common=zygot old=1044678 new=469769 55.0%
zygotic -> zymase common=zy old=1044685 new=469775 55.0%
zymase -> zymogenic common=zym old=1044695 new=469783 55.0%
zymogenic -> zymology common=zymo old=1044704 new=469789 55.0%
zymology -> zymolysis common=zymol old=1044714 new=469795 55.0%
zymolysis -> zymoplastic common=zymo old=1044726 new=469804 55.0%
zymoplastic -> zymoscope common=zymo old=1044736 new=469811 55.0%
zymoscope -> zymurgy common=zym old=1044744 new=469817 55.0%
zymurgy -> zyzzyva common=zy old=1044752 new=469824 55.0%
zyzzyva -> zyzzyvas common=zyzzyva old=1044761 new=469827 55.0%
```
To speed lookup, there was a 26-entry table in memory which held the starting offsets for words beginning with a, b, c, ..., z. The words at these offsets always had 0 as the first byte as they had no letters in common with the previous word.
This seems to be sort of a trie but without the pointers, which would surely get space-expensive if every character in the tree had a 4-byte pointer associated with it.
Mind you, this was from my CP/M days where memory was much scarcer than it is now. | Space-Efficient Data Structure for Storing a Word List? | [
"",
"java",
"data-structures",
""
] |
I got a table with a custom TableCellEditor (extending DefaultCellEditor) with a JFormattedTextField as the editor component.
Now I got problem: when I press a separate button while editing. When the button is pressed, the editor remains "open and active" while I'd want it to stop editing so that the changes made would be available for the operations caused by the button.
So how to cause the editing to be stopped when a distinct button is pressed. I tried *setFocusLostBehavior(JFormattedTextField.COMMIT)* for the *JFormattedTextField* but it didn't seem to have effect.
Hope somebody has some good ideas =) | You may try
`jtable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);` | Thanks asalamon74, that works quite nicely.
There's debate over the thing at Sun Bug Database : [Bug 4724980: JTable: Add API to control what happens to edits when table loses focus.](https://bugs.java.com/bugdatabase/view_bug?bug_id=4724980) (also other bug entries are found). The terminateEditOnFocusLost turns on "commit-or-cancel" behaviour that can be seen at the Java sources at the class *JTable$CellEditorRemover*
And yes, it's somewhat strange that it isn't documented at the APIs etc... | How to stop editing with DefaultCellEditor when a separate JBtton is pressed | [
"",
"java",
"swing",
"focus",
"jtable",
"tablecelleditor",
""
] |
I am writing a console program in C#.
Is there a way I can use a Console.Clear() to only clear certain things on the console screen?
Here's my issue:
I have a logo (I put it on screen using Console.WriteLine()) and a 2d array which I want to keep constant and clear everything below it. | You could use a custom method to clear parts of the screen...
```
static void Clear(int x, int y, int width, int height)
{
int curTop = Console.CursorTop;
int curLeft = Console.CursorLeft;
for (; height > 0;)
{
Console.SetCursorPosition(x, y + --height);
Console.Write(new string(' ',width));
}
Console.SetCursorPosition(curLeft, curTop);
}
``` | **Edit**: The answer [here](https://stackoverflow.com/questions/377927/c-console-consoleclear-problem#378036) shows how you can manipulate the console much more powerfully than I was aware. What I originally wrote still applies, and might be useful if you don't have these facilities available, perhaps in a different language.
---
Store the logo and the initially generated state of the array and then when you clear the console write out the saved values again, rather than using the same generation procedure.
As others have said, the console isn't designed for this kind of operation so you have to work around it.
Another option might be to write to a string or a string builder rather than to the console directly, then whenever the console needs updating, clear it's output and write your "output" string / stream to the console. This would let you perform string operations/ regexes etc. on your output text to remove / leave specific things in place.
However, this would involve a lot of console overhead as you would end up reprinting the entire output on every update.
A solution to THAT might be to keep a parallel string / stream representation of what you write to the console, then when you need to clear you can clear the string representation, clear the console, then write the string out to the console again. That way you would add only an additional-write operation to your usual write, and the major extra work would happen only when you cleared the console.
Whatever you do, writing to the console is never a fast operation, and if you are doing lots of operations where stuff is written to the console, it can be a significant drag on the performance of your application. | c# console, Console.Clear problem | [
"",
"c#",
"console-application",
""
] |
Good morning,
I am working on a C# winform application that is using validation for the controls. The issue I'm having is that when a user clicks into a textbox and attempts to click out, the validation fires and re-focuses the control, basically the user cannot click out of the control to another control.
My desired result is to have ALL of the controls on the form validate when the user clicks the submit button. I would like to have the errorProvider icon appear next to the fields that are in error and allow the user to correct them as they see fit.
My question is, how do I setup a control to allow a user to click outside of it when there is an error. I'd like the user to have the ability to fill in the rest of the form and come back to the error on their own instead of being forced to deal with it immediately.
Thank you in advance for any help and advice, | The simplest way would be just to put all the validation in the Submit button handler, instead of having it in the controls. | The form has AutoValidate property, that can be set to allow focus change | Textbox validation, focus switching issue | [
"",
"c#",
"winforms",
"validation",
"controls",
"focus",
""
] |
There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread. | I'm not sure how cross-platform this might be, but using signals and alarm might be a good way of looking at this. With a little work you could make this completely generic as well and usable in any situation.
<http://docs.python.org/library/signal.html>
So your code is going to look something like this.
```
import signal
def signal_handler(signum, frame):
raise Exception("Timed out!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(10) # Ten seconds
try:
long_function_call()
except Exception, msg:
print "Timed out!"
``` | An improvement on @rik.the.vik's answer would be to use the [`with` statement](http://www.python.org/dev/peps/pep-0343/) to give the timeout function some syntactic sugar:
```
import signal
from contextlib import contextmanager
class TimeoutException(Exception): pass
@contextmanager
def time_limit(seconds):
def signal_handler(signum, frame):
raise TimeoutException("Timed out!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
try:
with time_limit(10):
long_function_call()
except TimeoutException as e:
print("Timed out!")
``` | How to limit execution time of a function call? | [
"",
"python",
""
] |
I'm getting some really wierd linking errors from a class I wrote. I am completely unable to find anything that will describe what is happening.
Visual Studio (Windows XP)
> players.obj : error LNK2019: unresolved external symbol "public: \_\_thiscall TreeNode::TreeNode(void)" (??0?$TreeNode@VPlayer@@@@QAE@XZ) referenced in function "public: \_\_thiscall PlayerList::PlayerList(void)" (??0PlayerList@@QAE@XZ)
Xcode (OSX 10.5)
> Undefined symbols: "TreeNode::~TreeNode()", referenced from: PlayerList::~PlayerList()in players.o
Header File: generics.h
```
class TreeNode : public BaseNode{
public:
const static int MAX_SIZE = -1; //-1 means any size allowed.
const static int MIN_SIZE = 0;
//getters
int size() const;
vector<C*> getChildren() const;
//setters
void setChildren(vector<C*> &list);
//Serialization
virtual void display(ostream &out) const;
virtual void read(istream &in);
virtual void write(ostream &out) const;
//Overrides so SC acts like an array of sorts.
virtual C* get(int id) const;
virtual int get(C *child) const;
virtual bool has(C *child) const;
virtual C* pop(int id);
virtual void push(C *child);
virtual TreeNode& operator<< (C *child); //append
virtual void remove(int id); //Clears memory
virtual void remove(C *child); //Clears memory
//Initalizers
TreeNode();
TreeNode(istream &in);
TreeNode(long id, istream &in);
TreeNode(BaseNode* parent, istream &in);
TreeNode(long id, BaseNode* parent);
TreeNode(long id, BaseNode* parent, istream &in);
~TreeNode();
string __name__() const{ return "TreeNode"; }
protected:
void clearChildren();
void initalizeChildren();
vector<C*> _children;
};
```
Code from a subclass of TreeNode
```
PlayerList::PlayerList() : TreeNode<Player>(){}
PlayerList::PlayerList(istream &in) : TreeNode<Player>(in){}
PlayerList::~PlayerList(){}
``` | When you define your template in a .cpp file, you have to explicitly instantiate it with all the types / template parameters known the template will be used beforehand like this (put it in the .cpp file):
```
template class TreeNode<Player>;
```
If you don't know with which template parameters the template will be used, you have to put all the definitions into the header. like
```
template<typename T>
class TreeNode {
public:
TreeNode() /* now, also put the code into here: */ { doSomething(); }
};
```
The reason is that when you are going to use the template from somewhere, the compiler has to be able to generate the code for that specific instantiation of the template. But if you place the code into a .cpp file and compile it, there is no way for the compiler to get its hands on the code to generate the instantiation (except when using the infamous `export` keyword, which is only supported by very few compilers).
This is also an entry in my C++ Pitfalls answer: [What C++ pitfalls should I avoid?](https://stackoverflow.com/questions/30373/what-c-pitfalls-should-i-avoid#293047) | Well you are declaring ~TreeNode(), but are you defining it?
When you declare the destructor you stop the compiler from generating one for you, but you must define it somewhere, even if it is empty.
If your intent was to have an empty destructor you have two options:
-Remove the declaration of ~TreeNode() entirely, and rely on the self generated destructor
-Define it as empty. Inling would be very nice here, IE. ~TreeNode() {}; | C++ Linking Errors: Undefined symbols using a templated class | [
"",
"c++",
"linker",
""
] |
In a software-project written in java you often have resources, that are part of the project and should be included on the classpath. For instance some templates or images, that should be accessible through the classpath (getResource). These files should be included into a produced JAR-file.
It's clear that these resources should be added to the revision-control-system. But in which directory you put these files? Parallel to the java-source-files or in another directory that also reproduces the needed package-structure? | I prefer your latter solution: a separate directory that mimicks the source code’s package structure. This way they won’t clobber your source code but will be right next to the compiled class files in the packaged JAR file. | [Maven](http://maven.apache.org/) puts them into src/main/resources/ (Java code would go to src/main/java/). The main reason is that Maven can compile code in various languages and it makes sense to keep them separate so one compile isn't confused by files for another.
In the case of resources, Maven will replace variables in them before they are added to a Jar, so they are "compiled" sources as well. | How you organize non-source-resources available at the classpath in your java-project? | [
"",
"java",
"resources",
"classpath",
"structure",
""
] |
I am trying to implement a ListView data control for displaying and editing lookup table/ application level variables. There are multiple entity classes which can be bound to the ListView, so the ItemTemplate needs to be dynamically bound to the selected entity object.
For example i have:
```
AddressType { AddressTypeId, AddressTypeDescription},
PhoneType { PhoneTypeId, PhoneType},
MarriageStatusType { MarriageStatusId, marriageStatusType}
```
Those generated entity objects prevent me from simply doing something like the following snippet, because the ID and Type properties are different on each business object.
```
<ListView>
...
<itemTemplate>
<tr>
<td runat="server" id="tdId"> <%# Eval("ID") %> </td>
<td runat="server" id="tdType"> <%# Eval("TypeNameDescription") %> </td>
</tr>
</itemTemplate>
...
</ListView>
```
I am trying to discover :
1. How to iterate over the ListView Items to insert the appropriate property value into the server side html td tags.
2. How to use Databinder.Eval on the ListView items to insert that property value.
Thanks in advance! | Ok in answer to your questions:
* You can iterate over the ListViewItems by using the OnItemDataBound event in the parent ListView. You can then use this to databind nested child ListViews (or insert Html or manipulate the contents of the list in any way you need). Make sure you use ListViewItemEventArgs in your code behind handler so you can access the databound item easily...
* You can use Databinder.Eval to dynamically populate a Repeater in your ListView using something like this (note 'GetChildCategoryData' is a code behind method):
Hope it helps..
```
<asp:ListView ID="parentList" runat="server">
<ItemTemplate>
<asp:Repeater ID="childData" runat="server" DataSource='<%# GetChildCategoryData(DataBinder.Eval(Container.DataItem, "parentcategoryID")) %>'>.. </asp:Repeater>
</ItemTemplate>
</asp:ListView>
``` | maybe your answer is to bind a repeater inside the itemTemplate
and the repeater will get the datasource of the <%# Eval("DataDictionary") %>. | Asp.NET ListView Data Control Dynamically Databind | [
"",
"c#",
"asp.net",
"data-binding",
"listview",
""
] |
I've saved an entire webpage's html to a string, and now **I want to grab the "href" values** from the links, preferably with the ability to save them to different strings later. What's the best way to do this?
I've tried saving the string as an .xml doc and parsing it using an XPathDocument navigator, but (surprise surprise) it doesn't navigate a not-really-an-xml-document too well.
Are regular expressions the **best** way to achieve what I'm trying to accomplish? | Regular expressions are one way to do it, but it can be problematic.
Most HTML pages can't be parsed using standard html techniques because, as you've found out, most don't validate.
You could spend the time trying to integrate [HTML Tidy](http://tidy.sourceforge.net/) or a similar tool, but it would be much faster to just build the regex you need.
**UPDATE**
At the time of this update I've received 15 up and 9 downvotes. I think that maybe people aren't reading the question nor the comments on this answer. All the OP wanted to do was grab the href values. **That's it.** From that perspective, a simple regex is just fine. If the author had wanted to parse other items then there is no way I would recommend regex as I stated at the beginning, it's problematic at best. | I can recommend the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack). I've used it in a few cases where I needed to parse HTML and it works great. Once you load your HTML into it, you can use [XPath](http://msdn.microsoft.com/en-us/library/ms256115.aspx) expressions to query the document and get your anchor tags (as well as just about anything else in there).
```
HtmlDocument yourDoc = // load your HTML;
int someCount = yourDoc.DocumentNode.SelectNodes("your_xpath").Count;
``` | C# - Best Approach to Parsing Webpage? | [
"",
"c#",
"html",
"xml",
"html-content-extraction",
""
] |
Is there a way to debug javascript using Safari 3.2 in Windows Vista?
I found a [link](http://pietschsoft.com/post/2007/12/Safari-3-for-Windows-Enable-JavaScript-Debugging.aspx) to a debugger named Drosera but I can't get it to work because the information seams to be outdated. | Well, apart from the **Error Console** that can be opened from the Develop menu (which in turn can be enabled in (Prefences / Advanced / Show Develop menu in menu bar) there aren't many javascript debugging options in Safari AFAIK.
Still, the error console is quite useful as it shows javascript errors and also lets you to execute arbitrary Javascript statements.
Since you are on Windows anyway, you could try using the inbuilt Javascript debugger of [Google Chrome](http://www.google.com/chrome), which is a browser very similar to Safari (although the Javascript engine is different). | I stumbled across this question via google - although it's rather old, none of the answers are quite right, (due to safari being updated to 5.1 since this question was asked)
Enable the `develop menu` as DrJokepu mentioned:
> Prefences / Advanced / Show Develop menu in menu bar
Now you'll see an option in the page menu to `Show Web Inspector`, which gives you very similar tools to those found in chrome, ([Details here](http://developer.apple.com/technologies/safari/developer-tools.html)). You can also start debugging javascript directly from the develop menu. | Debugging javascript in Safari for Windows | [
"",
"javascript",
"windows",
"windows-vista",
"safari",
"cross-browser",
""
] |
What is the best (date format independent way) in PHP to calculate difference in days between two dates in specified format.
I tried the following function:
```
function get_date_offset($start_date, $end_date)
{
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
return round(($end_time-$start_time)/(3600*24));
}
```
It works ok on linux box, but when running under windows strtotime returns ''.
**EDIT**:
Input date is in **mm/dd/yyyy** format, but I would like to make it accept $format as a parameter.
I need only difference in days. | If you do not want or you cannot use Zend Framework or Pear package try this function i hope this would help:
```
function dateDifference($date1, $date2)
{
$d1 = (is_string($date1) ? strtotime($date1) : $date1);
$d2 = (is_string($date2) ? strtotime($date2) : $date2);
$diff_secs = abs($d1 - $d2);
$base_year = min(date("Y", $d1), date("Y", $d2));
$diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
return array
(
"years" => abs(substr(date('Ymd', $d1) - date('Ymd', $d2), 0, -4)),
"months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
"months" => date("n", $diff) - 1,
"days_total" => floor($diff_secs / (3600 * 24)),
"days" => date("j", $diff) - 1,
"hours_total" => floor($diff_secs / 3600),
"hours" => date("G", $diff),
"minutes_total" => floor($diff_secs / 60),
"minutes" => (int) date("i", $diff),
"seconds_total" => $diff_secs,
"seconds" => (int) date("s", $diff)
);
}
``` | The PEAR Date class offers all kinds of features for finding the differences between dates and about 1000 other things as well. The docs for it are [here...](http://pear.php.net/package/Date/) | PHP date calculation | [
"",
"php",
"windows",
"date",
"format",
""
] |
I have a multi-browser page that shows vertical text.
As an ugly hack to get text to render vertically in all browsers I've created a custom page handler that returns a PNG with the text drawn vertically.
Here's my basic code (C#3, but small changes to any other version down to 1):
```
Font f = GetSystemConfiguredFont();
//this sets the text to be rotated 90deg clockwise (i.e. down)
StringFormat stringFormat = new StringFormat { FormatFlags = StringFormatFlags.DirectionVertical };
SizeF size;
// creates 1Kx1K image buffer and uses it to find out how bit the image needs to be to fit the text
using ( Image imageg = (Image) new Bitmap( 1000, 1000 ) )
size = Graphics.FromImage( imageg ).
MeasureString( text, f, 25, stringFormat );
using ( Bitmap image = new Bitmap( (int) size.Width, (int) size.Height ) )
{
Graphics g = Graphics.FromImage( (Image) image );
g.FillRectangle( Brushes.White, 0f, 0f, image.Width, image.Height );
g.TranslateTransform( image.Width, image.Height );
g.RotateTransform( 180.0F ); //note that we need the rotation as the default is down
// draw text
g.DrawString( text, f, Brushes.Black, 0f, 0f, stringFormat );
//make be background transparent - this will be an index (rather than an alpha) transparency
image.MakeTransparent( Color.White );
//note that this image has to be a PNG, as GDI+'s gif handling renders any transparency as black.
context.Response.AddHeader( "ContentType", "image/png" );
using ( MemoryStream memStream = new MemoryStream() )
{
image.Save( memStream, ImageFormat.Png );
memStream.WriteTo( context.Response.OutputStream );
}
}
```
This creates an image that looks how I want it to, except that the transparency is index based. As I'm returning a PNG it could support a proper alpha transparency.
Is there any way to do this in .net?
---
Thanks to Vlix (see comments) I've made some changes, though it still isn't right:
```
using ( Bitmap image = new Bitmap( (int) size.Width, (int) size.Height, PixelFormat.Format32bppArgb ) )
{
Graphics g = Graphics.FromImage( (Image) image );
g.TranslateTransform( image.Width, image.Height );
g.RotateTransform( 180.0F ); //note that we need the rotation as the default is down
// draw text
g.DrawString( text, f, Brushes.Black, 0f, 0f, stringFormat );
//note that this image has to be a PNG, as GDI+'s gif handling renders any transparency as black.
context.Response.AddHeader( "ContentType", "image/png" );
using ( MemoryStream memStream = new MemoryStream() )
{
//note that context.Response.OutputStream doesn't support the Save, but does support WriteTo
image.Save( memStream, ImageFormat.Png );
memStream.WriteTo( context.Response.OutputStream );
}
}
```
Now the alpha appears to work, but the text appears blocky - as if it still has the jaggie edges but against a black background.
Is this some bug with .Net/GDI+? I've already found that it fails for even index transparencies for gifs, so I don't have much confidence it it.
This image shows the two ways this goes wrong:

The top image shows it with no white background or `MakeTransparent` call. The second with the background filled with white and then `MakeTransparent` called to add the index transparency.
Neither of these is correct - the second image has white aliasing jaggies that I don't want, the first appears to be solidly aliased against black. | To fix the text "blockiness", can't you just do...
```
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
```
after this line...
```
Graphics g = Graphics.FromImage( (Image) image );
``` | IIRC you need to specify the PixelFormat in the bitmap constructor. | Can you make an alpha transparent PNG with C#? | [
"",
"c#",
".net",
"gdi+",
""
] |
Our logging class, when initialised, truncates the log file to 500,000 bytes. From then on, log statements are appended to the file.
We do this to keep disk usage low, we're a commodity end-user product.
Obviously keeping the first 500,000 bytes is not useful, so we keep the last 500,000 bytes.
Our solution has some serious performance problem. What is an efficient way to do this? | > "I would probably create a new file, seek in the old file, do a buffered read/write from old file to new file, rename the new file over the old one."
I think you'd be better off simply:
```
#include <fstream>
std::ifstream ifs("logfile"); //One call to start it all. . .
ifs.seekg(-512000, std::ios_base::end); // One call to find it. . .
char tmpBuffer[512000];
ifs.read(tmpBuffer, 512000); //One call to read it all. . .
ifs.close();
std::ofstream ofs("logfile", ios::trunc);
ofs.write(tmpBuffer, 512000); //And to the FS bind it.
```
This avoids the file rename stuff by simply copying the last 512K to a buffer, opening your logfile in truncate mode (clears the contents of the logfile), and spitting that same 512K back into the beginning of the file.
Note that the above code hasn't been tested, but I think the idea should be sound.
You could load the 512K into a buffer in memory, close the input stream, then open the output stream; in this way, you wouldn't need two files since you'd input, close, open, output the 512 bytes, then go. You avoid the rename / file relocation magic this way.
If you don't have an aversion to mixing C with C++ to some extent, you could also perhaps:
(Note: pseudocode; I don't remember the mmap call off the top of my head)
```
int myfd = open("mylog", O_RDONLY); // Grab a file descriptor
(char *) myptr = mmap(mylog, myfd, filesize - 512000) // mmap the last 512K
std::string mystr(myptr, 512000) // pull 512K from our mmap'd buffer and load it directly into the std::string
munmap(mylog, 512000); //Unmap the file
close(myfd); // Close the file descriptor
```
Depending on many things, mmap *could be* faster than seeking. Googling 'fseek vs mmap' yields some interesting reading about it, if you're curious.
HTH | If you happen to use windows, don't bother copying parts around. Simply tell Windows you don't need the first bytes anymore by calling [`FSCTL_SET_SPARSE`](http://msdn.microsoft.com/en-us/library/aa364596%28VS.85%29.aspx) and [`FSCTL_SET_ZERO_DATA`](http://msdn.microsoft.com/en-us/library/aa364597%28VS.85%29.aspx) | Remove all but the last 500,000 bytes from a file with the STL | [
"",
"c++",
"logging",
"stl",
""
] |
I have a database for an E-commerce storefront. MSSQL 2008.
I have a table called Products and a table called Tags. This is a many to many relationship that is bound together by a table called ProductTags.
Products:
id, name, price
Tags:
id, name, sortorder, parentid(allow nulls)
ProductTags:
productid, tagid
I'm trying to create a View in SQL, but I just completely suck at writing SQL.
The View should consist of:
Tags.id, Tags.Name, Tags.sortorder, Tags.parentid, ProductCount, ChildTagCount
ProductCount is the number of products associated to this Tag.
ChildTagCount is the number of Tags that has this Tag's id as its parentid. | ```
SELECT Tags.ID, Tags.Name, Tags.SortOrder, Tags.ParentID,
COUNT(DISTINCT ProductTags.ProductID) AS ProductCount,
COUNT(DISTINCT ChildTags.ID) AS ChildTagCount
FROM Tags
LEFT OUTER JOIN ProductTags ON Tags.ID = ProductTags.TagID
LEFT OUTER JOIN Tags ChildTags ON Tags.ID = ChildTags.ParentID
GROUP BY Tags.ID, Tags.Name, Tags.SortOrder, Tags.ParentID
``` | ```
Select T.id, T.Name, T.sortorder, T.parentid,
(select count(*) from productstags where tagid=T.TagId) as ProductCount,
(select count(*) from Tags where parentid=T.TagId) as ChildTagCount
from Tags T
```
would that work? | SQL Query for Product-Tag relationship | [
"",
"sql",
""
] |
I have a method which is given the parameter "bool sortAscending". Now I want to use LINQ to create sorted list depending on this parameter. I got then this:
```
var ascendingQuery = from data in dataList
orderby data.Property ascending
select data;
var descendingQuery = from data in dataList
orderby data.Property descending
select data;
```
As you can see, both queries differ only in "ascending" resp. "descending". I'd like to merge both queries, but I don't know how. Does anyone have the answer? | You can easily create your own extension method on IEnumerable or IQueryable:
```
public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}
public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
(this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}
```
Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:
```
var query = dataList.OrderByWithDirection(x => x.Property, direction);
``` | In terms of how this is implemented, this changes the *method* - from OrderBy/ThenBy to OrderByDescending/ThenByDescending. However, you can apply the sort separately to the main query...
```
var qry = from .... // or just dataList.AsEnumerable()/AsQueryable()
if(sortAscending) {
qry = qry.OrderBy(x=>x.Property);
} else {
qry = qry.OrderByDescending(x=>x.Property);
}
```
Any use? You can create the entire "order" dynamically, but it is more involved...
Another trick (mainly appropriate to LINQ-to-Objects) is to use a multiplier, of -1/1. This is only really useful for numeric data, but is a cheeky way of achieving the same outcome. | ascending/descending in LINQ - can one change the order via parameter? | [
"",
"c#",
"linq",
""
] |
**What happens in the memory when a class instantiates the following object?**
```
public class SomeObject{
private String strSomeProperty;
public SomeObject(String strSomeProperty){
this.strSomeProperty = strSomeProperty;
}
public void setSomeProperty(String strSomeProperty){
this.strSomeProperty = strSomeProperty;
}
public String getSomeProperty(){
return this.strSomeProperty;
}
}
```
In class `SomeClass1`:
```
SomeObject so1 = new SomeObject("some property value");
```
In class `SomeClass2`:
```
SomeObject so2 = new SomeObject("another property value");
```
**How is memory allocated to the newly instantiated object and its properties?** | Let's step through it:
```
SomeObject so1 = new SomeObject("some property value");
```
... is actually more complicated than it looks, because you're creating a new String. It might be easier to think of as:
```
String tmp = new String("some property value");
SomeObject so1 = new SomeObject(tmp);
// Not that you would normally write it in this way.
```
(To be absolutely accurate - these are not really equivalent. In the original the 'new String' is created at compile time and is part of the .class image. You can think of this as a performance hack.)
So, first the JVM allocates space for the String. You typically don't know or care about the internals of the String implementation, so just take it on trust that a chunk of memory is being used to represent "some property value". Also, you have some memory temporarily allocated containing a reference to the String. In the second form, it's explicitly called `tmp`; in your original form Java handles it without naming it.
Next the JVM allocates space for a new SomeObject. That's a bit of space for Java's internal bookkeeping, and space for each of the object's fields. In this case, there's just one field, `strSomeProperty`.
Bear in mind that `strSomeProperty` is just a reference to a String. For now, it'll be initialised to null.
Next, the constructor is executed.
```
this.strSomeProperty = strSomeProperty;
```
All this does is copy the *reference* to the String, into your `strSomeProperty` field.
Finally, space is allocated for the object reference `so1`. This is set with a reference to the SomeObject.
`so2` works in exactly the same way. | [Determining Memory Usage in Java](http://www.javaspecialists.eu/archive/Issue029.html) by Dr. Heinz M. Kabutz gives a precise answer, plus a program to calculate the memory usage. The relevant part:
> 1. The class takes up at least 8 bytes. So, if you say new Object(); you will allocate 8 bytes on the heap.
> 2. Each data member takes up 4 bytes, except for long and double which take up 8 bytes. Even if the data member is a byte, it will still take up 4 bytes! In addition, the amount of memory used is increased in 8 byte blocks. So, if you have a class that contains one byte it will take up 8 bytes for the class and 8 bytes for the data, totalling 16 bytes (groan!).
> 3. Arrays are a bit more clever. Primitives get packed in arrays, so if you have an array of bytes they will each take up one byte (wow!). The memory usage of course still goes up in 8 byte blocks.
As people have pointed out in the comments, Strings are a special case, because they can be interned. You can reason about the space they take up in the same way, but keep in mind that what looks like multiple copies of the same String may actually point to the same reference. | Steps in the memory allocation process for Java objects | [
"",
"java",
"object",
"memory",
"heap-memory",
""
] |
I have two implementations of a method, one for value types and another for reference types:
```
public static Result<T> ImplRef(T arg) where T : class {...}
public static Result<T> ImplVal(T arg) where T : struct {...}
```
I want to write a method which calls the correct implementation like this
```
public static Result<T> Generic(T arg) {
if (typeOf(T).IsValueType)
return ImplVal(arg);
else
return ImplRef(arg);
}
```
Obviously, the above implementation doesn't compile. How can I do this with minimum of reflection? | The idea with generics is usually to do the same logic with whichever inputs you are given, although obviously you need to be practical. Personally, I'd probably use two different methods, rather than brute-force them into the same method, but that would make it hard to call from a generic method just knowing about `T`. There is no way of satisfying the `: class` / `: struct` from static code, although the `MakeGenericMethod` approach might work, but will be an order of magnitude slower.
```
// slow; use with caution
public static Result<T> Generic<T>(T arg) {
if (typeof(T).IsValueType)
return (Result<T>)typeof(Program).GetMethod("ImplVal")
.MakeGenericMethod(typeof(T))
.Invoke(null, new object[] {arg});
else
return (Result<T>)typeof(Program).GetMethod("ImplRef")
.MakeGenericMethod(typeof(T))
.Invoke(null, new object[] { arg });
}
```
(substitute `typeof(Program)` with the type that hosts the methods)
The alternative (as Jon notes) is to cache the (typed) delegate to the method:
```
public static Result<T> Generic<T>(T arg) {
return Cache<T>.CachedDelegate(arg);
}
internal static class Cache<T>
{
public static readonly Func<T, Result<T>> CachedDelegate;
static Cache()
{
MethodInfo method;
if (typeof(T).IsValueType)
method = typeof(Program).GetMethod("ImplVal")
.MakeGenericMethod(typeof(T));
else
method = typeof(Program).GetMethod("ImplRef")
.MakeGenericMethod(typeof(T));
CachedDelegate = (Func<T, Result<T>>)Delegate.CreateDelegate(
typeof(Func<T, Result<T>>), method);
}
}
```
More work, but will be plenty quick. The static constructor (or you could use a property/null check) ensures we only do the hard work once. | Do you actually *use* the constraints in `ImplRef` and `ImplVal`? If not (i.e. if it's just so you can behave differently) you could drop the constraints, make the methods private, and just call them appropriately from `Generic` - or possibly have:
```
public static Result<T> ImplRef(T arg) where T : class
{
return ImplRefImpl(arg);
}
private static Result<T> ImplRefImpl(T arg)
{
// Real code
}
public static Result<T> ImplVal(T arg) where T : struct
{
return ImplValImpl(arg);
}
private static Result<T> ImplValImpl(T arg)
{
// Real code
}
```
You should consider what to do if `T` is a nullable type, by the way - it doesn't actually satisfy either the `class` or `struct` constraints.
By the way, another way of testing for T being a value type (which may be more efficient - not sure) is:
```
if (default(T) == null)
```
Note that this will "pass" for a nullable type, unlike your test of IsValueType, so the behaviour isn't identical. | How to make a .Net generic method behave differently for value types and reference types? | [
"",
"c#",
"generics",
""
] |
Hey there, I've got a block of HTML that I'm going to be using repeatedly (at various times during a users visit, not at once). I think that the best way to accomplish this is to create an HTML div, hide it, and when needed take its innerHTML and do a replace() on several keywords. As an example HTML block...
```
<div id='sample'>
<h4>%TITLE%</h4>
<p>Text text %KEYWORD% text</p>
<p>%CONTENT%</p>
<img src="images/%ID%/1.jpg" />
</div>
```
Would the best way to replace those keywords with dynamic data be to go...
```
template = document.getElementById('sample');
template = template.replace(/%TITLE%/, some_var_with_title);
template = template.replace(/%KEYWORD%/, some_var_with_keyword);
template = template.replace(/%CONTENT%/, some_var_with_content);
template = template.replace(/%ID%/, some_var_with_id);
```
It just feels like I've chosen a stupid way to do this. Does anyone have any suggestions on how to do this faster, smarter, or better in any way? This code will be executed fairly often during a users visit, sometimes as often as once every 3-4 seconds.
Thanks in advance. | I doubt there will be anything more efficient. The alternative would be splitting it into parts and then concatenating, but I don't think that would be much efficient. Perhaps even less, considering that every concatenation results in a new string which has the same size as its operands.
**Added:** This is probably the most elegant way to write this. Besides - what are you worried about? Memory usage? It's abundant and Javascript has a decent memory manager. Execution speed? Then you must have some gigantic string. IMHO this is good. | It looks like you want to use a template.
```
//Updated 28 October 2011: Now allows 0, NaN, false, null and undefined in output.
function template( templateid, data ){
return document.getElementById( templateid ).innerHTML
.replace(
/%(\w*)%/g, // or /{(\w*)}/g for "{this} instead of %this%"
function( m, key ){
return data.hasOwnProperty( key ) ? data[ key ] : "";
}
);
}
```
Explanation of the code:
* Expects `templateid` to be the id of an existing element.
* Expects `data` to be an object with the data.
* Uses two parameters to replace to do the substitution:
* The first is a regexp that searches for all `%keys%` (or `{keys}` if you use the alternate version). The key can be a combination of A-Z, a-z, 0-9 and underscore \_.
* The second is a anonymous function that gets called for every match.
* The anonymous function searches the data object for the key that the regexp found.
If the key is found in the data, then the value of the key is returned and that value will be replacing the key in the final output. If the key isn't found, an empty string is returned.
Example of template:
```
<div id="mytemplate">
<p>%test%</p>
<p>%word%</p>
</div>
```
Example of call:
```
document.getElementById("my").innerHTML=template("mytemplate",{test:"MYTEST",word:"MYWORD"});
``` | Efficient Javascript String Replacement | [
"",
"javascript",
"string",
"performance",
"replace",
""
] |
Which is the best PHP library for openID integration? | For PHP, I find **[Zend Framework OpenID Component](http://framework.zend.com/manual/en/zend.openid.html)** to be really good.
You can also see all available OpenID libraries at [**this link**](http://wiki.openid.net/Libraries) | The [PHP OpenID library](http://openidenabled.com/php-openid/) is good. | PHP library for openID | [
"",
"php",
"openid",
""
] |
Does dot net have an interface like IEnumerable with a count property? I know about interfaces such as IList and ICollection which do offer a Count property but it seems like these interfaces were designed for mutable data structures first and use as a read only interface seems like an afterthought - the presence of an IsReadOnly field and mutators throwing exceptions when this property is true is IMO ample evidence for this.
For the time being I am using a custom interface called IReadOnlyCollection (see my own answer to this post) but I would be glad to know of other alternative approaches. | The key difference between the ICollection family and the IEnumerable family is the absence of certainty as to the count of items present (quite often the items will be generated/loaded/hydrated as needed) - in some cases, an Enumerable may not ever finish generating results, which is why the Count is missing.
Deriving and adding a Count is possible depending on your requirements, but it goes against this spirit, which is the purpose of ICollection - a collection of stuff that's all there.
Another way might be to use the System.Linq.Enumerable.Count method, i.e.
```
using System.Linq;
class X
{
void Y(IEnumerable<int> collection)
{
int itemCount = collection.Count();
}
}
```
or use the (System.Linq.Enumerable) .ToList() to pull all the items from the enumerator into a Collection and work from there.
(Also to answer your comment before having 50 rep:- the ".Count()" bit is a call to an extension method on the extension class System.Linq.Enumerable - the extension method is available on all things that derive from IEnumerable because the code has a "using System.Linq" which brings the extension methods in all classes in that namespace into scope - in this case its in the class Enumerable. If you're in VS, pressing F12 will bring you to the definition of S.L.Enumerable. BTW C# In Depth is a fantastic book for learning LINQ properly - its a page turner thats really helps you get the whole picture compared to learning the bits of LINQ piece by piece) | As of .Net 4.5, there are two new interfaces for this: [`IReadOnlyCollection<T>`](http://msdn.microsoft.com/en-us/library/hh881542%28v=vs.110%29) and [`IReadOnlyList<T>`](http://msdn.microsoft.com/en-us/library/hh192385%28v=vs.110%29).
`IReadOnlyCollection<T>` is `IEnumerable<T>` with a `Count` property added, `IReadOnlyList<T>` also adds indexing. | Does dot net have an interface like IEnumerable with a Count property? | [
"",
"c#",
".net",
""
] |
To do DataBinding of the `Document` in a WPF `RichtextBox`, I saw 2 solutions so far, which are to derive from the `RichtextBox` and add a `DependencyProperty`, and also the solution with a "proxy".
Neither the first or the second are satisfactory. Does somebody know another solution, or instead, a commercial RTF control which is capable of **DataBinding**? The normal `TextBox` is not an alternative, since we need text formatting.
Any idea? | There is a much easier way!
You can easily create an attached `DocumentXaml` (or `DocumentRTF`) property which will allow you to bind the `RichTextBox`'s document. It is used like this, where `Autobiography` is a string property in your data model:
```
<TextBox Text="{Binding FirstName}" />
<TextBox Text="{Binding LastName}" />
<RichTextBox local:RichTextBoxHelper.DocumentXaml="{Binding Autobiography}" />
```
Voila! Fully bindable `RichTextBox` data!
The implementation of this property is quite simple: When the property is set, load the XAML (or RTF) into a new `FlowDocument`. When the `FlowDocument` changes, update the property value.
This code should do the trick:
```
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
public class RichTextBoxHelper : DependencyObject
{
public static string GetDocumentXaml(DependencyObject obj)
{
return (string)obj.GetValue(DocumentXamlProperty);
}
public static void SetDocumentXaml(DependencyObject obj, string value)
{
obj.SetValue(DocumentXamlProperty, value);
}
public static readonly DependencyProperty DocumentXamlProperty =
DependencyProperty.RegisterAttached(
"DocumentXaml",
typeof(string),
typeof(RichTextBoxHelper),
new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true,
PropertyChangedCallback = (obj, e) =>
{
var richTextBox = (RichTextBox)obj;
// Parse the XAML to a document (or use XamlReader.Parse())
var xaml = GetDocumentXaml(richTextBox);
var doc = new FlowDocument();
var range = new TextRange(doc.ContentStart, doc.ContentEnd);
range.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml)),
DataFormats.Xaml);
// Set the document
richTextBox.Document = doc;
// When the document changes update the source
range.Changed += (obj2, e2) =>
{
if (richTextBox.Document == doc)
{
MemoryStream buffer = new MemoryStream();
range.Save(buffer, DataFormats.Xaml);
SetDocumentXaml(richTextBox,
Encoding.UTF8.GetString(buffer.ToArray()));
}
};
}
});
}
```
The same code could be used for TextFormats.RTF or TextFormats.XamlPackage. For XamlPackage you would have a property of type `byte[]` instead of `string`.
The XamlPackage format has several advantages over plain XAML, especially the ability to include resources such as images, and it is more flexible and easier to work with than RTF.
It is hard to believe this question sat for 15 months without anyone pointing out the easy way to do this. | I know this is an old post, but check out the [Extended WPF Toolkit](https://github.com/xceedsoftware/wpftoolkit). It has a RichTextBox that supports what you are tryign to do. | Richtextbox wpf binding | [
"",
"c#",
"wpf",
"data-binding",
"richtextbox",
""
] |
Here's the situation: we have an Oracle database we need to connect to to pull some data. Since getting access to said Oracle database is a real pain (mainly a bureaucratic obstacle more than anything else), we're just planning on linking it to our SQL Server and using the link to access data as we need it.
For one of our applications, we're planning on making a view to get the data we need. Now the data we need is joined from two tables. If we do this, which would be preferable?
This (in pseudo-SQL if such a thing exists):
```
OPENQUERY(Oracle, "SELECT [cols] FROM table1 INNER JOIN table2")
```
or this:
```
SELECT [cols] FROM OPENQUERY(Oracle, "SELECT [cols1] FROM table1")
INNER JOIN OPENQUERY(Oracle, "SELECT [cols2] from table2")
```
Is there any reason to prefer one over the other? One thing to keep in mind: we are on a limitation on how long the query can run to access the Oracle server. | If the inner join significantly reduces the total number of rows, then option 1 will result in much less network traffic (since you won't have all the rows from table1 having to go across the db link | I'd go with your first option especially if your query contains a where clause to select a sub-set of the data in the tables.
It will require less work on both servers, assuming there are indices on the tables in the Oracle server that support the join operation. | Join in linked server or join in host server? | [
"",
"sql",
"sql-server-2005",
"oracle",
"join",
"linked-server",
""
] |
I have a couple of tables which are used to log user activity for an application. The tables looks something like this (pseudo code from memory, may not be syntactically correct):
```
create table activity (
sessionid uniqueidentifier not null,
created smalldatetime not null default getutcdate()
);
create table activity_details (
sessionid uniqueidentifier not null,
activity_description varchar(100) not null,
created smalldatetime not null default getutcdate()
);
```
My goal is to populate a summary table for reporting purposes that looks something like this:
```
create table activity_summary (
sessionid uniqueidentifier not null,
first_activity_desc varchar(100) not null,
last_activity_desc varchar(100) not null
);
```
First and last activity descriptions would be determined chronologically. My initial thought is to update the summary table like so:
```
truncate table activity_summary;
insert into activity_summary (sessionid)
select sessionid from activity;
update table activity_summary set
first_activity_desc = (select top 1 activity_desc from activity_detail where sessionid = as.sessionid order by created asc),
last_activity_summary = (select top 1 activity_desc from activity_detail where sessionid = as.sessionid order by created desc)
from activity_summary as;
```
However, this seems incredibly verbose and unnecessary to me. I'm just not sure how to shrink it down. My gut feel is that I could do it somehow all within the insert statement, but I'm stumped. Any suggestions? | There's probably more efficient ways to do this as well, but this is closest to your original:
```
truncate table activity_summary;
insert into activity_summary (sessionid, first_activity_desc, last_activity_summary)
select a.sessionid
,(select top 1 ad.activity_desc from activity_detail AS ad where ad.sessionid = a.sessionid order by ad.created asc) AS first_activity_desc
,(select top 1 ad.activity_desc from activity_detail AS ad where ad.sessionid = a.sessionid order by ad.created desc) AS last_activity_summary
from activity AS a;
```
Something like this might be more efficient:
```
truncate table activity_summary;
WITH firsts AS (
SELECT ad.sessionid
,ad.activity_desc
,ROW_NUMBER() OVER (ORDER BY ad.created ASC) as RowNumber
FROM activity_detail AS ad
)
,lasts AS (
SELECT ad.sessionid
,ad.activity_desc
,ROW_NUMBER() OVER (ORDER BY ad.created DESC) as RowNumber
FROM activity_detail AS ad
)
insert into activity_summary (sessionid, first_activity_desc, last_activity_summary)
select a.sessionid
,firsts.activity_desc
,lasts.activity_desc
from activity AS a
INNER JOIN firsts ON firsts.sessionid = a.sessionid AND firsts.RowNumber = 1
INNER JOIN lasts ON lasts.sessionid = a.sessionid AND lasts.RowNumber = 1
``` | ```
insert into activity_summary
(sessionid, first_activity_desc, last_activity_desc)
select
agg.sessionid,
adf.activity_description,
adl.activity_description
from
(SELECT
sessionid, MIN(created) as firstcreated, MAX(created) as lastcreated
from
activity_detail group by sessionid
) agg
JOIN
activity_details adf ON agg.sessionid = adf.sessionid AND agg.firstcreated = adf.created
JOIN
activity_details adl ON agg.sessionid = adl.sessionid AND agg.lastcreated = adl.created
``` | SQL Server - update one table with first and last rows from another table | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
An answer and subsequent [debate in the comments](https://stackoverflow.com/questions/360899/c-math-problem#360931) in another thread prompted me to ask:
In C# || and && are the short-circuited versions of the logical operators | and & respectively.
Example usage:
```
if (String.IsNullOrEmpty(text1) | String.IsNullOrEmpty(text2) | String.IsNullOrEmpty(text3))
{
//...
}
```
versus:
```
if (String.IsNullOrEmpty(text1) || String.IsNullOrEmpty(text2) || String.IsNullOrEmpty(text3))
{
//...
}
```
In terms of coding practice which is the better to use and why?
Note: I do realize this question is similar to [this question](https://stackoverflow.com/questions/89154/benefits-of-using-short-circuit-evaluation) but I believe it warrants a language specific discussion. | > In terms of coding practice which is the better to use and why?
Simple answer: always use the short-circuited versions. There’s simply no reason not to. Additionally, you make your code clearer because you express your *intent*: logical evaluation. Using the bitwise (logical) operations implies that you want just that: bit operations, not logical evaluation (even though the MSDN calls them “logical operators” as well, when applied to boolean values).
Additionally, since short-circuiting only evaluates what needs evaluating, it’s often faster, and it allows to write such code as
```
bool nullorempty = str == null || str.Length == 0;
```
(Notice that to solve this particular problem a better function already exists, namely `string.IsNullOrEmpty` which you also used in your question.) This code wouldn’t be possible with the bitwise logical operations because even if `str` were `null`, the second expression would get evaluated, resulting in a `NullReferenceException`.
**EDIT**: If you *want* side-effects to occur in a logical context please *still* don’t use bitwise operations. This is a typical example of being too clever. The next maintainer of the code (or even yourself, after a few weeks) wo sees this code will think “hmm, this code can be cleared up to use conditional operators,” thus inadvertedly breaking the code. I pity whoever is in charge of fixing this bug.
Instead, if you have to rely on side, effects, make them explicit:
```
bool hasBuzzed = checkMakeBuzz();
bool isFrobbed = checkMakeFrob();
bool result = hasBuzzed || isFrobbed;
```
Granted, three lines instead of one. But a much clearer code as a result. | I am going to answer this question in reverse: when is the **only** time I use the logic operators?
I will sometimes use the logical comparisons when I have a series of (low-cost) conditionals that must all be met. For example:
```
bool isPasswordValid = true;
isPasswordValid &= isEightCharacters(password);
isPasswordValid &= containsNumeric(password);
isPasswordValid &= containsBothUppercaseAndLowercase(password);
return isPasswordValid;
```
In my opinion, the above is more readable than:
```
return (isEightCharacters(password) &&
containsNumberic(password) &&
containsBothUppercaseAndLowercase(password));
```
The downside is that it's a bit more esoteric. | What is the best practice concerning C# short-circuit evaluation? | [
"",
"c#",
""
] |
I know I could have an attribute but that's more work than I want to go to... and not general enough.
I want to do something like
```
class Whotsit
{
private string testProp = "thingy";
public string TestProp
{
get { return testProp; }
set { testProp = value; }
}
}
...
Whotsit whotsit = new Whotsit();
string value = GetName(whotsit.TestProp); //precise syntax up for grabs..
```
where I'd expect value to equal "TestProp"
but I can't for the life of me find the right reflection methods to write the GetName method...
EDIT: Why do I want to do this? I have a class to store settings read from a 'name', 'value' table. This is populated by a generalised method based upon reflection. I'd quite like to write the reverse...
```
/// <summary>
/// Populates an object from a datatable where the rows have columns called NameField and ValueField.
/// If the property with the 'name' exists, and is not read-only, it is populated from the
/// valueField. Any other columns in the dataTable are ignored. If there is no property called
/// nameField it is ignored. Any properties of the object not found in the data table retain their
/// original values.
/// </summary>
/// <typeparam name="T">Type of the object to be populated.</typeparam>
/// <param name="toBePopulated">The object to be populated</param>
/// <param name="dataTable">'name, 'value' Data table to populate the object from.</param>
/// <param name="nameField">Field name of the 'name' field'.</param>
/// <param name="valueField">Field name of the 'value' field.</param>
/// <param name="options">Setting to control conversions - e.g. nulls as empty strings.</param>
public static void PopulateFromNameValueDataTable<T>
(T toBePopulated, System.Data.DataTable dataTable, string nameField, string valueField, PopulateOptions options)
{
Type type = typeof(T);
bool nullStringsAsEmptyString = options == PopulateOptions.NullStringsAsEmptyString;
foreach (DataRow dataRow in dataTable.Rows)
{
string name = dataRow[nameField].ToString();
System.Reflection.PropertyInfo property = type.GetProperty(name);
object value = dataRow[valueField];
if (property != null)
{
Type propertyType = property.PropertyType;
if (nullStringsAsEmptyString && (propertyType == typeof(String)))
{
value = TypeHelper.EmptyStringIfNull(value);
}
else
{
value = TypeHelper.DefaultIfNull(value, propertyType);
}
property.SetValue(toBePopulated, System.Convert.ChangeType(value, propertyType), null);
}
}
}
```
FURTHER EDIT: I am just in code, have an instance of Whotsit and I want to get the text string of the 'TestProp' property. It seems kind of weird I know, I can just use the literal "TestProp" - or in the case of my class to datatable function I'd be in a foreach loop of PropertyInfos. I was just curious...
The original code had string constants, which I found clumsy. | No, there's nothing to do this. The expression `whotsit.TestProp` will evaluate the property. What you want is the mythical "infoof" operator:
```
// I wish...
MemberInfo member = infoof(whotsit.TestProp);
```
As it is, you can only use reflection to get the property by name - not from code. (Or get all the properties, of course. It still doesn't help you with your sample though.)
One alternative is to use an expression tree:
```
Expression<Func<string>> = () => whotsit.TestProp;
```
then examine the expression tree to get the property.
If none of this helps, perhaps you could tell us more about why you want this functionality? | It is possible (without reflection) but only with latest C# 3.0
**quick & very very dirty**
```
class Program
{
static void Main()
{
string propertyName = GetName(() => AppDomain.CurrentDomain);
Console.WriteLine(propertyName); // prints "CurrentDomain"
Console.ReadLine();
}
public static string GetName(Expression<Func<object>> property)
{
return property.Body.ToString().Split('.').Last();
}
}
```
**Update:** I've just realized that [**Jon Skeet**](https://stackoverflow.com/questions/305223/jon-skeet-facts) (anyone surprised? :) has covered this possibility already but I'll keep my answer here just in case someone is interested in some example to start with. | How do I get the name of a property from a property in C# (2.0) | [
"",
"c#",
"reflection",
"properties",
""
] |
I have been assigned a project to develop a set of classes that act as an interface to a storage system. A requirement is that the class support a get method with the following signature:
```
public CustomObject get(String key, Date ifModifiedSince)
```
Basically the method is supposed to return the `CustomObject` associated with the `key` if and only if the object has been modified after `ifModifiedSince`. If the storage system does not contain the `key` then the method should return null.
My problem is this:
**How do I handle the scenario where the key exists but the object has **not** been modified?**
This is important because some applications that use this class will be web services and web applications. Those applications will need to know whether to return a 404 (not found), 304 (not modified), or 200 (OK, here's the data).
The solutions I'm weighing are:
1. Throw a custom exception when the
storage system does not contain the
`key`
2. Throw a custom exception when the
`ifModifiedSince` fails.
3. Add a status property to the CustomObject. Require caller to check property.
I'm not happy with any of these three options. I don't like options 1 and 2 because I don't like using exceptions for flow control. Neither do I like returning a value when my intent is to indicate that there was **no value**.
Nonetheless, I am leaning towards option 3.
Is there an option I'm not considering? Does anyone have strong feelings about any of these three options?
---
**Answers to this Question, Paraphrased:**
1. Provide a `contains`
method and require caller to call it
before calling `get(key,
ifModifiedSince)`, throw
exception if key does not exist,
return null if object has not been
modified.
2. Wrap the response and data (if any)
in a composite object.
3. Use a predefined constant to denote some state (`UNMODIFIED, KEY_DOES_NOT_EXIST`).
4. Caller implements interface to be
used as callbacks.
5. The design sucks.
---
**Why I Cannot Choose Answer #1**
I agree that this is the ideal solution, but it was one I have already (reluctantly) dismissed. The problem with this approach is that in a majority of the cases in which these classes will be used, the backend storage system will be a third party remote system, like Amazon S3. This means that a `contains` method would require a round trip to the storage system, which would in most cases be followed by another round trip. Because this **would cost both time and money**, it is not an option.
**If not for that limitation, this would be the best approach.**
(I realize I didn't mention this important element in the question, but I was trying to keep it brief. Obviously it was relevant.)
---
**Conclusion:**
After reading all of the answers I have come to the conclusion that a wrapper is the best approach in this case. Essentially I'll mimic HTTP, with meta data (headers) including a response code, and content body (message). | It sounds like you actually want to return two items: the response code and the object found. You might consider creating a lightweight wrapper that holds both and return them together.
```
public class Pair<K,V>{
public K first;
public V second;
}
```
Then you can create a new Pair that holds your response code and the data. As a side effect to using generics, you can then reuse this wrapper for whatever pair you actually need.
Also, if the data hasn't expired, you could still return it, but give it a 303 code to let them know that it is unchanged. 4xx series would be paired with `null`. | With the given requirement you cannot do this.
*If you designed the contract*, then add a condition and make the caller invoke
```
exists(key): bool
```
The service implementation look like this:
```
if (exists(key)) {
CustomObject o = get(key, ifModifiedSince);
if (o == null) {
setResponseCode(302);
} else {
setResponseCode(200);
push(o);
}
} else {
setResponseCode(400);
}
```
The client remains unchanged and never notice you've validated upfront.
*If you didn't design the contract* Probably there's a good reason for that or probably it's only the designer (or architect) fault. But since you cannot change it, then you don't have to worry either.
Then you should adhere to the specifications and proceed like this:
```
CustomObject o = get(key, ifModifiedSince);
if (o != null) {
setResponseCode(200);
push(o);
} else {
setResponseCode(404); // either not found or not modified.
}
```
Ok, you're not sending 302 in this case, but probably that is the way it was designed.
I mean, for security reasons, the server should not return more information than that *[ the probe is get( key, date ) only return either null or object ]*
So don't worry about it. Talk with your manager and let him know this decision. Comment the code with this decision too. And if you have the architect in hand confirm the rationale behind this strange restriction.
Chances are they you didn't see this coming and they can modify the contract after your suggestion.
Sometimes while wanting to proceed right we may proceed wrong and compromise the security of our app.
Communicate with your team. | How Can I Avoid Using Exceptions for Flow Control? | [
"",
"java",
"exception",
"return-type",
"control-flow",
""
] |
I have a JPanel full of JTextFields...
```
for (int i=0; i<maxPoints; i++) {
JTextField textField = new JTextField();
points.add(textField);
}
```
How do I later get the JTextFields in that JPanel? Like if I want their values with
```
TextField.getText();
```
Thanks | Well bear in mind they didn't get there by them selves ( I think a read some questions about dynamically creating these panels at runtime )
In the answers posted there, someone said you should kept reference to those textfields in an array. That's exactly what you need here:
```
List<JTextField> list = new ArrayLists<JTextField>();
// your code...
for (int i=0; i<maxPoints; i++) {
JTextField textField = new JTextField();
points.add(textField);
list.add( textField ); // keep a reference to those fields.
}
```
// Later
```
for( JTextField f : list ) {
System.out.println( f.getText() ) ;
}
```
Wasn't that easy?
Just remember to keep these kinds of artifacts ( list ) as private as possible. They are for your control only, I don't think they belong to the interface.
Let's say you want to get the array of texts, instead of
```
public List<JTextField> getFields();
```
You should consider:
```
public List<String> getTexts(); // get them from the textfields ...
``` | Every JPanel in Java is also an AWT container. Thus, you should be able to use getComponents to get the array of contained components in the panel, iterate over them, check their types (To make sure you didn't get other controls), and do whatever you need with them.
However, this is generally poor design. If you know that you will need to access specific components, it is better to maintain an array of those text fields and pass it around, even though they are visually contained within the container.
If this is a recurrent task or could be done from multiple points, it may even make sense to have a special class representing a panel with text fields, that will then provide through its interface means of accessing these fields. | Java get JPanel Components | [
"",
"java",
"swing",
"jframe",
"jpanel",
"jcomponent",
""
] |
For example I can point the `url '^/accounts/password/reset/$'` to `django.contrib.auth.views.password_reset` with my template filename in the context but I think need to send more context details.
I need to know exactly what context to add for each of the password reset and change views. | If you take a look at the sources for [django.contrib.auth.views.password\_reset](http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py) you'll see that it uses [`RequestContext`](http://code.djangoproject.com/browser/django/trunk/django/template/__init__.py). The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.
The b-list has a good [introduction to context processors](http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/).
Edit (I seem to have been confused about what the actual question was):
You'll notice that `password_reset` takes a named parameter called `template_name`:
```
def password_reset(request, is_admin_site=False,
template_name='registration/password_reset_form.html',
email_template_name='registration/password_reset_email.html',
password_reset_form=PasswordResetForm,
token_generator=default_token_generator,
post_reset_redirect=None):
```
Check [password\_reset](https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.views.password_reset) for more information.
... thus, with a urls.py like:
```
from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset
urlpatterns = patterns('',
(r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
...
)
```
`django.contrib.auth.views.password_reset` will be called for URLs matching `'/accounts/password/reset'` with the keyword argument `template_name = 'my_templates/password_reset.html'`.
Otherwise, you don't need to provide any context as the `password_reset` view takes care of itself. If you want to see what context you have available, you can trigger a `TemplateSyntax` error and look through the stack trace find the frame with a local variable named `context`. If you want to modify the context then what I said above about context processors is probably the way to go.
In summary: what do you need to do to use your own template? Provide a `template_name` keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple. | Strongly recommend this article.
I just plugged it in and it worked
<http://garmoncheg.blogspot.com.au/2012/07/django-resetting-passwords-with.html> | How do I use the built in password reset/change views with my own templates | [
"",
"python",
"django",
"passwords",
""
] |
I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would allow me to check this condition in a single if() statement? Target language is C# but I'm interested in solutions in other languages as well (as long as we're not talking about specific built-in functions).
One interesting option is to store the booleans in a byte, do a right shift and compare with the original byte. Something like `if(myByte && (myByte >> 1))` But this would require converting the separate booleans to a byte (via a bitArray?) and that seems a bit (pun intended) clumsy... *[edit]Sorry, that should have been* `if(myByte & (myByte - 1))` *[/edit]*
Note: This is of course very close to the classical "population count", "sideways addition" or "Hamming weight" programming problem - but not quite the same. I don't need to know how many of the bits are set, only if it is more than one. My hope is that there is a much simpler way to accomplish this. | How about
```
if ((bool1? 1:0) + (bool2? 1:0) + (bool3? 1:0) +
(bool4? 1:0) + (bool5? 1:0) > 1)
// do something
```
or a generalized method would be...
```
public bool ExceedsThreshold(int threshold, IEnumerable<bool> bools)
{
int trueCnt = 0;
foreach(bool b in bools)
if (b && (++trueCnt > threshold))
return true;
return false;
}
```
or using LINQ as suggested by other answers:
```
public bool ExceedsThreshold(int threshold, IEnumerable<bool> bools)
{ return bools.Count(b => b) > threshold; }
```
EDIT (to add Joel Coehoorn suggestion:
(in .Net 2.x and later)
```
public void ExceedsThreshold<T>(int threshold,
Action<T> action, T parameter,
IEnumerable<bool> bools)
{ if (ExceedsThreshold(threshold, bools)) action(parameter); }
```
or in .Net 3.5 and later:
```
public void ExceedsThreshold(int threshold,
Action action, IEnumerable<bool> bools)
{ if (ExceedsThreshold(threshold, bools)) action(); }
```
or as an extension to `IEnumerable<bool>`
```
public static class IEnumerableExtensions
{
public static bool ExceedsThreshold<T>
(this IEnumerable<bool> bools, int threshold)
{ return bools.Count(b => b) > threshold; }
}
```
usage would then be:
```
var bools = new [] {true, true, false, false, false, false, true};
if (bools.ExceedsThreshold(3))
// code to execute ...
``` | I was going to write the Linq version, but five or so people beat me to it. But I really like the params approach to avoid having to manually new up an array. So I think the best hybrid is, based on rp's answer with the body replace with the obvious Linqness:
```
public static int Truth(params bool[] booleans)
{
return booleans.Count(b => b);
}
```
Beautifully clear to read, and to use:
```
if (Truth(m, n, o, p, q) > 2)
``` | Elegantly determine if more than one boolean is "true" | [
"",
"c#",
"hammingweight",
""
] |
I have a few modules of block of code in VBA to run on few Access databases. I would like to know how I should proceed if I want to convert the coding to C# environment. And is it possible to implement and obtain the same results as I am getting now with Access and VBA?
I am completely new to C# at this point. | Automatic conversion isn't possible at the moment, but doing it manually will also help improve your C# skills. There's a Top 10 article here that takes you through the common differences:
<http://msdn.microsoft.com/en-us/library/aa164018%28office.10%29.aspx>
You may also find the following links useful:
The MSDN page for developing Office solutions with C#:
<http://msdn.microsoft.com/en-us/library/ms228286.aspx>
The MSDN Visual C# application development page (for starting out in C# development):
<http://msdn.microsoft.com/en-us/library/aezdt881.aspx>
Good luck and I hope this helps. | One thing to be aware of is that some object name spaces and library references are included automatically when you are coding in VBA. These need to be explicitly added when working in C#. For example,
```
Selection.TypeText("foo")
```
in VBA becomes
```
using Microsoft.Office.Interop.Word;
Application word = new Application();
word.Selection.TypeText("foo");
```
in C#. Library references can be added by right-clicking the References folder in the Solution Explorer and choosing "Add Reference". | Is it possible to convert VBA to C#? | [
"",
"c#",
"vba",
"ms-access",
""
] |
How would you get a reference to an executing class several stack frames above the current one? For example, if you have:
```
Class a {
foo() {
new b().bar();
}
}
Class b {
bar() {
...
}
}
```
Is there a way to get the value that would be retrieved by using 'this' in foo() while the thread is executing bar()? | No, you can't. In all the languages that use a stack that I know of, the contents of other stack frames are hidden from you. There are a few things you can do to get it, beyond the obvious passing it as a parameter. One of the aspect oriented frameworks might get you something. Also, you can get a bit of debugging info from [`Thread.getStackTrace()`](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getStackTrace()). | You have three choices. You can pass the calling object into the bar method:
```
Class A {
foo() {
new B().bar(this);
}
}
Class B {
bar(A caller) {
...
}
}
```
Or you can make class B an inner class of class A:
```
Class A {
foo() {
new B().bar();
}
Class B {
bar() {
A caller=A.this;
...
}
}
}
```
If all you need is the Class rather than the object instance, you have a third choice. By using `Thread.currentThread().getStackTrace()`, you can get the qualified name of a class at an arbitrary point in the stack, and use reflection to obtain the class instance. But that is so horrible, you should either fix your design, or (if you are writing your own debugger or something similar) try a simpler project until you know enough about java to figure this kind of thing out for yourself... | Java: Retrieve this for methods above in the stack | [
"",
"java",
""
] |
There are too many method for embedding flash in html, which way is the best?
Requirements are:
* Cross-browser support
* Support for alternative content (if flash is not supported by the browser)
* Possibility to require a specific version of the flash player
I have been reading about [SWFobject](http://code.google.com/p/swfobject/wiki/documentation), has anyone used it/tested? | In a project I work on we use SWFobject which works like a charm, it allows you to check for a specific version and also display alternative content if flash is not supported.
```
var fn = function() {
if(swfobject.hasFlashPlayerVersion("9.0.115"))
{
var att = { data:"flash.swf", width:"y", height:"x" };
var par = { menu: "false", flashvars: "" };
signUp = swfobject.createSWF(att, par);
}
}
swfobject.addDomLoadEvent(fn);
``` | I would highly recommend using [flashembed](http://flowplayer.org/tools/flash-embed.html). It has support for everything you need and more, without being that complicated to use. It was originally developed for embedding [flowplayer](http://flowplayer.org/), which I can also recommend, but it works for any flash file.
An example of how I use it:
```
flashembed("frontPageFlash",
{
src: "img/flash/FrontPage.swf",
width: "480",
height: "600",
bgcolor: "#ebebeb",
version: [9,0],
expressInstall:'scripts/expressinstall.swf'
},{
head1: "<%= frontPageFlashHead1 %>",
head2: "<%= frontPageFlashHead2 %>",
pitch1: "<%= frontPageFlashPitch1 %>",
pitch2: "<%= frontPageFlashPitch2 %>"
}
);
```
And where it is embedded I simply put:
```
<div id="frontPageFlash"></div>
``` | Best way to embed flash in html | [
"",
"javascript",
"html",
"flash",
"embed",
""
] |
I have been using PRETTY\_FUNCTION to output the current function name, however I have reimplemented some functions and would like to find out which functions are calling them.
In C++ how can I get the function name of the calling routine? | Here are two options:
1. You can get a full stacktrace (including the name, module, and offset of the calling function) with recent versions of glibc with the [GNU backtrace functions](http://www.gnu.org/software/libc/manual/html_node/Backtraces.html). See [my answer here](https://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes/77336#77336) for the details. This is probably the easiest thing.
2. If that isn't exactly what you're looking for, then you might try [libunwind](http://www.hpl.hp.com/research/linux/libunwind/), but it's going to involve more work.
Keep in mind that this isn't something you can know statically (as with PRETTY\_FUNCTION); you actually have to walk the stack to figure out what function called you. So this isn't something that's really worth doing in ordinary debug printfs. If you want to do more serious debugging or analysis, though, then this might be useful for you. | Here is a solution you can often use. It has the advantage of requiring no changes to the actual function code (*no adding calls to stackwalk functions, changing parameters to pass in function names, or linking to extra libraries.*). To get it working, you simply need to use a bit of preprocessor magic:
## Simple Example
```
// orignal function name was 'FunctionName'
void FunctionNameReal(...)
{
// Do Something
}
#undef FunctionName
#define FunctionName printf("Calling FunctionName from %s\n",__FUNCTION__);FunctionNameReal
```
You must rename your function temporarily, but see the note below for more suggestions. This will result in a `printf()` statement at each point of calling the function. Obviously, you have to make some arrangements if you are calling a member function, or need to capture the return value (*Like pass the function call and* `__FUNCTION__` *to a custom function that returns the same type...*), but the basic technique is the same. You might want to use `__LINE__` and `__FILE__` or some other preprocessor macros depending on which compiler you have. (This example is specifically for MS VC++, but probably works in others.)
Also, you might want to put something like this in your header surrounded by `#ifdef` guards to conditionally turn it on, which can handle renaming the actual function for you as well.
# UPDATE [2012-06-21]
I got a request to expand my answer. As it turns out, my above example is a bit simplistic. Here are some fully compiling examples of handling this, using C++.
## Full Source Example with a return value
Using a `class` with `operator()` makes this pretty straight forward. This first technique works for freestanding functions with and without return values. `operator()` just needs to reflect the same return as the function in question, and have matching arguments.
You can compile this with `g++ -o test test.cpp` for a non-reporting version and `g++ -o test test.cpp -DREPORT` for a version that displays the caller information.
```
#include <iostream>
int FunctionName(int one, int two)
{
static int calls=0;
return (++calls+one)*two;
}
#ifdef REPORT
// class to capture the caller and print it.
class Reporter
{
public:
Reporter(std::string Caller, std::string File, int Line)
: caller_(Caller)
, file_(File)
, line_(Line)
{}
int operator()(int one, int two)
{
std::cout
<< "Reporter: FunctionName() is being called by "
<< caller_ << "() in " << file_ << ":" << line_ << std::endl;
// can use the original name here, as it is still defined
return FunctionName(one,two);
}
private:
std::string caller_;
std::string file_;
int line_;
};
// remove the symbol for the function, then define a new version that instead
// creates a stack temporary instance of Reporter initialized with the caller
# undef FunctionName
# define FunctionName Reporter(__FUNCTION__,__FILE__,__LINE__)
#endif
void Caller1()
{
int val = FunctionName(7,9); // <-- works for captured return value
std::cout << "Mystery Function got " << val << std::endl;
}
void Caller2()
{
// Works for inline as well.
std::cout << "Mystery Function got " << FunctionName(11,13) << std::endl;
}
int main(int argc, char** argv)
{
Caller1();
Caller2();
return 0;
}
```
*Sample Output (Reporting)*
```
Reporter: FunctionName() is being called by Caller1() in test.cpp:44
Mystery Function got 72
Reporter: FunctionName() is being called by Caller2() in test.cpp:51
Mystery Function got 169
```
Basically, anywhere that `FunctionName` occurs, it replaces it with `Reporter(__FUNCTION__,__FILE__,__LINE__)`, the net effect of which is the preprocessor writing some object instancing with an immediate call to the `operator()` function. You can view the result (in gcc) of the preprocessor substitutions with `g++ -E -DREPORT test.cpp`. Caller2() becomes this:
```
void Caller2()
{
std::cout << "Mystery Function got " << Reporter(__FUNCTION__,"test.cpp",51)(11,13) << std::endl;
}
```
You can see that `__LINE__` and `__FILE__` have been substituted. (I'm not sure why `__FUNCTION__` still shows in the output to be honest, but the compiled version reports the right function, so it probably has something to do with multi-pass preprocessing or a gcc bug.)
## Full Source Example with a Class Member Function
This is a bit more complicated, but very similar to the previous example. Instead of just replacing the call to the function, we are also replacing the class.
Like the above example, you can compile this with `g++ -o test test.cpp` for a non-reporting version and `g++ -o test test.cpp -DREPORT` for a version that displays the caller information.
```
#include <iostream>
class ClassName
{
public:
explicit ClassName(int Member)
: member_(Member)
{}
int FunctionName(int one, int two)
{
return (++member_+one)*two;
}
private:
int member_;
};
#ifdef REPORT
// class to capture the caller and print it.
class ClassNameDecorator
{
public:
ClassNameDecorator( int Member)
: className_(Member)
{}
ClassNameDecorator& FunctionName(std::string Caller, std::string File, int Line)
{
std::cout
<< "Reporter: ClassName::FunctionName() is being called by "
<< Caller << "() in " << File << ":" << Line << std::endl;
return *this;
}
int operator()(int one, int two)
{
return className_.FunctionName(one,two);
}
private:
ClassName className_;
};
// remove the symbol for the function, then define a new version that instead
// creates a stack temporary instance of ClassNameDecorator.
// FunctionName is then replaced with a version that takes the caller information
// and uses Method Chaining to allow operator() to be invoked with the original
// parameters.
# undef ClassName
# define ClassName ClassNameDecorator
# undef FunctionName
# define FunctionName FunctionName(__FUNCTION__,__FILE__,__LINE__)
#endif
void Caller1()
{
ClassName foo(21);
int val = foo.FunctionName(7,9); // <-- works for captured return value
std::cout << "Mystery Function got " << val << std::endl;
}
void Caller2()
{
ClassName foo(42);
// Works for inline as well.
std::cout << "Mystery Function got " << foo.FunctionName(11,13) << std::endl;
}
int main(int argc, char** argv)
{
Caller1();
Caller2();
return 0;
}
```
Here is sample output:
```
Reporter: ClassName::FunctionName() is being called by Caller1() in test.cpp:56
Mystery Function got 261
Reporter: ClassName::FunctionName() is being called by Caller2() in test.cpp:64
Mystery Function got 702
```
The high points of this version are a class that decorates the original class, and a replacement function that returns a reference to the class instance, allowing the `operator()` to do the actual function call. | How do I find the name of the calling function? | [
"",
"c++",
"debugging",
""
] |
From reading here and around the net, I'm close to assuming the answer is "no", but...
Let's say I have an ASP.Net page that sometimes has a query string parameter. If the page has the query string parameter, I want to strip it off before, during, or after postback. The page already has a lot of client-side script (pure JavaScript and jQuery).
As an example, say I load:
```
http://myPage.aspx?QS=ABC
```
The QS parameter is necessary to control what appears on the page when it first loads and is set by the page that "calls" it. `myPage.aspx` has form elements that need to be filled in and has a submit button that does a postback. When the page completes the postback, I need to returned URL to be:
```
http://myPage.aspx
```
in order to avoid the client-side code that is called when the query string is present. In other words, after a submit I don't want the client side actions associated with the query string parameter to fire. I know I could append the form contents to the URL as query string parameters themselves and just redirect to the new URL and avoid the submit/postback, but that will require a lot more type checking on the codebehind to avoid bad data and casual spoofing. I supposed I could also set a hidden field in the codebehind and look at it along with the query string to cancel the client-side behavior if I am coming back from the postback, but that still leaves the query string intact basically forever and I want to get rid of it after the initial page load.
Any ideas or best practices?
PS - Is there anything I can do with the Form.Action property that won't break the postback behavior? | iam not sure this is what you are looking for, but if understand correctly you could do this:
-on page load check for the QS value, if its not there use a hidden input field.
-first time page loads with QS, do your normal processing and store QS value in a hidden input field.
-if no QS then use the hidden input value
-after postback, you could redirect to the same page, at that point you could user Request.Form[] to retrieve the hidden input field, still load the data properly but get rid of the QS.
it made sense in my head, i am not sure it make sense now, but i'll let you decide. | I would use an [**HTTPModule**](http://msdn.microsoft.com/en-us/library/ms972974.aspx) to intercept and rewrite the URL and query as it came in. I'm not 100%, but I don't believe this has any impact with viewstate.
It sounds (and looks) complex, but it's actually fairly trivial and open to a ton of refinement and extension (as per .NET in general). | Is there any way to modify query strings without breaking an ASP.Net postback? | [
"",
"asp.net",
"javascript",
"jquery",
"html",
"asp.net-2.0",
""
] |
Is this functionality going to be put into a later Java version?
Can someone explain why I can't do this, as in, the technical way Java's `switch` statement works? | Switch statements with `String` cases have been implemented in [Java SE 7](http://openjdk.java.net/projects/jdk7/features/), at least 16 years [after they were first requested.](https://bugs.java.com/bugdatabase/view_bug.do?bug_id=1223179) A clear reason for the delay was not provided, but it likely had to do with performance.
## Implementation in JDK 7
The feature has now been implemented in `javac` [with a "de-sugaring" process;](http://blogs.oracle.com/darcy/entry/project_coin_string_switch_anatomy) a clean, high-level syntax using `String` constants in `case` declarations is expanded at compile-time into more complex code following a pattern. The resulting code uses JVM instructions that have always existed.
A `switch` with `String` cases is translated into two switches during compilation. The first maps each string to a unique integer—its position in the original switch. This is done by first switching on the hash code of the label. The corresponding case is an `if` statement that tests string equality; if there are collisions on the hash, the test is a cascading `if-else-if`. The second switch mirrors that in the original source code, but substitutes the case labels with their corresponding positions. This two-step process makes it easy to preserve the flow control of the original switch.
## Switches in the JVM
For more technical depth on `switch`, you can refer to the JVM Specification, where the [compilation of switch statements](http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.10) is described. In a nutshell, there are two different JVM instructions that can be used for a switch, depending on the sparsity of the constants used by the cases. Both depend on using integer constants for each case to execute efficiently.
If the constants are dense, they are used as an index (after subtracting the lowest value) into a table of instruction pointers—the `tableswitch` instruction.
If the constants are sparse, a binary search for the correct case is performed—the `lookupswitch` instruction.
In de-sugaring a `switch` on `String` objects, both instructions are likely to be used. The `lookupswitch` is suitable for the first switch on hash codes to find the original position of the case. The resulting ordinal is a natural fit for a `tableswitch`.
Both instructions require the integer constants assigned to each case to be sorted at compile time. At runtime, while the `O(1)` performance of `tableswitch` generally appears better than the `O(log(n))` performance of `lookupswitch`, it requires some analysis to determine whether the table is dense enough to justify the space–time tradeoff. Bill Venners wrote [a great article](http://www.artima.com/underthehood/flowP.html) that covers this in more detail, along with an under-the-hood look at other Java flow control instructions.
## Before JDK 7
Prior to JDK 7, `enum` could approximate a `String`-based switch. This uses [the static `valueOf`](http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.3) method generated by the compiler on every `enum` type. For example:
```
Pill p = Pill.valueOf(str);
switch(p) {
case RED: pop(); break;
case BLUE: push(); break;
}
``` | If you have a place in your code where you can switch on a String, then it may be better to refactor the String to be an enumeration of the possible values, which you can switch on. Of course, you limit the potential values of Strings you can have to those in the enumeration, which may or may not be desired.
Of course your enumeration could have an entry for 'other', and a fromString(String) method, then you could have
```
ValueEnum enumval = ValueEnum.fromString(myString);
switch (enumval) {
case MILK: lap(); break;
case WATER: sip(); break;
case BEER: quaff(); break;
case OTHER:
default: dance(); break;
}
``` | Why can't I use switch statement on a String? | [
"",
"java",
"string",
"switch-statement",
""
] |
I have a simple function in which an array is declared with size
depending on the parameter which is int.
```
void f(int n){
char a[n];
};
int main() {
return 0;
}
```
This piece of code compiles fine on [GNU C++](http://en.wikipedia.org/wiki/G%2B%2B), but not on MSVC 2005.
I get the following compilation errors:
```
.\main.cpp(4) : error C2057: expected constant expression
.\main.cpp(4) : error C2466: cannot allocate an array of constant size 0
.\main.cpp(4) : error C2133: 'a' : unknown size
```
What can I do to correct this?
(I'm interested in making this work with MSVC,without using new/delete) | What you have found it one of the Gnu compiler's extensions to the C++ language. In this case, Visual C++ is completely correct. Arrays in C++ must be defined with a size that is a compile-time constant expression.
There was a feature added to C in the 1999 update to that language called variable length arrays, where this is legal. If you can find a C compiler that supports C99, which is not easy. But this feature is not part of standard C++, not is it going to be added in the next update to the C++ standard.
There are two solutions in C++. The first is to use a std::vector, the second is just to use operator `new []`:
```
char *a = new char [n];
```
While I was writing my answer, another one posted a suggestion to use \_alloca. I would strongly recommend against that. You would just be exchanging one non-standard, non-portable method for another one just as compiler-specific. | Your method of allocating from the stack is a g++ extension. To do the equivalent under MSVC, you need to use \_alloca:
```
char *a = (char *)_alloca(n);
``` | C++ array size dependent on function parameter causes compile errors | [
"",
"c++",
"arrays",
"parameters",
"declaration",
""
] |
Im trying to do a dialog box with jquery. In this dialog box Im going to have terms and conditions. The problem is that the dialog box is only displayed for the FIRST TIME.
This is the code.
JavaScript:
```
function showTOC()
{
$("#TOC").dialog({
modal: true,
overlay: {
opacity: 0.7,
background: "black"
}
})
}
```
HTML (a href):
```
<a class="TOClink" href="javascript:showTOC();">View Terms & Conditions</a>
<div id="example" title="Terms & Conditions">1..2..</div>
```
The problem I think is that when you close the dialog box the DIV is destroyed from the html code therfore it can never be displayed again on screen.
Can you please help!
Thanks | Looks like there is an issue with the code you posted. Your function to display the T&C is referencing the wrong div id. You should consider assigning the showTOC function to the onclick attribute once the document is loaded as well:
```
$(document).ready({
$('a.TOClink').click(function(){
showTOC();
});
});
function showTOC() {
$('#example').dialog({modal:true});
}
```
A more concise example which accomplishes the desired effect using the jQuery UI dialog is:
```
<div id="terms" style="display:none;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<a id="showTerms" href="#">Show Terms & Conditions</a>
<script type="text/javascript">
$(document).ready(function(){
$('#showTerms').click(function(){
$('#terms').dialog({modal:true});
});
});
</script>
``` | I encountered the same issue (dialog would only open once, after closing, it wouldn't open again), and tried the solutions above which did not fix my problem. I went back to the docs and realized I had a fundamental misunderstanding of how the dialog works.
The $('#myDiv').dialog() command creates/instantiates the dialog, but is not necessarily the proper way to **open** it. The proper way to open it is to instantiate the dialog with dialog(), then use dialog('open') to display it, and dialog('close') to close/hide it. This means you'll probably want to set the autoOpen option to false.
So the process is: instantiate the dialog on document ready, then listen for the click or whatever action you want to show the dialog. Then it will work, time after time!
```
<script type="text/javascript">
jQuery(document).ready( function(){
jQuery("#myButton").click( showDialog );
//variable to reference window
$myWindow = jQuery('#myDiv');
//instantiate the dialog
$myWindow.dialog({ height: 350,
width: 400,
modal: true,
position: 'center',
autoOpen:false,
title:'Hello World',
overlay: { opacity: 0.5, background: 'black'}
});
}
);
//function to show dialog
var showDialog = function() {
//if the contents have been hidden with css, you need this
$myWindow.show();
//open the dialog
$myWindow.dialog("open");
}
//function to close dialog, probably called by a button in the dialog
var closeDialog = function() {
$myWindow.dialog("close");
}
</script>
</head>
<body>
<input id="myButton" name="myButton" value="Click Me" type="button" />
<div id="myDiv" style="display:none">
<p>I am a modal dialog</p>
</div>
``` | jQuery Dialog Box | [
"",
"javascript",
"jquery",
"jquery-ui",
"dialog",
""
] |
I'm coming from a .net background and want to know the accepted way of creating a method that returns a boolean and modifies a string that was passed in via parameter. I understand Strings are immutable in Java so the below snippet will always produce an empty string. I am constrained to return boolean only. Exceptions can't be thrown. If I need to wrap the String class in, say, a StringHolder, what package could I find this in.
```
public static void DoStuff()
{
String msg = "";
if (GetMessage(msg))
{
System.out.println(msg);
}
}
``` | Use a java.lang.StringBuilder - basically a mutable String. However, it would be safer and more "Java style" to return the modified String. | I strongly suggest you do not use StringBuilder, holder or similar. They are hacks. You want to be working with Strings, not builders.
The most obvious approach is to return an object containing the data you want to return. David's [bombe.livejournal.com's] solution covers that, so I won't repeat it. However, I would suggest instead of trying to make it generic ball of data, make it specific. Make it like an object, perhaps it could even grow real behaviour. (And if you really want to go to town, hide the constructor and give it a static creation method instead.)
A second approach, not so well supported in Java, is to invert the calls. Instead of returning a result, tell a callback the result.
The (more important) usage code would be something like (it looks a bit odd because it isn't specific, nor is it generic):
```
String userMessage = thing.doStuff(new StuffHandler<String>() {
public String stuff(boolean success, String message) {
return message+" was "+(success ? "succesful" : "unsuccesful");
}
});
```
The implementation goes something like:
```
public interface StuffHandler<T> {
T stuff(boolean success, String message);
}
[...]
public <T> T doStuff(StuffHandler<T> handler) {
handler.stuff(isSuccess(), getMessage());
}
```
A third approach is simply to break the method in two. That may or may not be feasible. | Java String Parameters | [
"",
"java",
"parameters",
"string",
"idioms",
""
] |
EDIT: minor fixes (virtual Print; return mpInstance) following remarks in the answers.
I am trying to create a system in which I can derive a Child class from any Base class, and its implementation should replace the implementation of the base class.
All the objects that create and use the base class objects shouldn't change the way they create or call an object, i.e. should continue calling BaseClass.Create() even when they actually create a Child class.
The Base classes know that they can be overridden, but they do not know the concrete classes that override them.
And I want the registration of all the the Child classes to be done just in one place.
Here is my implementation:
```
class CAbstractFactory
{
public:
virtual ~CAbstractFactory()=0;
};
template<typename Class>
class CRegisteredClassFactory: public CAbstractFactory
{
public:
~CRegisteredClassFactory(){};
Class* CreateAndGet()
{
pClass = new Class;
return pClass;
}
private:
Class* pClass;
};
// holds info about all the classes that were registered to be overridden
class CRegisteredClasses
{
public:
bool find(const string & sClassName);
CAbstractFactory* GetFactory(const string & sClassName)
{
return mRegisteredClasses[sClassName];
}
void RegisterClass(const string & sClassName, CAbstractFactory* pConcreteFactory);
private:
map<string, CAbstractFactory* > mRegisteredClasses;
};
// Here I hold the data about all the registered classes. I hold statically one object of this class.
// in this example I register a class CChildClass, which will override the implementation of CBaseClass,
// and a class CFooChildClass which will override CFooBaseClass
class RegistrationData
{
public:
void RegisterAll()
{
mRegisteredClasses.RegisterClass("CBaseClass", & mChildClassFactory);
mRegisteredClasses.RegisterClass("CFooBaseClass", & mFooChildClassFactory);
};
CRegisteredClasses* GetRegisteredClasses(){return &mRegisteredClasses;};
private:
CRegisteredClasses mRegisteredClasses;
CRegisteredClassFactory<CChildClass> mChildClassFactory;
CRegisteredClassFactory<CFooChildClass> mFooChildClassFactory;
};
static RegistrationData StaticRegistrationData;
// and here are the base class and the child class
// in the implementation of CBaseClass::Create I check, whether it should be overridden by another class.
class CBaseClass
{
public:
static CBaseClass* Create()
{
CRegisteredClasses* pRegisteredClasses = StaticRegistrationData.GetRegisteredClasses();
if (pRegisteredClasses->find("CBaseClass"))
{
CRegisteredClassFactory<CBaseClass>* pFac =
dynamic_cast<CRegisteredClassFactory<CBaseClass>* >(pRegisteredClasses->GetFactory("CBaseClass"));
mpInstance = pFac->CreateAndGet();
}
else
{
mpInstance = new CBaseClass;
}
return mpInstance;
}
virtual void Print(){cout << "Base" << endl;};
private:
static CBaseClass* mpInstance;
};
class CChildClass : public CBaseClass
{
public:
void Print(){cout << "Child" << endl;};
private:
};
```
Using this implementation, when I am doing this from some other class:
```
StaticRegistrationData.RegisterAll();
CBaseClass* b = CBaseClass::Create();
b.Print();
```
I expect to get "Child" in the output.
What do you think of this design? Did I complicate things too much and it can be done easier? And is it OK that I create a template that inherits from an abstract class?
I had to use dynamic\_pointer (didn't compile otherwise) - is it a hint that something is wrong?
Thank you. | This sort of pattern is fairly common. I'm not a C++ expert but in Java you see this everywhere. The dynamic cast appears to be necessary because the compiler can't tell what kind of factory you've stored in the map. To my knowledge there isn't much you can do about that with the current design. It would help to know how these objects are meant to be used. Let me give you an example of how a similar task is accomplished in Java's database library (JDBC):
The system has a DriverManager which knows about JDBC drivers. The drivers have to be registered somehow (the details aren't important); once registered whenever you ask for a database connection you get a Connection object. Normally this object will be an OracleConnection or an MSSQLConnection or something similar, but the client code only sees "Connection". To get a Statement object you say connection.prepareStatement, which returns an object of type PreparedStatement; except that it's really an OraclePreparedStatement or MSSQLPreparedStatement. This is transparent to the client because the factory for Statements is in the Connection, and the factory for Connections is in the DriverManager.
If your classes are similarly related you may want to have a function that returns a specific type of class, much like DriverManager's getConnection method returns a Connection. No casting required.
The other approach you may want to consider is using a factory that has a factory-method for each specific class you need. Then you only need one factory-factory to get an instance of the Factory. Sample (sorry if this isn't proper C++):
```
class CClassFactory
{
public:
virtual CBaseClass* CreateBase() { return new CBaseClass(); }
virtual CFooBaseClass* CreateFoo() { return new CFooBaseClass();}
}
class CAImplClassFactory : public CClassFactory
{
public:
virtual CBaseClass* CreateBase() { return new CAImplBaseClass(); }
virtual CFooBaseClass* CreateFoo() { return new CAImplFooBaseClass();}
}
class CBImplClassFactory : public CClassFactory // only overrides one method
{
public:
virtual CBaseClass* CreateBase() { return new CBImplBaseClass(); }
}
```
As for the other comments criticizing the use of inheritance: in my opinion there is no difference between an interface and public inheritance; so go ahead and use classes instead of interfaces wherever it makes sense. Pure Interfaces may be more flexible in the long run but maybe not. Without more details about your class hierarchy it's impossible to say. | Usually, base class/ derived class pattern is used when you have an interface in base class, and that interface is implemented in derived class (IS-A relationship). In your case, the base class does not seem to have any connection with derived class - it may as well be void\*.
If there is no connection between base class and derived class, why do you use inheritance? What is the benefit of having a factory if factory's output cannot be used in a general way? You have
```
class CAbstractFactory
{
public:
virtual ~CAbstractFactory()=0;
};
```
This is perfectly wrong. A factory has to manufacture something that can be used immediately:
```
class CAbstractFactory
{
public:
virtual ~CAbstractFactory(){};
public:
CBaseClass* CreateAndGet()
{
pClass = new Class;
return pClass;
}
private:
CBaseClass* pClass;
protected:
CBaseClass *create() = 0;
};
```
In general, you're mixing inheritance, virtual functions and templates the way they should not be mixed. | Registering derived classes in C++ | [
"",
"c++",
"design-patterns",
"templates",
"abstract-class",
"factory",
""
] |
I wish to execute a javascript function after asp.net postback with out using ajax.
I've tried the following in my even method with no luck:
```
Page.ClientScript.RegisterStartupScript(GetType(), "ShowPopup", "showCheckOutPopIn('Livraison',556);");
``` | You should rather use the ScriptManager class, since the Page.ClientScript property is deprecated...
> The ClientScriptManager class is new in ASP.NET 2.0 and replaces Page class methods for managing scripts that are now deprecated.
> [Reference: MSDN - Page.ClientScript Property](http://msdn.microsoft.com/en-us/library/system.web.ui.page.clientscript.aspx)
The advantage with ScriptManager is that it works with asynchronous postbacks, so if you are using AJAX it will not work with the ClientScriptManager.
Your code would look like this:
```
ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowPopup", "showCheckOutPopIn('Livraison',556);", true);
```
Note also that if you are using AJAX and have a piece of javascript code, that you want executed on multiple postbacks, then you should refer to your UpdatePanel in the firstargument e.g.:
```
ScriptManager.RegisterStartupScript(MainUpdatePanel, typeof(string), "ShowPopup", "showCheckOutPopIn('Livraison',556);", true);
``` | **Solution**
I needed to add the script tags using the following overload.
```
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "script", "alert('Success!');", true);
```
Found : [Re: execute javascript after postback](http://forums.asp.net/p/1314545/2605856.aspx) | Execute javascript function after asp.net postback without Ajax | [
"",
"c#",
"asp.net",
".net-2.0",
""
] |
How do you build a hierarchical set of tags with data in PHP?
For example, a nested list:
```
<div>
<ul>
<li>foo
</li>
<li>bar
<ul>
<li>sub-bar
</li>
</ul>
</li>
</ul>
</div>
```
This would be build from flat data like this:
```
nested_array = array();
nested_array[0] = array('name' => 'foo', 'depth' => 0)
nested_array[1] = array('name' => 'bar', 'depth' => 0)
nested_array[2] = array('name' => 'sub-bar', 'depth' => 1)
```
It would be nice if it were nicely formatted like the example, too. | *Edit: Added formatting*
As already said in the comments, your data structure is somewhat strange. Instead of using text manipulation (like OIS), I prefer DOM:
```
<?php
$nested_array = array();
$nested_array[] = array('name' => 'foo', 'depth' => 0);
$nested_array[] = array('name' => 'bar', 'depth' => 0);
$nested_array[] = array('name' => 'sub-bar', 'depth' => 1);
$nested_array[] = array('name' => 'sub-sub-bar', 'depth' => 2);
$nested_array[] = array('name' => 'sub-bar2', 'depth' => 1);
$nested_array[] = array('name' => 'sub-sub-bar3', 'depth' => 3);
$nested_array[] = array('name' => 'sub-sub3', 'depth' => 2);
$nested_array[] = array('name' => 'baz', 'depth' => 0);
$doc = new DOMDocument('1.0', 'iso-8859-1');
$doc->formatOutput = true;
$rootNode = $doc->createElement('div');
$doc->appendChild($rootNode);
$rootList = $doc->createElement('ul');
$rootNode->appendChild($rootList);
$listStack = array($rootList); // Stack of created XML list elements
$depth = 0; // Current depth
foreach ($nested_array as $nael) {
while ($depth < $nael['depth']) {
// New list element
if ($listStack[$depth]->lastChild == null) {
// More than one level at once
$li = $doc->createElement('li');
$listStack[$depth]->appendChild($li);
}
$listEl = $doc->createElement('ul');
$listStack[$depth]->lastChild->appendChild($listEl);
array_push($listStack, $listEl);
$depth++;
}
while ($depth > $nael['depth']) {
array_pop($listStack);
$depth--;
}
// Add the element itself
$li = $doc->createElement('li');
$li->appendChild($doc->createTextNode($nael['name']));
$listStack[$depth]->appendChild($li);
}
echo $doc->saveXML();
```
Your formatting convention is kind of strange. Replace the last line with the following to achieve it:
```
printEl($rootNode);
function printEl(DOMElement $el, $depth = 0) {
$leftFiller = str_repeat("\t", $depth);
$name = preg_replace('/[^a-zA-Z]/', '', $el->tagName);
if ($el->childNodes->length == 0) {
// Empty node
echo $leftFiller . '<' . $name . "/>\n";
} else {
echo $leftFiller . '<' . $name . ">";
$printedNL = false;
for ($i = 0;$i < $el->childNodes->length;$i++) {
$c = $el->childNodes->item($i);
if ($c instanceof DOMText) {
echo htmlspecialchars($c->wholeText);
} elseif ($c instanceof DOMElement) {
if (!$printedNL) {
$printedNL = true;
echo "\n";
}
printEl($c, $depth+1);
}
}
if (!$printedNL) {
$printedNL = true;
echo "\n";
}
echo $leftFiller . '</' . $name . ">\n";
}
}
``` | You mean something like
```
function array_to_list(array $array, $width = 3, $type = 'ul', $separator = ' ', $depth = 0)
{
$ulSpace = str_repeat($separator, $width * $depth++);
$liSpace = str_repeat($separator, $width * $depth++);
$subSpace = str_repeat($separator, $width * $depth);
foreach ($array as $key=>$value) {
if (is_array($value)) {
$output[(isset($prev) ? $prev : $key)] .= "\n" . array_to_list($value, $width, $type, $separator, $depth);
} else {
$output[$key] = $value;
$prev = $key;
}
}
return "$ulSpace<$type>\n$liSpace<li>\n$subSpace" . implode("\n$liSpace</li>\n$liSpace<li>\n$subSpace", $output) . "\n$liSpace</li>\n$ulSpace</$type>";
}
echo array_to_list(array('gg', 'dsf', array(array('uhu'), 'df', array('sdf')), 'sdfsd', 'sdfd')) . "\n";
```
produces
```
<ul>
<li>
gg
</li>
<li>
dsf
<ul>
<li>
<ul>
<li>
uhu
</li>
</ul>
</li>
<li>
df
<ul>
<li>
sdf
</li>
</ul>
</li>
</ul>
</li>
<li>
sdfsd
</li>
<li>
sdfd
</li>
</ul>
```
I know theres a little gap there if a sub list don't start with an explanation.
Personally I usually don't really care how the HTML looks as long as its easy to work with in PHP.
Edit: OK, it works if you run it through this first ... :P
```
function flat_array_to_hierarchical_array(array &$array, $depth = 0, $name = null, $toDepth = 0)
{
if ($depth == 0) {
$temp = $array;
$array = array_values($array);
}
if (($name !== null) && ($depth == $toDepth)) {
$output[] = $name;
} else if ($depth < $toDepth) {
$output[] = flat_array_to_hierarchical_array(&$array, $depth + 1, $name, $toDepth);
}
while ($item = array_shift($array)) {
$newDepth = $item['depth'];
$name = $item['name'];
if ($depth == $newDepth) {
$output[] = $name;
} else if ($depth < $newDepth) {
$output[] = flat_array_to_hierarchical_array(&$array, $depth + 1, $name, $newDepth);
} else {
array_unshift($array, $item);
return $output;
}
}
$array = $temp;
return $output;
}
$arr = flat_array_to_hierarchical_array($nested_array);
echo array_to_list($arr);
``` | Build hierarchical html tags in PHP from flat data | [
"",
"php",
"html",
"hierarchy",
""
] |
I have a service that sometimes calls a batch file. The batch file takes 5-10 seconds to execute:
```
System.Diagnostics.Process proc = new System.Diagnostics.Process(); // Declare New Process
proc.StartInfo.FileName = fileName;
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.WaitForExit();
```
The file does exist and the code works when I run the same code in-console. However when it runs inside the service, it hangs up at `WaitForExit()`. I have to kill the batch file from the Process in order to continue. (I am certain the file exists, as I can see it in the processes list.)
How can I fix this hang-up?
# Update #1:
Kevin's code allows me to get output. One of my batch files is still hanging.
> "C:\EnterpriseDB\Postgres\8.3\bin\pg\_dump.exe" -i -h localhost -p 5432 -U postgres -F p -a -D -v -f "c:\backupcasecocher\backupdateevent2008.sql" -t "\"public\".\"dateevent\"" "DbTest"
The other batch file is:
> "C:\EnterpriseDB\Postgres\8.3\bin\vacuumdb.exe" -U postgres -d DbTest
I have checked the path and the `postgresql` path is fine. The output directory does exist and still works outside the service. Any ideas?
# Update #2:
Instead of the path of the batch file, I wrote the "C:\EnterpriseDB\Postgres\8.3\bin\pg\_dump.exe" for the `proc.StartInfo.FileName` and added all parameters to `proc.StartInfo.Arguments`. The results are unchanged, but I see the `pg_dump.exe` in the process window. Again this only happens inside the service.
# Update #3:
I have run the service with a user in the administrator group, to no avail. I restored `null` for the service's username and password
# Update #4:
I created a simple service to write a trace in the event log and execute a batch file that contains "dir" in it. It will now hang at `proc.Start();` - I tried changing the Account from LocalSystem to **User** and I set the admnistrator user and password, still nothing. | Here is what i use to execute batch files:
```
proc.StartInfo.FileName = target;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit
(
(timeout <= 0)
? int.MaxValue : timeout * NO_MILLISECONDS_IN_A_SECOND *
NO_SECONDS_IN_A_MINUTE
);
errorMessage = proc.StandardError.ReadToEnd();
proc.WaitForExit();
outputMessage = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
```
I don't know if that will do the trick for you, but I don't have the problem of it hanging. | ```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace VG
{
class VGe
{
[STAThread]
static void Main(string[] args)
{
Process proc = null;
try
{
string targetDir = string.Format(@"D:\adapters\setup");//this is where mybatch.bat lies
proc = new Process();
proc.StartInfo.WorkingDirectory = targetDir;
proc.StartInfo.FileName = "mybatch.bat";
proc.StartInfo.Arguments = string.Format("10");//this is argument
proc.StartInfo.CreateNoWindow = false;
proc.Start();
proc.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred :{0},{1}", ex.Message,ex.StackTrace.ToString());
}
}
}
}
``` | Service hangs up at WaitForExit after calling batch file | [
"",
"c#",
".net",
"service",
"windows-services",
""
] |
NHibernatians!
I have a table [dbo].[Wibble] and another table [dbo].[WibbleExtended].
[Wibble] is the main table and [WibbleExtended] is an optional table where some other fields are stored. There are far fewer entries in the [WibbleExtended] table than the main [Wibble] table. I think this was done back in the day to cure some space issues (Wibble has many rows and WibbleExtened has many columns).
The ID for each table is the same and comes from an external source.
I.e.
```
[dbo].[Wibble].[WibbleId]
```
and
```
[dbo].[WibbleExtended].[WibbleId]
```
are identical and is how the two tables relate.
N.B. I can't change the schema. I'm shoe-horning this onto a legacy system that I have almost no control over.
Searching around it seems that one-to-one mappings are problematic and the prevailing wisdom is to use two many-to-one mappings.
My mappings currently are:
```
<class name="Wibble" table="Wibble" >
<id name="Id" column="WibbleId" type="Int32">
<generator class="assigned"/>
</id>
<many-to-one name="WibbleExtended" class="WibbleExtended" column="WibbleId" not-null="false" cascade="all"/>
</class>
```
And
```
<class name="WibbleExtended" table="WibbleExtended" >
<id name="Id" column="WibbleId" type="Int32">
<generator class="assigned" />
</id>
<many-to-one name="Wibble" class="Wibble" column="WibbleId" not-null="true" />
</class>
```
The problem with this is I'm getting errors such as
```
System.IndexOutOfRangeException: Invalid index n for this SqlParameterCollection with Count=n.
```
I've looked around and this does look like the correct strategy, it's just falling at the final hurdle.
Is the problem the id generator? Other aspect of the mapping?
Free mince pie for the correct answer.
EDIT: Ok - here's what I did to solve this via @James Gregory.
1. Moved the unit tests from the WibbleExtended tests to the Wibble test class and made the necessary modifications.
2. Added the following to the Wibble.hbm.xml
```
<join table="WibbleExtended" optional="true">
<key column="WibbleId"/>
<property name="Blah1" column="Blah1" type="String" length="2000" not-null="false" />
<property name="Blah2" column="Blah2" type="String" length="1000" not-null="false" />
</join>
```
3. Added the corresponding properties to the Wibble POCO.
4. Deleted all code relating to WibbleExtended.
5. Run tests, all passed, checked in. Build passed. Went for an xmas beer (hence it's been a couple of days before I updated this! :-)) | Have you considered using the [Join element](http://nhibernate.info/doc/nhibernate-reference/mapping.html#mapping-declaration-join) that was introduced in NHibernate 2.0? This element allows you to join multiple tables to form one entity; that relationship can also be optional. | The error you are getting:
> Invalid index n for this
> SqlParameterCollection with Count=n.
is due to **two properties mapped to the same column**. Use insert=false and
update=false in one of the two.
reference <http://groups.google.com/group/nhusers/browse_thread/thread/84830b1257efd219> | NHibernate mapping - one-to-one (or one-to-zero) | [
"",
"c#",
"nhibernate",
"nhibernate-mapping",
""
] |
Say I have an interface like this:
```
public interface ISomeInterface
{
...
}
```
I also have a couple of classes implementing this interface;
```
public class SomeClass : ISomeInterface
{
...
}
```
Now I have a WPF ListBox listing items of ISomeInterface, using a custom DataTemplate.
The databinding engine will apparently not (that I have been able to figure out) allow me to bind to interface properties - it sees that the object is a SomeClass object, and data only shows up if SomeClass should happen to have the bound property available as a non-interface property.
How can I tell the DataTemplate to act as if every object is an ISomeInterface, and not a SomeClass etc.?
Thanks! | In order to bind to explicit implemented interface members, all you need to do is to use the parentheses. For example:
implicit:
```
{Binding Path=MyValue}
```
explicit:
```
{Binding Path=(mynamespacealias:IMyInterface.MyValue)}
``` | [This answer](http://social.msdn.microsoft.com/Forums/vstudio/en-US/1e774a24-0deb-4acd-a719-32abd847041d/data-templates-and-interfaces) from Microsoft forums by [Beatriz Costa - MSFT](http://social.msdn.microsoft.com/profile/beatriz%20costa%20-%20msft/?ws=usercard-inline) is worth reading (rather old):
> The data binding team discussed adding support for interfaces a while ago but ended up not implementing it because we could not come up with a good design for it. The problem was that interfaces don't have a hierarchy like object types do. Consider the scenario where your data source implements both `IMyInterface1` and `IMyInterface2` and you have DataTemplates for both of those interfaces in the resources: which DataTemplate do you think we should pick up?
>
> When doing implicit data templating for object types, we first try to find a `DataTemplate` for the exact type, then for its parent, grandparent and so on. There is very well defined order of types for us to apply. When we talked about adding support for interfaces, we considered using reflection to find out all interfaces and adding them to the end of the list of types. The problem we encountered was defining the order of the interfaces when the type implements multiple interfaces.
>
> The other thing we had to keep in mind is that reflection is not that cheap, and this would decrease our perf a little for this scenario.
>
> So what's the solution? You can't do this all in XAML, but you can do it easily with a little bit of code. The `ItemTemplateSelector` property of `ItemsControl` can be used to pick which `DataTemplate` you want to use for each item. In the `SelectTemplate` method for your template selector, you receive as a parameter the item you will template. Here, you can check for what interface it implements and return the `DataTemplate` that matches it. | WPF databinding to interface and not actual object - casting possible? | [
"",
"c#",
"wpf",
"data-binding",
""
] |
I'm using LINQ to SQL to pull records from a database, sort them by a string field, then perform some other work on them. Unfortunately the Name field that I'm sorting by comes out of the database like this
```
Name
ADAPT1
ADAPT10
ADAPT11
...
ADAPT2
ADAPT3
```
I'd like to sort the Name field in numerical order. Right now I'm using the Regex object to replace "ADAPT1" with "ADAPT01", etc. I then sort the records again using another LINQ query. The code I have for this looks like
```
var adaptationsUnsorted = from aun in dbContext.Adaptations
where aun.EventID == iep.EventID
select new Adaptation
{
StudentID = aun.StudentID,
EventID = aun.EventID,
Name = Regex.Replace(aun.Name,
@"ADAPT([0-9])$", @"ADAPT0$1"),
Value = aun.Value
};
var adaptationsSorted = from ast in adaptationsUnsorted
orderby ast.Name
select ast;
foreach(Adaptation adaptation in adaptationsSorted)
{
// do real work
}
```
The problem I have is that the foreach loop throws the exception
```
System.NotSupportedException was unhandled
Message="Method 'System.String Replace(System.String, System.String,
System.String)' has no supported translation to SQL."
Source="System.Data.Linq"
```
I'm also wondering if there's a cleaner way to do this with just one LINQ query. Any suggestions would be appreciated. | Force the hydration of the elements by enumerating the query (call ToList). From that point on, your operations will be against in-memory objects and those operations will not be translated into SQL.
```
List<Adaptation> result =
dbContext.Adaptation
.Where(aun => aun.EventID = iep.EventID)
.ToList();
result.ForEach(aun =>
aun.Name = Regex.Replace(aun.Name,
@"ADAPT([0-9])$", @"ADAPT0$1")
);
result = result.OrderBy(aun => aun.Name).ToList();
``` | Implement a `IComparer<string>` with your logic:
```
var adaptationsUnsorted = from aun in dbContext.Adaptations
where aun.EventID == iep.EventID
select new Adaptation
{
StudentID = aun.StudentID,
EventID = aun.EventID,
Name = aun.Name,
Value = aun.Value
};
var adaptationsSorted = adaptationsUnsorted.ToList<Adaptation>().OrderBy(a => a.Name, new AdaptationComparer ());
foreach (Adaptation adaptation in adaptationsSorted)
{
// do real work
}
public class AdaptationComparer : IComparer<string>
{
public int Compare(string x, string y)
{
string x1 = Regex.Replace(x, @"ADAPT([0-9])$", @"ADAPT0$1");
string y1 = Regex.Replace(y, @"ADAPT([0-9])$", @"ADAPT0$1");
return Comparer<string>.Default.Compare(x1, y1);
}
}
```
I didn't test this code but it should do the job. | Regex Replace to assist Orderby in LINQ | [
"",
"c#",
"regex",
"linq",
"linq-to-sql",
""
] |
I want to align my member variables based on a class template type but I'm not sure if it is actually possible.
The following is a (very) simple example of what I'd like to do
```
template<int Align>
class MyClass
{
private:
struct MyStruct
{
// Some stuff
} __declspec(align(Align));
__declspec(align(Align)) int myAlignedVariable;
};
```
So what I'd like is for Align to be a per-instance variable, and only through that is the align value of the class contents decided.
Unfortunately I always get the following error
```
error C2975: 'test::MyClass' : invalid template argument for 'Align', expected compile-time constant expression
```
So, is this actually possible or can the alignment only be possible using a fixed compile time constant? If not, can anyone think of a way around this?
Thanks :) | Custom alignment isn't in the standard, so how the compilers deal with it is up to them - looks like VC++ doesn't like combining templates with \_\_declspec.
I suggest a work-around using specialisation, something like this:
```
template<int A> struct aligned;
template<> struct aligned<1> { } __declspec(align(1));
template<> struct aligned<2> { } __declspec(align(2));
template<> struct aligned<4> { } __declspec(align(4));
template<> struct aligned<8> { } __declspec(align(8));
template<> struct aligned<16> { } __declspec(align(16));
template<> struct aligned<32> { } __declspec(align(32));
```
and then derive from that in your code:
```
template<int Align>
class MyClass
{
private:
struct MyStruct : aligned<Align> {
// stuff
};
};
```
This unfortunately breaks the POD-ness of MyStruct. It also doesn't work with built-in/existing types, so you'll have to use a wrapper for those.
```
aligned_t<int, 4> myAlignedVariable;
``` | Boost has solved this problem already. They use the technique in [boost::optional](http://www.boost.org/doc/libs/1_35_0/libs/optional/doc/html/index.html) ([link to header](http://www.boost.org/doc/libs/1_32_0/boost/optional/optional.hpp)), which has to hold enough space for an aligned, arbitrary type but can't (won't) actually instantiate that object on construction.
Their solution was to allocate a simple pool of bytes (char array) and use in-place new to construct objects at the desired location. The address given to in-place new can be of any arbitrary alignment.
That being said, you're saying that you're giving a very simple example in your question. What is the actual problem that you're trying to solve by implementing a class where every member has a user-specified alignment that doesn't vary per member but can vary per class instance? | Aligning Member Variables By Template Type | [
"",
"c++",
"templates",
""
] |
I'd like to know if there's a better approach to this problem. I want to resize a label (vertically) to accomodate certain amount of text. My label has a fixed width (about 60 chars wide before it must wrap), about 495 pixels. The font is also a fixed size (12points afaik), but the text is not.
What I want to do is increase the Label Height when there's a "NewLine" or the text must wrap; the idea is that the text is fully visible in the label. The AutoSize doesn't work because it will grow in width, not in height.
Of course I could count the number of NewLines and add: Newlines \* LineHeight, and then -given that I manage to put 60 chars per line, just divide the number of chars and add as many LineHeight pixels as needed.
I was wondering if there was a more professional way to do it. Is my approach too "lame" ?
Thanks in advance. | How about `Graphics.MeasureString`, with the overload that accepts a string, the font, and the max width? This returns a `SizeF`, so you can round round-off the `Height`.
```
using(Graphics g = CreateGraphics()) {
SizeF size = g.MeasureString(text, lbl.Font, 495);
lbl.Height = (int) Math.Ceiling(size.Height);
lbl.Text = text;
}
``` | System.Drawing.Graphics has a MeasureString method that you can use for this purpose. Use the overload that takes a string, a font, and an int "width" parameter; this last parameter specifies the maximum width allowed for the string - use the set width of your label for this parameter.
MeasureString returns a SizeF object. Use the Height property of this returned object to set the height of your label.
Note: to get a Graphics object for this purpose, you can call this.CreateGraphics. | Determine Label Size based upon amount of text and font size in Winforms/C# | [
"",
"c#",
".net",
"winforms",
""
] |
I have a bunch of pretty large CSV (comma separated values) files and I want to analyze them. SQL queries are ideal for this. So far I have been using MS Access to import the CSV files and execute queries on them. However, in addition to having a very bad SQL editor and having stupid arbitrary rules about when a query/table can be opened/edited/deleted, it is extremely slow. I can live with initial slowness when executing a query, but I really hate that it seems to re-execute it whenever I try to sort the table on another column, wait 5 minutes, or try to scroll.
Are there any better (free) tools for the job? (I would be willing to manually write a script to transform the CSV into something else if required)
Thanks!
Edit:
Thanks for all the answers! I'm going to try out SQL Server and if it works out, I'll accept that answer. Just a clarification: importing the data file is not necessarily a problem for me (although easy ways to do this are of course welcome). What I need is some program that subsequently allows me to quickly and efficiently execute (reasonably complex) queries on it.
FileHelpers isn't going to help me, because first of all I don't know any .NET languages and second of all, I had the data in Java, but I thought analyzing it would be a lot easier with SQL. Thanks for the answer though! | there's also an Oracle Express Edition.
I guess it depends on where you are already proficient. Or maybe where you **want to be** proficient. | Why don't just import them to MySQL, it's easy.
```
LOAD DATA LOCAL INFILE 'file.csv'
INTO TABLE some_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(field1, filed2, field3);
```
And then you can easilly run queries of any complexity... | Fast, Free Desktop SQL tool for CSV files | [
"",
"sql",
"csv",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.