Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I Have an MS Access Db that I built for a friend about 8 1/2 years ago. It now has a ton of important data, reports, and programming (important but crappy programming I will admit). I now need to revist this app and rewrite it in c#. But here is the catch, I no longer have access to MS Access (pun not intended -- well ok, it really was). And I dont want to download the trial version from MS because it is part of Office Professional and installing a trial of Professional will mess up my registered version of Small Buiness edt. So in effect, I would need to uninstall my version of office, install the trial, do what I need to do, then uninstall the trial and reinstall my version. Somewhere in that process, I am sure my computer would die.
So my question to the group would be, can you think of a way to extact the reports and forms from Access (data is easy) so I can continue the development in VS2008 and c#. | It will be far easier to find a friend with a version - any version - of Access installed and do what you need from there. It will take much less time, especially since there's code involved. | Intall VMWare on your machine, then create a new virtual machine with the necessary software installed. That way your main system stays. | Weird Access Question | [
"",
"c#",
"ms-access",
""
] |
As the question says it all.
Which framework in PHP is most closely cloned to ActiveRecord (Ruby on Rail).
I have gone through many frameworks claiming to be based on ActiveRecord ideology but unfortunately none really come any close to ActiveRecord. Wny?
Are there any such frameworks that I have missed? | I would say the most stable and up-to-date project resembling RoR is [PhpOnTrax](http://www.phpontrax.com/) | I think you're slightly confused. ActiveRecord itself isn't really a framework; Rails is the framework, ActiveRecord is the [object-relational mapper](http://en.wikipedia.org/wiki/Object-relational_mapping) (ORM, or database abstraction layer, if you prefer).
That said, [CakePHP](http://cakephp.org/) is probably the PHP framework with the most similarities to Rails, in general.
But either way, why not just *use* Rails? You won't be able to get anything like Rails on PHP. | Which PHP Framework is most closely cloned to ActiveRecord (RoR) | [
"",
"php",
"ruby",
"activerecord",
"frameworks",
""
] |
I need to define a class like this:
```
class Color
{
private:
union Data
{
unsigned int intValue;
unsigned char argbBytes[4];
}
private:
Data m_data;
};
```
Another way is of course define the data as integer and cast it to char array whenever necessary.
I'm wondering which one is the preferred way. The contradiction here is that I have remote memory of someone's remind not to use union anymore however it seems to be a cleaner solution in this case. | Unions can be fine, as long as you use them **carefully**.
They can be used in two ways:
1. To allow a single type of data to be accessed in several ways (as in your example, accessing a colour as an int or (as you probably intended) four chars)
2. To make a polymorphic type (a single value that could hold an int or a float for example).
Case (1) Is fine because you're not changing the meaning of the type - you can read and write any of the members of the union without breaking anything. This makes it a very convenient and efficient way of accessing the same data in slightly different forms.
Case (2) can be useful, but is extremely dangerous because you need to always access the right type of data from within the union. If you write an int and try to read it back as a float, you'll get a meaningless value. Unless memory usage is your primary consideration it might be better to use a simple struct with two members in it.
Unions used to be vital in C. In C++ there are usually much nicer ways to achieve the same ends (e.g. a class can be used to wrap a value and allow it to be accessed in different ways). However, if you need raw performance or have a critical memory situation, unions may still be a useful approach. | Is it good practice? Yes, but with some caveats.
Back in the days when memory was scarce, unions were popular to re-use memory. Those days are long gone and using unions for that purpose adds needless complexity. Don't do it.
If a union genuinely describes your data, as it does in the example you give, then it is a perfectly reasonable thing to do. However, be warned that you are building in some platform dependencies. On a different platform with different integer sizes or different byte ordering you might not get what you were expecting. | Is it a good practice to use unions in C++? | [
"",
"c++",
""
] |
When I print the CDC for a report control that I've created it appears tiny (less than 1 square inch on paper). How can I get the report to be printed to occupy the entire page ?
Or in other words, how can I make the entire report to appear in one printed page.
`CPrintDialog printDialog(FALSE);
printDialog.DoModal();`
```
CDC dcPrint;
if(dcPrint.Attach(printDialog.GetPrinterDC()))
{
int iHorzRes = dcPrint.GetDeviceCaps(HORZRES);
int iVertRes = dcPrint.GetDeviceCaps(VERTRES);
int iHorzResCDC = m_CDC.GetDeviceCaps(HORZRES);
int iVertResCDC = m_CDC.GetDeviceCaps(VERTRES);
dcPrint.m_bPrinting = TRUE;
dcPrint.BitBlt(0,0, iHorzRes, iVertRes, &m_CDC, iHorzResCDC, iVertResCDC, SRCCOPY);
CFont* pOldFont = dcPrint.SelectObject(&m_HeaderFont);
dcPrint.TextOut(0,0,"HelloWorld") ;
dcPrint.SelectObject(pOldFont);
CPrintInfo printInfo;
printInfo.m_rectDraw.SetRect(0,0, iHorzRes, iVertRes);
dcPrint.StartDoc("Report Print");
dcPrint.StartPage();
if(dcPrint.EndPage())
dcPrint.EndDoc();
else
dcPrint.AbortDoc();
}
dcPrint.DeleteDC();
```
m\_CDC is the memory DC that I use to buffer and display the entire report on screen. | As others have said, this is because, in general, the display resolution of printers is a lot higher than displays. Displays are usually 96 to 120DPI: at 96DPI this means that an image of 96 pixels (dots) by 96 pixels occupies approximately 1 square inch on the display. However, if you just take that image and print it out on a 600DPI printer, the size of the image will be about 1/6" by 1/6" - much smaller. This is a bane of the publishing world - images that look fine on displays often look either tiny or terrible when printed.
You could, as has been suggested, use StretchBlt rather than BitBlt to scale up your image. Depending on the difference between your display and printer, this will either look a bit blocky, or utterly hideously blocky.
A much better option is to rewrite your code that does the drawing of the control so that you've got a method that takes a device context (and some co-ordinates) and draws into it. Your normal window painting code can pass the memory DC to this routine and then BitBlt the result to the window, and your painting code can call this method with the printer DC and some suitable co-ordinates.
When writing this routine you'll have to worry about scaling: for example, you'll need to create fonts for the given device context, and with a scaling-indepdendant size (that is, specify the font size in points, not pixels), rather than relying on a pre-created font. | I suppose that you're not scaling your report to the printer's resolution. Typical screen resolution is 72 DPI (sometimes 96 DPI). Printer resolution can be 300DPI, 600DPI or higher.
You should repaint the report to the printer DC with all coordinates and sizes scaled to the printer's resolution. | Printed CDC appears tiny on paper | [
"",
"c++",
"mfc",
"printing",
""
] |
Say I have
```
var i = 987654321;
```
Is there an easy way to get an array of the digits, the equivalent of
```
var is = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
```
without `.ToString()`ing and iterating over the chars with `int.Parse(x)`? | ```
public Stack<int> NumbersIn(int value)
{
if (value == 0) return new Stack<int>();
var numbers = NumbersIn(value / 10);
numbers.Push(value % 10);
return numbers;
}
var numbers = NumbersIn(987654321).ToArray();
```
Alternative without recursion:
```
public int[] NumbersIn(int value)
{
var numbers = new Stack<int>();
for(; value > 0; value /= 10)
numbers.Push(value % 10);
return numbers.ToArray();
}
``` | I know there are probably better answers than this, but here is another version:
You can use `yield return` to return the digits in ascending order (according to weight, or whatever it is called).
```
public static IEnumerable<int> Digits(this int number)
{
do
{
yield return number % 10;
number /= 10;
} while (number > 0);
}
```
> 12345 => 5, 4, 3, 2, 1 | Is there an easy way to turn an int into an array of ints of each digit? | [
"",
"c#",
""
] |
I have two servlets which are running on different tomcat servers.
I and trying to call a servlet1 from servlet2 in the following way and wanted to write an object to output stream.
```
URL url=new URL("http://msyserver/abc/servlet1");
URLConnection con=url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
OutputStream os=con.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(pushEmailDTO);
oos.flush();
oos.close();
```
The problem is that i am unable to hit the servlet? I cannot figure out what i am missing. | I cannot unnderstand but it worked by adding the following line in the code.
```
con.getExpiration();
```
like this
```
URL url=new URL("http://msyserver/abc/servlet1");
URLConnection con=url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.getExpiration();//<----------
OutputStream os=con.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(pushEmailDTO);
oos.flush();
oos.close();
``` | You must create a connection via `url.connect()` before you can read/send data. This is counter-intuitive since the name `openConnection()` suggests that it does that already but the docs say:
> In general, creating a connection to a URL is a multistep process:
>
> 1. `openConnection()`
> 2. Manipulate parameters that affect the connection to the remote resource.
> 3. connect()
> 4. Interact with the resource; query header fields and contents.
This is why `getExpiration()` makes it work: It calls `connect()` for you. | Calling servlet from another servlet | [
"",
"java",
"servlets",
"urlconnection",
""
] |
I've heard of **window.status** and that it can be used to control the browser's status bar text, but I would like to know if there are better or newer methods that can do the same, with most modern browsers. Also, is it possible to change the status text multiple times after the page has loaded? | The feature you are looking for as been disabled for security reason.
Here is another solution to your problem.
You could create a DIV and put the position:fixed; at the bottom of the page, so people will always see it. | For security reasons, most modern browsers disable status bar access by default. | Reliable cross browser way of setting Status bar text | [
"",
"javascript",
"dom",
"statusbar",
""
] |
I am wondering if there is any performance differences between
1. String s = someObject.toString(); System.out.println(s);
and
2. System.out.println(someObject.toString());
Looking at the generated bytecode, it seems to have differences. Is the JVM able to optimize this bytecode at runtime to have both solutions providing same performances ?
In this simple case, of course solution 2 seems more appropriate but sometimes I would prefer solution 1 for readability purposes and I just want to be sure to not introduce performances "decreases" in critical code sections. | The creation of a temporary variable (especially something as small as a String) is inconsequential to the speed of your code, so you should stop worrying about this.
Try measuring the actual time spent in this part of your code and I bet you'll find there's no performance difference at all. The time it takes to call `toString()` and print out the result takes far longer than the time it takes to store a temporary value, and I don't think you'll find a measurable difference here at all.
Even if the bytecode looks different here, it's because `javac` is naive and your JIT Compiler does the heavy lifting for you. If this code really matters for speed, then it will be executed many, many times, and your JIT will select it for compilation to native code. It is highly likely that both of these compile to the same native code.
Finally, why are you calling `System.out.println()` in performance-critical code? If anything here is going to kill your performance, that will. | If you have critical code sections that demand performance, avoid using `System.out.println()`. There is more overhead incurred by going to standard output than there ever will be with a variable assignment.
Do solution 1.
**Edit**: or solution 2 | Java Optimizations | [
"",
"java",
"optimization",
"jit",
""
] |
I have following code:
```
Tools::Logger.Log(string(GetLastError()), Error);
```
`GetLastError()` returns a `DWORD` a numeric value, but the constructor of `std::string` doesn't accept a `DWORD`.
What can I do? | You want to read up on ostringstream:
```
#include <sstream>
#include <string>
int main()
{
std::ostringstream stream;
int i = 5;
stream << i;
std::string str = stream.str();
}
``` | You want to convert the number to a `string`:
```
std::ostringstream os;
os << GetLastError();
Log(os.str(), Error);
```
Or `boost::lexical_cast`:
```
Log(boost::lexical_cast<std::string>(GetLastError()), Error);
``` | How do I construct a std::string from a DWORD? | [
"",
"c++",
"numeric",
"stdstring",
""
] |
I develop a web application which uses a lot of JavaScript. I developed first portion of code on my machine and everything works just fine. Problems occurred after deploying to remote machine to IIS - the page runs but i.e. whole validation that I wrote doesn't run - I've checked under FF, IE6, IE7.. Are there any IIS properties to set to make it run?
**EDIT**
I've just found out that the problem is here:
```
<script type="text/javascript">
function validate() {
return validateTrees();
}
</script>
```
The validate() function is called here:
```
<asp:Button ID="btnSubmit" CssClass="button" runat="server" OnClientClick="return validate();" Text="Send for approval" />
```
And validateTrees() function is loaded dynamically from .js file by the control:
```
<cust:CustomTreeControl ID="CustomTreeControl 1" runat="server" />
```
which is placed just before this submit button. It seems that after deploy the browser can't find validateTrees() function. | Ok, that was silly, I didn't update paths to scripts after deployment. | IIS shouldn't affect your JS in anyway (as long as the JS files are present and accessed properly).
Could you post some code examples of what you have (simple test cases, preferably) and what you expect it to do and what it isn't doing, and what, if any, errors you are getting. | JavaScript after deploying web application to IIS | [
"",
"asp.net",
"javascript",
"iis",
""
] |
I need something similar to [String.format(...)](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)) method, but with lazy evaluation.
This lazyFormat method should return some object whose toString() method would then evaluate the format pattern.
I suspect that somebody has already done this. Is this available in any libararies?
I want to replace this (logger is log4j instance):
```
if(logger.isDebugEnabled() ) {
logger.debug(String.format("some texts %s with patterns %s", object1, object2));
}
```
with this:
```
logger.debug(lazyFormat("some texts %s with patterns %s", object1, object2));
```
I need lazyFormat to format string only if debug logging is enabled. | if you are looking for a "simple" solution:
```
public class LazyFormat {
public static void main(String[] args) {
Object o = lazyFormat("some texts %s with patterns %s", "looong string", "another loooong string");
System.out.println(o);
}
private static Object lazyFormat(final String s, final Object... o) {
return new Object() {
@Override
public String toString() {
return String.format(s,o);
}
};
}
}
```
outputs:
> some texts looong string with
> patterns another loooong string
you can of course add any `isDebugEnabled()` statement inside lazyFormat if you will. | It can be done by using parameter substitution in newest log4j 2.X version <http://logging.apache.org/log4j/2.x/log4j-users-guide.pdf>:
> 4.1.1.2 Parameter Substitution
>
> Frequently the purpose of logging is to provide information about what is happening in the system, which
> requires including information about the objects being manipulated. In
> Log4j 1.x this could be accomplished by doing:
```
if (logger.isDebugEnabled()) {
logger.debug("Logging in user " + user.getName() + " with id " + user.getId());
}
```
> Doing this repeatedly has the effect of making the
> code feel like it is more about logging than the actual task at hand.
> In addition, it results in the logging level being checked twice; once
> on the call to isDebugEnabled and once on the debug method. A better
> alternative would be:
```
logger.debug("Logging in user {} with id {}", user.getName(), user.getId());
```
> With the code above the logging level
> will only be checked once and the String construction will only occur
> when debug logging is enabled. | String.format with lazy evaluation | [
"",
"java",
"logging",
"lazy-evaluation",
""
] |
I have a class called `Questions` (plural). In this class there is an enum called `Question` (singular) which looks like this.
```
public enum Question
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}
```
In the `Questions` class I have a `get(int foo)` function that returns a `Questions` object for that `foo`. Is there an easy way to get the integer value off the enum so I can do something like this `Questions.Get(Question.Role)`? | Just cast the enum, e.g.
```
int something = (int) Question.Role;
```
The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is `int`.
However, as [cecilphillip](https://stackoverflow.com/users/333082/cecilphillip) points out, enums can have different underlying types.
If an enum is declared as a `uint`, `long`, or `ulong`, it should be cast to the type of the enum; e.g. for
```
enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
```
you should use
```
long something = (long)StarsInMilkyWay.Wolf424B;
``` | Since Enums can be any integral type (`byte`, `int`, `short`, etc.), a more robust way to get the underlying integral value of the enum would be to make use of the `GetTypeCode` method in conjunction with the `Convert` class:
```
enum Sides {
Left, Right, Top, Bottom
}
Sides side = Sides.Bottom;
object val = Convert.ChangeType(side, side.GetTypeCode());
Console.WriteLine(val);
```
This should work regardless of the underlying integral type. | Get int value from enum in C# | [
"",
"c#",
"enums",
"casting",
"int",
""
] |
I have some Delphi code that did this needs to be re-coded in C#:
```
procedure TDocSearchX.Decompress;
var
BlobStream:TBlobStream;
DecompressionStream:TDecompressionStream;
FileStream:TFileStream;
Buffer:array[0..2047] of byte;
count:integer;
begin
BlobStream:=TBlobStream.Create(DocQueryDATA,bmRead);
DecompressionStream:=TDecompressionStream.Create(BlobStream);
FileStream:=TFileStream.Create(FDocFile,fmCreate);
while True do
begin
Count := DecompressionStream.Read(Buffer, 2048);
if Count <> 0 then FileStream.Write(Buffer, Count) else Break;
end;
Blobstream.Free;
DecompressionStream.Free;
FileStream.Free;
end;
```
The contractor that wrote this is leaving and I need to decompress the image (that is currently stored in the database). I have been able to extract the image to a file but have no idea how to decompress it using C#? | It looks like `TDecompressionStream` probably uses ZLib. Here is a .NET library for ZLIB:
<http://www.componentace.com/zlib_.NET.htm> | To my knowledge there is no .Net Framework equivalent to the TDecompressionStream class. Are you able to write a small converter app in Delphi that decompresses the image? Then you are free to use whatever compression library (e.g. SharpZipLib) supporting .Net within your C# code. | What's the C# Equivalent of a Delphi TDecompressionStream? | [
"",
"c#",
".net",
"delphi",
"compression",
""
] |
I have a button control. Once the user clicks on it, the click event should fire and then the button should get disabled. How can I do this? I have the option to use JQuery or JavaScript or both.
Here is my button declaration:
```
<asp:Button
ID="Button1"
runat="server"
Text="Click Me"
onclick="Button1_Click"
/>
```
On the button click code behind, I have added a Response.Write(). That should get executed and then the button should be disabled | For whatever reason, [the HTML spec dictates that disabled elements should not be included in POST requests](http://www.w3.org/TR/html401/interact/forms.html#successful-controls). So, if you use JavaScript to disable the HTML element in the client-side onclick event, the input element will be disabled when the browser assembles the POST request, the server won't be properly notified which element raised the postback, and it won't fire server-side click event handlers.
When you set the **UseSubmitBehavior** property to false, ASP.NET renders an input element of type **button** instead of the regular input of type **submit** that the ASP.NET Button control normally generates. This is important because clicking a button element does not trigger the browser's form submit event.
Instead of relying on a browser form submission, ASP.NET will render a client-side call to \_\_doPostBack() within that button element's onclick handler. \_\_doPostBack will raise the postback explicitly, regardless of what POST data comes through in the request.
With the postback being raised independent of the browser submit event, you're freed of the previously mentioned HTML quirk. Then, you can set an OnClientClick of "this.disabled = true;", which will render as "this.disabled = true; \_\_doPostBack('Button1', '');", and things will work as intended. | add an OnClientClick="this.disabled = true;" to your button.
If you are using Asp.net Ajax you might want to look at using [PostBack Ritalin](http://encosia.com/downloads/postback-ritalin/). | Disable a button on click | [
"",
"asp.net",
"javascript",
"jquery",
""
] |
One table has "`John Doe <jdoe@aol.com>`" while another has "`jdoe@aol.com`". Is there a UDF or alternative method that'll match the email address from the first field against the second field?
This isn't going to be production code, I just need it for running an ad-hoc analysis. It's a shame the DB doesn't store both friendly and non-friendly email addresses.
**Update:** Fixed the formatting, should be `<` and `>` on the first one. | You could do a join using LOCATE method, something like...
```
SELECT * FROM table1 JOIN table2 ON (LOCATE(table2.real_email, table1.friend_email) > 0)
``` | I would split the email addresses on the last space- this should give you the email address. The exact code would depend on your database, but some rough pseudocode:
```
email = row.email
parts = email.split(" ")
real_email = parts[ len(parts) - 1 ]
``` | How to match two email fields where one contains friendly email address | [
"",
"sql",
"sql-server",
"t-sql",
"function",
"user-defined-functions",
""
] |
I have what I think is a simple "problem" to which I have found a couple of solutions but I am not sure which way to go andn the best practice in C#.
I have a master object (say a singleton) instanciated once during the lifespan of the application. This "MasterClass" creates a bunch of new type of objects, say "SlaveClass" every time MasterClass.Instance.CreateSlaveObject is called.
This MasterClass also monitors some other object for status change, and when that happens, notifies the SlaveClass objects it created of the change. Seems simple enough.
Since I come from the native C++ world, the way I did it first it to have an interface
```
Interface IChangeEventListener
{
void ChangeHappened();
}
```
from which I derived "SlaveClass". Then in my "MasterClass" i have:
```
...
IList<IChangeEventListener> slaveList;
...
CreateSlaveObject
{
...
slaveList.Add(slave);
}
...
ChangeHappened()
{
...
foreach(var slave in slaveList)
{
slave.ChangeHappened();
}
}
```
And this works. But I kept wondering in the back of my mind if there is another (better) way of doing this. So I researched a bit more on the topic and saw the C# events.
So instead of maintaining a collection of slaves in the MasterClass, I would basically inject the MasterClass into the ctor of SlaveClass (or via a property) and let the SlaveClass object add it's ChangeHappened as an event handler. this would be illustrated:
```
...Master...
public delegate void ChangeHappenedDelegate(object sender, NewsInfoArgs args);
public event NewUpdateDelegate ChangeHappenedEvent;
....
public SlaveClass (MasterClass publisher) //inject publisher service
{
publisher.ChangeHappenedEvent += ChangeHappened;
}
```
But this seems to be like an un-necessary coupling between the Slave and the Master, but I like the elegance of the provided build-in event notification mechanism.
So should I keep my current code, or move to the event based approach (with publisher injection)? and why?
Or if you can propose an alternative solution I might have missed, I would appreciate that as well. | Well, in my mind, events and interfaces like you showed are two sides of the same coin (at least in the context you described it), but they're really two *sides* of this.
The way I think about events is that "I need to subscribe to your event because I need you to tell me when something happens to you".
Whereas the interface way is "I need to call a method on you to inform you that something happened to me".
It can sound like the same, but it differs in who is talking, in both cases it is your "masterclass" that is talking, and that makes all the difference.
Note that if your slave classes have a method available that would be suitable for calling when something happened in your master class, you don't need the slave class to contain the code to hook this up, you can just as easily do this in your CreateSlaveClass method:
```
SlaveClass sc = new SlaveClass();
ChangeHappenedEvent += sc.ChangeHappened;
return sc;
```
This will basically use the event system, but let the MasterClass code do all the wiring of the events.
Does the SlaveClass objects live as long as the singleton class? If not, then you need to handle the case when they become stale/no longer needed, as in the above case (basically in both of yours and mine), you're holding a reference to those objects in your MasterClass, and thus they will never be eligible for garbage collection, unless you forcibly remove those events or unregisters the interfaces.
---
To handle the problem with the SlaveClass not living as long as the MasterClass, you're going to run into the same coupling problem, as you also noted in the comment.
One way to "handle" (note the quotes) this could be to not really link directly to the correct method on the SlaveClass object, but instead create a wrapper object that internally will call this method. The benefit from this would be that the wrapper object could use a WeakReference object internally, so that once your SlaveClass object is eligible for garbage collection, it might be collected, and then the next time you try to call the right method on it, you would notice this, and thus you would have to clean up.
For instance, like this (and here I'm typing without the benefit of a Visual Studio intellisense and a compiler, please take the meaning of this code, and not the syntax (errors).)
```
public class WrapperClass
{
private WeakReference _Slave;
public WrapperClass(SlaveClass slave)
{
_Slave = new WeakReference(slave);
}
public WrapperClass.ChangeHappened()
{
Object o = _Slave.Target;
if (o != null)
((SlaveClass)o).ChangeHappened();
else
MasterClass.ChangeHappenedEvent -= ChangeHappened;
}
}
```
In your MasterClass, you would thus do something like this:
```
SlaveClass sc = new SlaveClass();
WrapperClass wc = new WrapperClass(sc);
ChangeHappenedEvent += wc.ChangeHappened;
return sc;
```
Once the SlaveClass object is collected, the next call (but not sooner than that) from your MasterClass to the event handlers to inform them of the change, all those wrappers that no longer has an object will be removed. | I think it's just a matter of personal preference... personnally I like to use events, because it fits better in .NET "philosophy".
In your case, if the MasterClass is a singleton, you don't need to pass it to the constructor of the SlaveClass, since it can be retrieved using the singleton property (or method) :
```
public SlaveClass ()
{
MasterClass.Instance.ChangeHappenedEvent += ChangeHappened;
}
``` | C#:: When to use events or a collection of objects derived from an event handling Interface? | [
"",
"c#",
".net",
"events",
"delegates",
"collections",
""
] |
This one seems quite stupid, but I'm struglling from an hour to do this,
**How to Draw the Sine Wave in WPF??**
Thanks | Draw lines between points which you calculate with Math.Sin function. You'll have to decide how many points per cycle to use, a compromise between drawing speed and accuracy. Presumably you'll also need to scale the amplitude to suit the area on the screen, since Sin function will return a value between +1 and -1. | How are you doing your "Drawing". WPF doesn't have OnPaint events like Winforms so that might prove a little tricky. The way to do this in WinForms would have been to use the `Graphics.DrawBezier` method
```
e.Graphics.DrawBezier(new Pen(new SolidBrush(Color.Red)),
new Point(0, 100),
new Point(50, 0),
new Point(50, 200),
new Point(100, 100));
```
Maybe that's helpful, but I'm not even sure how to draw directly to the WPF Canvas.
A quick glance as MSDN shows that it has a BezierSegment control that maybe of use to you. | Draw Sine Wave in WPF | [
"",
"c#",
"wpf",
"math",
"drawing",
""
] |
Is there a tool out there for visually building Django templates?
Thanks | I haven't tried it personally, but a co-worker uses the free [ActiveState Komodo Edit](https://www.activestate.com/products/komodo-edit/) to edit Django templates, and the page I linked claims support for Django template editing.
There's also [netbeans-django](https://web.archive.org/web/20160316054658/https://code.google.com/p/netbeans-django/) that is building a Django plugin for Netbeans, but no idea how complete or how well it works.
I've read that TextMate has a "Django bundle" for editing code and templates if you're on a Mac. | There is also [PyCharm](http://www.jetbrains.com/pycharm/). | Visual Editor for Django Templates? | [
"",
"python",
"django",
"django-templates",
""
] |
As a freelance developer I deal with clients mostly by contacting them via email/im.
That isn't working bad, but I'm thinking of a more professional approach with client communication panel for my website.
Client basically will be given login/password and access it to see previews and comment them.
I'm fine with writing the application myself, but since so many developers have similar things on their websites, maybe there already is some solution that I could just reuse?
**//edit**
well, I should probably explain myself a bit clearer.
I'm fine with showing websites as they're being properly built/coded.
It's just communication and design stage that I'd like to move from mail/im to some simple web application.
Theoretically project management tools would do, but they overly complicated and I need just simple functionality to comment (in threads ideally) and attach images. Probably will want more later, but that's all I can think of now. | I found [collabtive](http://collabtive.o-dyn.de/) being a brilliant all-in-one software.
Got all I really needed. | It might already be 'overly complicated' but you could take a look at Request Tracker: <http://bestpractical.com/rt/> | Client's panel for my website | [
"",
"php",
""
] |
This is a .net problem with winforms, not asp.net.
I have a windows form with several tabs. I set data bindings of all controls when the form is loaded. But I have noticed that the data bindings of controls on the second tab do not work. Those bindings work only when the form is loaded and when I select the second tab. This brings the suspicion to me: data bindings work only when bound controls become visible.
Anyone can tell me whether this is true or not? It is not hard to test this but I would like to know some confirmation.
Thanks | You are correct. A data-bound control are not updated until the control is made visible.
The only reference I can find for this at the moment is [this MSDN thread](http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/70f0bbbb-07d5-4253-9a79-789700a8450a). | Your issue has to do with the behavior of the TabControl. See [Microsoft bug report](https://connect.microsoft.com/VisualStudio/feedback/details/351177). I posted a workaround for that problem which subclasses the TabControl and 'Iniatalizes' all the tab pages when the control is created or the handle is created. Below is the code for the workaround.
```
public partial class TabControl : System.Windows.Forms.TabControl
{
protected override void OnHandleCreated(EventArgs e_)
{
base.OnHandleCreated(e_);
foreach (System.Windows.Forms.TabPage tabPage in TabPages)
{
InitializeTabPage(tabPage, true, Created);
}
}
protected override void OnControlAdded(ControlEventArgs e_)
{
base.OnControlAdded(e_);
System.Windows.Forms.TabPage page = e_.Control as System.Windows.Forms.TabPage;
if ((page != null) && (page.Parent == this) && (IsHandleCreated || Created))
{
InitializeTabPage(page, IsHandleCreated, Created);
}
}
protected override void OnCreateControl()
{
base.OnCreateControl();
foreach (System.Windows.Forms.TabPage tabPage in TabPages)
{
InitializeTabPage(tabPage, IsHandleCreated, true);
}
}
//PRB: Exception thrown during Windows Forms data binding if bound control is on a tab page with uncreated handle
//FIX: Make sure all tab pages are created when the tabcontrol is created.
//https://connect.microsoft.com/VisualStudio/feedback/details/351177
private void InitializeTabPage(System.Windows.Forms.TabPage page_, bool createHandle_, bool createControl_)
{
if (!createControl_ && !createHandle_)
{
return;
}
if (createHandle_ && !page_.IsHandleCreated)
{
IntPtr handle = page_.Handle;
}
if (!page_.Created && createControl_)
{
return;
}
bool visible = page_.Visible;
if (!visible)
{
page_.Visible = true;
}
page_.CreateControl();
if (!visible)
{
page_.Visible = false;
}
}
}
``` | Does data binding work on invisible control? | [
"",
"c#",
".net",
"winforms",
""
] |
I have a MySQL 5.1 InnoDB table (`customers`) with the following structure:
```
int record_id (PRIMARY KEY)
int user_id (ALLOW NULL)
varchar[11] postcode (ALLOW NULL)
varchar[30] region (ALLOW NULL)
..
..
..
```
There are roughly 7 million rows in the table. Currently, the table is being queried like this:
```
SELECT * FROM customers WHERE user_id IN (32343, 45676, 12345, 98765, 66010, ...
```
in the actual query, currently over 560 `user_id`s are in the `IN` clause. With several million records in the table, this query is *slow*!
There are secondary indexes on table, the first of which being on `user_id` itself, which I thought would help.
I know that `SELECT(*)` is A Bad Thing and this will be expanded to the full list of fields required. However, the fields not listed above are more `int`s and `double`s. There are another 50 of those being returned, but they *are* needed for the report.
I imagine there's a much better way to access the data for the `user_id`s, but I can't think how to do it. My initial reaction is to remove the `ALLOW NULL` on the `user_id` field, as I understand `NULL` handling slows down queries?
I'd be very grateful if you could point me in a more efficient direction than using the `IN ( )` method.
**EDIT**
Ran EXPLAIN, which said:
```
select_type = SIMPLE
table = customers
type = range
possible_keys = userid_idx
key = userid_idx
key_len = 5
ref = (NULL)
rows = 637640
Extra = Using where
```
does that help? | First, check if there is an index on `USER_ID` *and make sure it's used*.
You can do it with running `EXPLAIN`.
Second, create a temporary table and use it in a `JOIN`:
```
CREATE TABLE temptable (user_id INT NOT NULL)
SELECT *
FROM temptable t
JOIN customers c
ON c.user_id = t.user_id
```
Third, how may rows does your query return?
If it returns almost all rows, then it just will be slow, since it will have to pump all these millions over the connection channel, to begin with.
`NULL` will not slow your query down, since the `IN` condition only satisfies non-`NULL` values which are indexed.
**Update:**
The index is used, the plan is fine except that it returns more than half a million rows.
Do you really need to put all these `638,000` rows into the report?
Hope its not printed: bad for rainforests, global warming and stuff.
Speaking seriously, you seem to need either aggregation or pagination on your query. | "Select \*" is not as bad as some people think; row-based databases will fetch the entire row if they fetch any of it, so in situations where you're not using a covering index, "SELECT \*" is essentially no slower than "SELECT a,b,c" (NB: There is sometimes an exception when you have large BLOBs, but that is an edge-case).
First things first - does your database fit in RAM? If not, get more RAM. No, seriously. Now, suppose your database is too huge to reasonably fit into ram (Say, > 32Gb) , you should try to reduce the number of random I/Os as they are probably what's holding things up.
I'll assuming from here on that you're running proper server grade hardware with a RAID controller in RAID1 (or RAID10 etc) and at least two spindles. If you're not, go away and get that.
You could definitely consider using a clustered index. In MySQL InnoDB you can only cluster the primary key, which means that if something else is currently the primary key, you'll have to change it. Composite primary keys are ok, and if you're doing a lot of queries on one criterion (say user\_id) it is a definite benefit to make it the first part of the primary key (you'll need to add something else to make it unique).
Alternatively, you might be able to make your query use a covering index, in which case you don't need user\_id to be the primary key (in fact, it must not be). This will only happen if all of the columns you need are in an index which begins with user\_id.
As far as query efficiency is concerned, WHERE user\_id IN (big list of IDs) is almost certainly the most efficient way of doing it from SQL.
BUT my biggest tips are:
* Have a goal in mind, work out what it is, and when you reach it, stop.
* Don't take anybody's word for it - try it and see
* Ensure that your performance test system is the same hardware spec as production
* Ensure that your performance test system has the same data size and kind as production (same schema is not good enough!).
* Use synthetic data if it is not possible to use production data (Copying production data may be logistically difficult (Remember your database is >32Gb) ; it may also violate security policies).
* If your query is optimal (as it probably already is), try tuning the schema, then the database itself. | faster way to use sets in MySQL | [
"",
"sql",
"mysql",
"optimization",
"performance",
"set",
""
] |
Let's say I have the following class
```
class Parent(object):
Options = {
'option1': 'value1',
'option2': 'value2'
}
```
And a subclass called Child
```
class Child(Parent):
Options = Parent.Options.copy()
Options.update({
'option2': 'value2',
'option3': 'value3'
})
```
I want to be able to override or add options in the child class. The solution I'm using works. But I'm sure there is a better way of doing it.
---
**EDIT**
I don't want to add options as class attributes because I have other class attributes that aren't options and I prefer to keep all options in one place. This is just a simple example, the actual code is more complicated than that. | One way would be to use keyword arguments to dict to specify additional keys:
```
Parent.options = dict(
option1='value1',
option2='value2',
)
Child.options = dict(Parent.options,
option2='value2a',
option3='value3',
)
```
If you want to get fancier, then using the descriptor protocol you can create a proxy object that will encapsulate the lookup. (just walk the owner.\_\_mro\_\_ from the owner attribute to the \_\_get\_\_(self, instance, owner) method). Or even fancier, crossing into the probably-not-a-good-idea territory, metaclasses/class decorators. | Semantically equivalent to your code but arguably neater:
```
class Child(Parent):
Options = dict(Parent.Options,
option2='value2',
option3='value3')
```
Remember, "life is better without braces", and by calling `dict` explicitly you can often avoid braces (and extra quotes around keys that are constant identifier-like strings).
See <http://docs.python.org/library/stdtypes.html#dict> for more details -- the key bit is "If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is retained", i.e. keyword args *override* key-value associations in the positional arg, just like the `update` method lets you override them). | A neat way of extending a class attribute in subclasses | [
"",
"python",
""
] |
`os.path.getmtime()` and `os.stat()` seem to return values in whole seconds only.
Is this the greatest resolution possible on either a Windows or OSX file system, or is there a way of getting greater resolution on file times? | [The documentation for os.stat()](http://docs.python.org/library/os.html#os.stat) has a note that says:
> The exact meaning and resolution of
> the st\_atime, st\_mtime, and st\_ctime
> members depends on the operating
> system and the file system. For
> example, on Windows systems using the
> FAT or FAT32 file systems, st\_mtime
> has 2-second resolution, and st\_atime
> has only 1-day resolution. See your
> operating system documentation for
> details.
On for instance [Windows](http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx), the FILETIME structure used to represent file times uses a 100-nanosecond resolution. I would expect Python to "know" this, and give you the best possible resolution. Is it possible that you're using files on a FAT filesystem? | HFS+ (used by OS X) has a date resolution of [one second](http://en.wikipedia.org/wiki/HFS_Plus). | Python: Getting file modification times with greater resolution than a second | [
"",
"python",
"windows",
"macos",
"filesystems",
"timestamp",
""
] |
I'm wondering if anyone has any experience converting User controls to Web controls?
Ideally, I'd like to offload some of the design work to others, who would give me nicely laid out User Controls. Then, I could go through the process of converting, compiling, testing and deploying.
Until MS comes up with the magic "Convert to Server Control" option, it looks like I'm pretty well stuck with re-writing from scratch. Any ideas? | Is there a reason you *must* convert these user controls to server controls? Remember that it is possible to [compile a user control into an assembly](http://www.nathanblevins.com/Articles/Compile-a-Web-User-Control-into-a-DLL-.Net-c-.aspx). | You are right there is no magic bullet here but since you already have a User Control its not that difficult.
1. Make sure all properties, events, etc. are set in the code behind since you won't have any mark up when you're done
2. Create a new Server Control
3. Paste all of the event handling and property setting code into the new control
4. override the Render method for each child control call the RenderControl Method passing in the supplied HtmlTextWriter
```
protected override void Render(HtmlTextWriter writer)
{
TextBox box = new TextBox();
//Set all the properties here
box.RenderControl(writer);
base.Render(writer);
}
``` | Convert User Controls to Server Controls | [
"",
"c#",
".net",
"user-controls",
"servercontrols",
""
] |
In my application, I alter some part of XML files, which begin like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: version control yadda-yadda $ -->
<myElement>
...
```
Note the blank line before `<myElement>`. After loading, altering and saving, the result is far from pleasing:
```
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: version control yadda-yadda $ --><myElement>
...
```
I found out that the whitespace (one newline) between the comment and the document node is not represented in the DOM at all. The following self-contained code reproduces the issue reliably:
```
String source =
"<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<!-- foo -->\n<empty/>";
byte[] sourceBytes = source.getBytes("UTF-16");
DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc =
builder.parse(new ByteInputStream(sourceBytes, sourceBytes.length));
DOMImplementationLS domImplementation =
(DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
System.out.println(lsSerializer.writeToString(doc));
// output: <?xml version="1.0" encoding="UTF-16"?>\n<!-- foo --><empty/>
```
Does anyone have an idea how to avoid this? Essentially, I want the output to be the same as the input. (I know that the xml declaration will be regenerated because it's not part of the DOM, but that's not an issue here.) | The root cause is that the standard [DOM Level 3](http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-1590626202) cannot represent Text nodes as children of a Document without breaking the spec. Whitespace will be dropped by any compliant parser.
```
Document --
Element (maximum of one),
ProcessingInstruction,
Comment,
DocumentType (maximum of one)
```
If you require a standards-compliant solution and the objective is readability rather than 100% reproduction, I would look for it in your output mechanism. | I had the same problem. My solution was to write my own XML parser: [DecentXML](http://code.google.com/p/decentxml/)
Main feature: it can 100% preserve the original input, whitespace, entities, everything. It won't bother you with the details, but if your code needs to generate XML like this:
```
<element
attr="some complex value"
/>
```
then you can. | How to keep whitespace before document element when parsing with Java? | [
"",
"java",
"xml",
"dom",
"parsing",
"whitespace",
""
] |
At work we have Oracle 7. I would like to use python to access the DB.
Has anyone done that or knows how to do it?
I have Windows XP, Python 2.6 and the cx\_oracle version for python 2.6
However, when I try to import cx\_oracle i get the following error:
```
ImportError: DLL load failed the module could not be found
```
Any help is appreciated!
Matt | cx\_Oracle is currently only being provided with linkage to the 9i, 10g, and 11i clients. Install one of these clients and configure it to connect to the Oracle 7 database using the proper ORACLE\_SID. | Make sure you have the location of the oracle .dll (o files set in your PATH environment variable. The location containing oci.dll should suffice. | cx_oracle and oracle 7? | [
"",
"python",
"cx-oracle",
""
] |
I have a jQuery UI dialog box with a form. I would like to simulate a click on one of the dialog's buttons so you don't have to use the mouse or tab over to it. In other words, I want it to act like a regular GUI dialog box where simulates hitting the "OK" button.
I assume this might be a simple option with the dialog, but I can't find it in the [jQuery UI documentation](http://jqueryui.com/demos/dialog/). I could bind each form input with keyup() but didn't know if there was a simpler/cleaner way. Thanks. | I don't know if there's an option in the ***jQuery UI widget***, but you could simply bind the `keypress` event to the div that contains your dialog...
```
$('#DialogTag').keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
//Close dialog and/or submit here...
}
});
```
This'll run no matter what element has the focus in your dialog, which may or may not be a good thing depending on what you want.
If you want to make this the default functionality, you can add this piece of code:
```
// jqueryui defaults
$.extend($.ui.dialog.prototype.options, {
create: function() {
var $this = $(this);
// focus first button and bind enter to it
$this.parent().find('.ui-dialog-buttonpane button:first').focus();
$this.keypress(function(e) {
if( e.keyCode == $.ui.keyCode.ENTER ) {
$this.parent().find('.ui-dialog-buttonpane button:first').click();
return false;
}
});
}
});
```
Here's a more detailed view of what it would look like:
```
$( "#dialog-form" ).dialog({
buttons: { … },
open: function() {
$("#dialog-form").keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
$(this).parent().find("button:eq(0)").trigger("click");
}
});
};
});
``` | I have summed up the answers above & added important stuff
```
$(document).delegate('.ui-dialog', 'keyup', function(e) {
var target = e.target;
var tagName = target.tagName.toLowerCase();
tagName = (tagName === 'input' && target.type === 'button')
? 'button'
: tagName;
isClickableTag = tagName !== 'textarea' &&
tagName !== 'select' &&
tagName !== 'button';
if (e.which === $.ui.keyCode.ENTER && isClickableTag) {
$(this).find('.ui-dialog-buttonset button').eq(0).trigger('click');
return false;
}
});
```
**Advantages:**
1. Disallow enter key on non compatible elements like `textarea` , `select` , `button` or inputs with type button , imagine user clicking enter on `textarea` and get the form submitted instead of getting new line!
2. The binding is done once , avoid using the dialog 'open' callback to bind enter key to avoid binding the same function again and again each time the dialog is 'open'ed
3. Avoid changing existing code as some answers above suggest
4. Use 'delegate' instead of the deprecated 'live' & avoid using the new 'on' method to allow working with older versions of jquery
5. Because we use delegate , that mean the code above can be written even before initializing dialog. you can also put it in head tag even without `$(document).ready`
6. Also delegate will bind only one handler to `document` and will not bind handler to each dialog as in some code above , for more efficiency
7. Works even with dynamically generated dialogs like `$('<div><input type="text"/></div>').dialog({buttons: .});`
8. Worked with ie 7/8/9!
9. Avoid using the slow selector `:first`
10. Avoid using hacks like in answers [here](https://stackoverflow.com/questions/477691/) to make a hidden submit button
**Disadvantages:**
1. Run the first button as the default one , you can choose another button with `eq()` or call a function inside the if statement
2. All of dialogs will have same behavior you can filter it by making your selector more specific ie '#dialog' instead of `'.ui-dialog'`
I know the question is old but I have had the same need, so, I shared the solution I've used. | Submit jQuery UI dialog on <Enter> | [
"",
"javascript",
"jquery",
"jquery-ui",
""
] |
I'm working with mySQL, and I'm in a situation where I need to select data from one table that matches an ID at any level in parent -> child data hierarchy in the other table.
Further more, I would like to resolve this with a well written SQL query, rather than a recursive function in my PHP code, as this feature will be used quite a bit.
I did try searching, and I have stumbled upon numerous similar problems (most of them being resolved), however none of them helped me.
To help illustrate the situation, here's my current setup
table "articles":
* article\_id
* category\_id
* ...
table categories
* category\_id
* parent\_id
* ...
I need to select all the articles from "articles" where "articles.category\_id" is, let's say, 10. But also receive all the articles from all categories from the tree the "categories.category\_id" 10 belongs to.
Meaning, where "10" is the parent and all of it's children, and upwards where 10 is the child and all of it's parents.
Possible without a recursive php function?
Thank you. | This is possible to do in `MySQL`, but it takes a little effort. You'll have to write a function like this:
```
CREATE FUNCTION hierarchy_connect_by_parent_eq_prior_id(value INT) RETURNS INT
NOT DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE _id INT;
DECLARE _parent INT;
DECLARE _next INT;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET @id = NULL;
SET _parent = @id;
SET _id = -1;
IF @id IS NULL THEN
RETURN NULL;
END IF;
LOOP
SELECT MIN(id)
INTO @id
FROM categories
WHERE parent = _parent
AND id > _id;
IF @id IS NOT NULL OR _parent = @start_with THEN
SET @level = @level + 1;
RETURN @id;
END IF;
SET @level := @level - 1;
SELECT id, parent
INTO _id, _parent
FROM categories
WHERE id = _parent;
END LOOP;
END
```
and use it in a query:
```
SELECT id, parent, level
FROM (
SELECT hierarchy_connect_by_parent_eq_prior_id(id) AS id, @level AS level
FROM (
SELECT @start_with := 0,
@id := @start_with,
@level := 0
) vars, categories
WHERE @id IS NOT NULL
) ho
JOIN categories hi
ON hi.id = ho.id
```
See this entry in my blog for more detail:
* [**Hierarchical queries in MySQL**](http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/) | It is not possible to fetch an entire tree in one query using the Adjacency List design you're using, given that you're using MySQL.
Some other brands of database support SQL extensions to handle this kind of design. Oracle, Microsoft SQL Server, IBM DB2, and PostgreSQL 8.4 (currently in beta) support SQL extensions.
Other database designs exist that allow you to query trees more efficiently. This question has been addressed many times on StackOverflow, on blogs, and in articles.
You can also read "[Trees and Hierarchies in SQL for Smarties](https://rads.stackoverflow.com/amzn/click/com/1558609202)" by Joe Celko, which goes into several such designs in depth. | MySQL parent -> child query | [
"",
"php",
"mysql",
"hierarchical-data",
""
] |
I program in PHP mostrly and Ruby sometimes I happen to be in need of a way to implements those "hash arguments" into my PHP funcions (Like, say, an HTML select helper)
```
draw_select :name => :id, :onclick => 'alert(this.value)'
```
The problem in PHP is that I would have to define an argument order to implement many possible attributes.
I have been thinking of just define 1 string argument and use json\_decode() so i can pass arguments like this:
```
draw_select("'name': 'id', 'onclick': 'alert(this.value)' ")
```
the definition would be as follows:
```
function draw_select($string) {
// use json_decode here and pass them as variables
}
```
Do you know a smarter way to do this.. or you think that triying to to this in PHP does actually makes any sense at all?
**Edited to add: I'm looking for a 'alternative' alternative to just pass a signle array as an argument like function(array(...))** | PHP definitely is lacking some sugar in this aspect. I do a lot of Python also and I dearly miss named arguments when using PHP. With PHP, however, whenever I have a function that will need to accept a multitude of options I simply accept one or two required/important arguments, and an array for the rest:
```
function draw_select($name, $options = array(), $html_options = array()) {
}
```
This is the way libraries like CodeIgniter and CakePHP handle the same `<select>` scenario.
Personally, using JSON in this situation brings no real benefit when PHP's associative arrays are so powerful. Just stick to what the language gives you, and this is the way to do it with PHP. | Why not pass an array instead?
```
draw_select(array(
'name'=> 'id',
'onclick'=> 'alert(this.value)'
));
``` | Ruby-like array arguments implementation in PHP | [
"",
"php",
"json",
"ruby",
"language-comparisons",
""
] |
I've been wondering why would I use Exceptions in my PHP. Let's take a look at a simple example:
```
class Worker
{
public function goToWork()
{
return $isInThatMood ?
// Okay, I'll do it.
true :
// In your dreams...
false;
}
}
$worker = new Worker;
if (!$worker->goToWork())
{
if (date('l',time()) == 'Sunday')
echo "Fine, you don't have to work on Sundays...";
else
echo "Get your a** back to work!";
}
else
echo "Good.";
```
Is there a reason for me to use Exceptions for that kind of code? Why? How would the code be built?
And what about code that may produce errors:
```
class FileOutputter
{
public function outputFile($file)
{
if (!file_exists($file))
return false;
return file_get_contents($file);
}
}
```
Why would I use Exceptions in the above case? I have a feeling that Exceptions help you to recognize the type of the problem, which occured, true?
So, am I using Exceptions appropriately in this code:
```
class FileOutputter
{
public function outputFile($file)
{
if (!file_exists($file))
return throw new Exception("File not found.",123);
try
{
$contents = file_get_contents($file);
}
catch (Exception $e)
{
return $e;
}
return $contents;
}
}
```
Or is that poor? Now the underlying code can do this:
```
$fo = new FileOutputter;
try
{
$fo->outputFile("File.extension");
}
catch (Exception $e)
{
// Something happened, we could either display the error/problem directly
echo $e->getMessage();
// Or use the info to make alternative execution flows
if ($e->getCode() == 123) // The one we specified earlier
// Do something else now, create "an exception"
}
```
Or am I completely lost here? | ## When should I use an exception?
You use an exception to indicate an **exceptional** condition; that is, something which prevents a method from fulfilling its contract, and which shouldn't have occurred at that level.
For example, you might have a method, `Record::save()`, which saves changes to a record into a database. If, for some reason, this can't be done (e.g. a database error occurs, or a data constraint is broken), then you could throw an exception to indicate failure.
## How do I create custom exceptions?
Exceptions are usually named such that they indicate the nature of the error, for example, `DatabaseException`. You can subclass `Exception` to create custom-named exceptions in this manner, e.g.
```
class DatabaseException extends Exception {}
```
(Of course, you could take advantage of inheritance to give this exception some additional diagnostic information, such as connection details or a database error code, for example.)
## When *shouldn't* I use an exception?
Consider a further example; a method which checks for file existence. This should probably *not* throw an exception if the file doesn't exist, since the purpose of the method was to perform said check. However, a method which opens a file and performs some processing *could* throw an exception, since the file was expected to exist, etc.
Initially, it's not always clear when something is and isn't exceptional. Like most things, experience will teach you, over time, when you should and shouldn't throw an exception.
## Why use exceptions instead of returning special error codes, etc?
The useful thing about exceptions is that they immediately leap out of the current method and head up the call stack until they're caught and handled, which means you can move error-handling logic higher up, although ideally, not too high.
By using a clear mechanism to deal with failure cases, you automatically kick off the error handling code when something bad happens, which means you can avoid dealing with all sorts of magic sentinel values which have to be checked, or worse, a global error flag to distinguish between a bunch of different possibilities. | I'm not a PHP programmer, but this looks similar to C#.
Typically you'd want to throw errors if it is a point of no return. Then you would be able to log something to show that the impossible happened.
If you can tell that the file doesn't exist then you could just say that. No real need in my mind to also throw an exception.
Now if the file was found and you are processing it, and say only half the file was uploaded and you had no way of telling that without an exception, then it'd be nice to have around.
I would say it's a good design practice to avoid the catch all exceptions "catch (Exception $e)" and design by contract instead, just like you seem to be doing in the prior example. I would at first be more specific with the type of exception being thrown and then work from there if needed. Otherwise, stay away from the try->catch and exceptions. | Why and how would you use Exceptions in this sample PHP code? | [
"",
"php",
"exception",
"error-handling",
""
] |
Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:
```
def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True
```
The following is a bit shorter, but also less efficient since a third sequence is created:
```
def comp2(a, b):
for l, r in map(None, a, b):
if l != r:
return False
return True
```
Shoehorning one of those examples into a list comprehension isn't really what I'm looking for either.
Edit: Ideally I am looking for a solution that doesn't create another sequence during the comparison. | Convert both sequences to lists, and use builtin list comparison. It should be sufficient, unless your sequences are really large.
```
list(a) == list(b)
```
Edit:
Testing done by schickb shows that using tuples is slightly faster:
```
tuple(a) == tuple(b)
``` | You can determine the equality of any two iterables (strings, tuples, lists, even custom sequences) without creating and storing duplicate lists by using the following:
```
all(x == y for x, y in itertools.izip_longest(a, b))
```
Note that if the two iterables are not the same length, the shorter one will be padded with `None`s. In other words, it will consider `[1, 2, None]` to be equal to `(1, 2)`.
**Edit:** As Kamil points out in the comments, `izip_longest` is only available in Python 2.6. However, [the docs for the function](http://docs.python.org/library/itertools.html#itertools.izip_longest) also provide an alternate implementation which should work all the way back to 2.3.
**Edit 2:** After testing on a few different machines, it looks like this is only faster than `list(a) == list(b)` in certain circumstances, which I can't isolate. Most of the time, it takes about seven times as long. However, I also found `tuple(a) == tuple(b)` to be consistently at least twice as fast as the `list` version. | Elegant way to compare sequences | [
"",
"python",
""
] |
I've successfully added an C++ object to a QWebFrame with [addToJavaScriptWindowObject](https://doc.qt.io/qt-4.8/qwebframe.html#addToJavaScriptWindowObject),
and can call a slot on that object from javascript.
But what I really want to do is have one of those slots return a new object. For example, I have a slot like this, which returns a QObject derived class instance:
```
MyObject* MyApp::helloWorld()
{
//MyObject is dervied from QObject
return new MyObject();
}
```
I can call this slot from javascript successfully like this
```
var foo=myapp.helloWorld();
```
But foo appears to be empty, I can't call any slots or access any
properties on it from Javascript.
Any ideas on how I can achieve this? | One rather ugly hack I've considered is to use addToJavaScriptWindowObject to drop the object I want to return into the window object with a random name, then have my slot return the name of the object instance instead:
```
QString MyApp::helloWorld()
{
//general a unique name for the js variable
QString name=getRandomVariableName();
//here's the object we want to expose to js
MyObject* pReturn=new MyObject();
//we make attach our object to the js window object
getWebFrame()->addToJavaScriptWindowObject(name, pReturn,
QScriptEngine::ScriptOwnership);
//tell js the name we used
return name;
}
```
The JS can be written to check if the return value is a string, and if it is, grab the object from the window.:
```
var foo=myapp.helloWorld();
if (typeof foo == "string")
{
foo=window[foo];
}
```
A little ugly, but will get me by until a better method comes along. Future Qt versions are going unify the scripting support so that it's all based on the JavaScriptCore in WebKit, so hopefully this will improve then! | You can assign your Object pointer to a QObject \* and return that.
```
QObject * obj = new MyObject();
return obj;
```
That is working for me on Qt Webkit port on Linux. | How to get Javascript in a QWebView to create new instances of C++ based classes? | [
"",
"javascript",
"qt",
"webkit",
"qtwebkit",
""
] |
**Intro**
Some continuous-integration tools (say, Hudson) assume compilers generate warnings of different severity (aka priority): high, normal and low.
Depending on number and severity of compiler warnings, the tool can mark a build as *unstable*.
I want my builds unstable if compiler generates high priority warnings.
I never seen any high (and low) priority warnings on our project -- only normal, so I'm a bit suspicious if they really exist.
**Question**
Where can I look at a **list of high priority compiler warnings** generated by javac and/or ecj.
Or maybe you can provide some examples of high priority warnings.
**Other**
Related, but maybe different question: I suspect high priority compiler warnings are actually errors and there can't be actually a situation you have source code compiled with high priority warnings (build will be broken in that case). | You can get a list of *all* compiler warnings by typing:
javac -X
and looking at the list given for the -Xlint option.
Java doesn't really have a notion of "high" vs "low" priority, and arguably shouldn't-- which particuarly warnings are likely to indicate a problem with your project is really specific to your particular mode of development. | If you want to see high and low priority warning you could use PMD, FindBug and/or checkstyle. Checkstyle is particularly good at producing a lot of very low priority warning. ;) | Java compiler warnings severity | [
"",
"java",
"compiler-construction",
"hudson",
""
] |
I need to write a function which will detect if the input contains at least one value which is non-numeric. If a non-numeric value is found I will raise an error (because the calculation should only return a numeric value). The number of dimensions of the input array is not known in advance - the function should give the correct value regardless of ndim. As an extra complication the input could be a single float or `numpy.float64` or even something oddball like a zero-dimensional array.
The obvious way to solve this is to write a recursive function which iterates over every iterable object in the array until it finds a non-iterabe. It will apply the `numpy.isnan()` function over every non-iterable object. If at least one non-numeric value is found then the function will return False immediately. Otherwise if all the values in the iterable are numeric it will eventually return True.
That works just fine, but it's pretty slow and I expect that [NumPy](http://en.wikipedia.org/wiki/NumPy) has a much better way to do it. What is an alternative that is faster and more numpyish?
Here's my mockup:
```
def contains_nan( myarray ):
"""
@param myarray : An n-dimensional array or a single float
@type myarray : numpy.ndarray, numpy.array, float
@returns: bool
Returns true if myarray is numeric or only contains numeric values.
Returns false if at least one non-numeric value exists
Not-A-Number is given by the numpy.isnan() function.
"""
return True
``` | This should be faster than iterating and will work regardless of shape.
```
numpy.isnan(myarray).any()
```
Edit: 30x faster:
```
import timeit
s = 'import numpy;a = numpy.arange(10000.).reshape((100,100));a[10,10]=numpy.nan'
ms = [
'numpy.isnan(a).any()',
'any(numpy.isnan(x) for x in a.flatten())']
for m in ms:
print " %.2f s" % timeit.Timer(m, s).timeit(1000), m
```
Results:
```
0.11 s numpy.isnan(a).any()
3.75 s any(numpy.isnan(x) for x in a.flatten())
```
Bonus: it works fine for non-array NumPy types:
```
>>> a = numpy.float64(42.)
>>> numpy.isnan(a).any()
False
>>> a = numpy.float64(numpy.nan)
>>> numpy.isnan(a).any()
True
``` | If infinity is a possible value, I would use [numpy.isfinite](http://docs.scipy.org/doc/numpy/reference/generated/numpy.isfinite.html#numpy.isfinite)
```
numpy.isfinite(myarray).all()
```
If the above evaluates to `True`, then `myarray` contains none of `numpy.nan`, `numpy.inf` or `-numpy.inf`.
`numpy.isnan` will be OK with `numpy.inf` values, for example:
```
In [11]: import numpy as np
In [12]: b = np.array([[4, np.inf],[np.nan, -np.inf]])
In [13]: np.isnan(b)
Out[13]:
array([[False, False],
[ True, False]], dtype=bool)
In [14]: np.isfinite(b)
Out[14]:
array([[ True, False],
[False, False]], dtype=bool)
``` | Detect if a NumPy array contains at least one non-numeric value? | [
"",
"python",
"numpy",
""
] |
How are random numbers generated.? How do languages such as java etc generate random numbers, especially how it is done for GUIDs.? i found that algorithms like Pseudorandomnumber generator uses initial values.
But i need to create a random number program, in which a number once occurred should never repeats even if the system is restarted etc. I thought that i need to store the values anywhere so that i can check if the number repeats or not, but it will be too complex when the list goes beyond limits.? | First: If the number is guaranteed to never repeat, it's not very random.
Second: There are lots of [PRNG algorithms](http://en.wikipedia.org/wiki/List_of_pseudorandom_number_generators).
UPDATE:
Third: There's an [IETF RFC for UUIDs](https://www.rfc-editor.org/rfc/rfc4122) (what MS calls GUIDs), but you should recognize that (U|G)UIDs are *not* cryptographically secure, if that is a concern for you.
UPDATE 2:
If you want to actually use something like this in production code (not just for your own edification) **please** use a pre-existing library. This is the sort of code that is almost guaranteed to have subtle bugs in it if you've never done it before (or even if you have).
UPDATE 3:
Here's the [docs for .NET's GUID](http://msdn.microsoft.com/en-us/library/system.guid.aspx) | There are a lot of ways you could generate random numbers. It's usually done with a system/library call which uses a pseudo-number generator with a seed as you've already described.
But, there are other ways of getting random numbers which involve specialized hardware to get TRUE random numbers. I know of some [poker sites](http://www.ultimatebet.net/help/random) that use this kind of hardware. It's very interesting to read how they do it. | How to generate "random" but also "unique" numbers? | [
"",
"c#",
"random",
""
] |
Supposing I have a class "Item", which has three member variables: string name, decimal quantity and string unit. I have got public get/set properties on all three.
Sometimes, I want to display quantity as text along with correct unit, eg. 10m or 100 feet.
My question is, is it possible to have some sort of ToString() function for properties too, so that their text output can be customized?
Thanks,
Saurabh. | What you can do is to make a new (readonly) property returning a formatted version:
```
public string QuantityAsString
{
get
{
return string.Format("{0} {1}", this.Quantity, this.Unit);
}
}
``` | It sounds like your object model isn't correctly factored. What you probably want to do is abstract `Unit` and `Quantity` into another object and then you can override `ToString` for that. This has the advantage of keeping dependent values together, and allowing you to implement things such as conversions between units in the future (e.g. conversion from inchest to feet etc.), e.g.
```
public struct Measure
{
public Measure(string unit, decimal quantity)
{
this.Unit = unit;
this.Quantity = quantity;
}
public string Unit { get; private set; }
public decimal Quantity { get; private set; }
public override string ToString()
{
return string.Format("{0} {1}", this.Quantity, this.Unit);
}
}
public class Item
{
public string Name { get; set; }
public Measure Measure { get; set; }
public override string ToString()
{
return string.Format("{0}: {1}", this.Name, this.Measure);
}
}
```
Note that I made `Measure` a struct here as it probably has value semantics. If you take this approach you should make it immutable and override Equals/GetHashCode as is appropriate for a struct. | ToString() for a class property? | [
"",
"c#",
""
] |
Django has a DATE\_FORMAT and a DATE\_TIME\_FORMAT options that allow us to choose which format to use when viewing dates, but doesn't apparently let me change the input format for the date when editing or adding in the Django Admin.
The default for the admin is: YYYY-MM-DD
But would be awesome to use: DD-MM-YYYY
Is this integrated in any case in i18n?
Can this be changed without a custom model? | Based on this idea I made new db.fields class EuDateField:
mydbfields.py
```
from django import forms
from django.forms.fields import DEFAULT_DATE_INPUT_FORMATS
from django.db import models
class EuDateFormField(forms.DateField):
def __init__(self, *args, **kwargs):
kwargs.update({'input_formats': ("%d.%m.%Y",)+DEFAULT_DATE_INPUT_FORMATS})
super(EuDateFormField, self).__init__(*args, **kwargs)
class EuDateField(models.DateField):
def formfield(self, **kwargs):
kwargs.update({'form_class': EuDateFormField})
return super(EuDateField, self).formfield(**kwargs)
```
Note that it adds my format (e.g. 31.12.2007) to existing "standard" django formats at first place.
Usage:
```
from mydbfields import EuDateField
class Person(models.Model):
...
birthday = EuDateField("Birthday", null=True, blank=True, help_text="")
```
In my case this renders good in admin, but most probably will in ModelForm too (haven't tried it).
My django version is:
```
>>> import django
>>> django.get_version()
u'1.1 alpha 1 SVN-10105'
``` | There is an official way to do this now since the closing of [Django ticket 6483](https://code.djangoproject.com/ticket/6483) & release of Django 1.2.
If you have [`USE_L10N`](https://docs.djangoproject.com/en/1.3/ref/settings/#std%3asetting-USE_L10N) set to `False`, what you should do is specify the [`DATE_INPUT_FORMATS`](https://docs.djangoproject.com/en/1.3//ref/settings/#date-input-formats) and [`DATETIME_INPUT_FORMATS`](https://docs.djangoproject.com/en/1.3//ref/settings/#datetime-input-formats) in your `settings.py`. Here are the settings I use for this, based on converting the defaults:
```
#dd/mm/yyyy and dd/mm/yy date & datetime input field settings
DATE_INPUT_FORMATS = ('%d-%m-%Y', '%d/%m/%Y', '%d/%m/%y', '%d %b %Y',
'%d %b, %Y', '%d %b %Y', '%d %b, %Y', '%d %B, %Y',
'%d %B %Y')
DATETIME_INPUT_FORMATS = ('%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%Y',
'%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M', '%d/%m/%y',
'%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d')
```
If you have `USE_L10N` set to `True`, then you will need to use the [`FORMAT_MODULE_PATH`](https://docs.djangoproject.com/en/1.3/ref/settings/#format-module-path) instead.
For example, my [`LANGUAGE_CODE`](https://docs.djangoproject.com/en/1.3/ref/settings/#language-code) is set to `en-au`, my site is called `golf`, and my `FORMAT_MODULE_PATH` is set to `golf.formats`, so my directory structure looks like this:
```
golf/
settings.py
...
formats/
__init__.py
en/
__init__.py
formats.py
```
and the `DATE_INPUT_FORMATS` and `DATETIME_INPUT_FORMATS` settings are in `formats.py` instead of `settings.py`. | European date input in Django Admin | [
"",
"python",
"django",
"date",
"django-admin",
""
] |
What's a good way to profile a PHP page's memory usage? For example, to see how much memory my data is using, and/or which function calls are allocating the most memory.
* xdebug doesn't seem to provide memory information in its profiling feature.
* xdebug **does** provide it in its tracing feature. This is pretty close to what I want, except the sheer amount of data is overwhelming, since it shows memory deltas for every single function call. If it were possible to hide calls below a certain depth, maybe with some GUI tool, that would solve my problem.
Is there anything else? | [Xdebug](https://xdebug.org/) [reimplemented memory tracing in 2.6](https://bugs.xdebug.org/bug_view_page.php?bug_id=00000474) (2018-01-29) which can be used in Qcachegrind or similar tool. Just [make sure to select the memory option](https://bugs.xdebug.org/view.php?id=1524) :)
From the docs:
> Since Xdebug 2.6, the profiler also collects information about how much memory is being used, and which functions aGnd methods increased memory usage.
I'm not familiar with the format of the file, but it's Qcachegrind has worked great for me in tracing a couple memory issues.
[](https://i.stack.imgur.com/dzJVi.jpg) | As you probably know, Xdebug dropped the memory profiling support since the 2.\* version. Please search for the "removed functions" string here: <http://www.xdebug.org/updates.php>
> **Removed functions**
>
> Removed support for Memory profiling as that didn't work properly.
So I've tried another tool and it worked well for me.
<https://github.com/arnaud-lb/php-memory-profiler>
This is what I've done on my Ubuntu server to enable it:
```
sudo apt-get install libjudy-dev libjudydebian1
sudo pecl install memprof
echo "extension=memprof.so" > /etc/php5/mods-available/memprof.ini
sudo php5enmod memprof
service apache2 restart
```
And then in my code:
```
<?php
memprof_enable();
// do your stuff
memprof_dump_callgrind(fopen("/tmp/callgrind.out", "w"));
```
Finally open the `callgrind.out` file with [KCachegrind](http://kcachegrind.sourceforge.net/html/Home.html)
# Using Google gperftools (recommended!)
First of all install the **Google gperftools** by downloading the latest package here: <https://code.google.com/p/gperftools/>
Then as always:
```
sudo apt-get update
sudo apt-get install libunwind-dev -y
./configure
make
make install
```
Now in your code:
```
memprof_enable();
// do your magic
memprof_dump_pprof(fopen("/tmp/profile.heap", "w"));
```
Then open your terminal and launch:
```
pprof --web /tmp/profile.heap
```
*pprof* will create a new window in your existing browser session with something like shown below:

# Xhprof + Xhgui (the best in my opinion to profile both cpu and memory)
With **Xhprof** and **Xhgui** you can profile the cpu usage as well or just the memory usage if that's your issue at the moment.
It's a very complete solutions, it gives you full control and the logs can be written both on mongo or in the filesystem.
For more details [see my answer here](https://stackoverflow.com/questions/16787462/php-xdebug-how-to-profile-forked-process/31388948#31388948).
# Blackfire
Blackfire is a PHP profiler by SensioLabs, the Symfony2 guys <https://blackfire.io/>
If you use [puphpet](https://puphpet.com/) to set up your virtual machine you'll be happy to know it's supported ;-) | PHP memory profiling | [
"",
"php",
"memory",
"profiling",
""
] |
Lets say that one has a class like Person that has associated with it some default settings implemented in a Setting class. Those settings might be things like "Default Title" or "First Name Required". Correspondingly, other classes like an Address class might also have some default settings. The Setting class persists each setting into a persistent store.
Should one implement a static method in each class like "SetDefaults()" that contains these settings so that an external method can call SetDefaults() on each object type? e.g. Person.SetDefaults() and then Address.SetDefaults()?
Or is there some better object oriented way of doing this?
[Update: this can't be in the constructor because SetDefaults() should be called from an external class at a particular point in time, rather than each time the object is constructed.] | I can't think of many occasions where defaults are truly spanning... given all the different use-cases that an object may go through (not least, things like deserialization - which could end up setting the defaults even though that isn't what was intended).
One option here is IoC; IoC containers like StructureMap have the ability to set properties after initialization, and that is then abstracted from the calling code.
Another option might be some kind of template instance (static), that instances can copy values from. But I think this is risky in a few scenarios. You also get problems if different threads (perhaps requests on a web-server) need different defaults. `[ThreadStatic]` isn't a *good* option (although it is an option).
Another option (that provides the greatest flexibility) would be to provide a user-settable factory... perhaps via a delegate or event mechanism - but I struggle to see *why* you might want this scenario. It isn't one I've seen very often...
---
re update: if it is only used by the external class; could it perhaps use something like an extension method (rather than the `Person` class having to know anything about this):
```
public static class PersonExt {
public static void SetDefaults(this Person person) {
// your code
}
}
```
Since it sounds like the original `Person` class doesn't care about `SetDefaults`, this divorces the logic from `Person` neatly. | Why not set these defaults when you create the object (in the constructor).
A default is -imho- a value that should be assigned to a property when no specific value is given to that property, so, I think it is a good idea to set those default-values when the object is created (in the constructor, or via a factory).
Or, am i missing something ? | Static Method or OO Alternative? | [
"",
"c#",
"design-patterns",
"oop",
""
] |
Is it possible to do `mysqldump` by single `SQL query`?
I mean to dump the **whole** database, like `phpmyadmin` does when you do export to `SQL` | not mysqldump, but mysql cli...
```
mysql -e "select * from myTable" -u myuser -pxxxxxxxxx mydatabase
```
you can redirect it out to a file if you want :
```
mysql -e "select * from myTable" -u myuser -pxxxxxxxx mydatabase > mydumpfile.txt
```
Update:
Original post asked if he could dump from the database by query. What he asked and what he meant were different. He really wanted to just mysqldump all tables.
```
mysqldump --tables myTable --where="id < 1000"
``` | This should work
```
mysqldump --databases X --tables Y --where="1 limit 1000000"
``` | MySQL dump by query | [
"",
"sql",
"mysql",
"database",
""
] |
I'm new to LINQ,My knowledge on that library is from Jon Skeet's book "C# In Depth 1"
I read a lot of tutorials about LINQ in the past days including Skeet's book,but I could never find out a code snippet showing a normal C# code and then the shorter version of that code with LINQ so the reader can understand what does what.
My Problem:
The function below opens a text file and searches for numbers placed at a specific place inside the text file.The numbers(I used ID in the code) start from 1 to 25000 and there are a few that are missing(for example there's no life 25,but 24,23,26,27 etc).
I want the code to copy the lines in the array "Ids".Its not meant to be an array,I'm just new and I don't know if anything else would be more handy for LINQ.
```
public static IEnumerable<string> ReadLines(StreamReader reader)
{
while (!reader.EndOfStream)
{
yield return reader.ReadLine();
}
}
static void Filter(string filename)
{
using(var writer = File.CreateText(Application.StartupPath + "\\temp\\test.txt"))
{
using (var reader = File.OpenText(filename))
{
int[] Ids = { 14652, 14653, 14654, 14655, 14656, 14657, 14658, 14659, 14660 };
var myId = from id in Ids
from line in ReadLines(reader)
let items = line.Split('\t')
where items.Length > 1
let ItemId = int.Parse(items[1])
where ItemId == id
select line;
foreach (var id in myId)
{
writer.WriteLine(id);
}
}
}
}
```
What it writes: It only writes one line with number ,which is the first member of the Ids[] array(14652).
I had to add the second 'from' ,which is placed at first place in the code so it will check it for every member of the array.I get the from statement as a "while",because I couldn't find a snipper with normal code-> linq.
Where is the problem in the code? | > It only writes one line with number ,which is the first member of the Ids[] array(14652).
> Where is the problem in the code?
```
from id in Ids
from line in ReadLines(reader)
```
This code is conceptually like (ignoring deferred execution):
```
foreach(int id in Ids)
{
foreach(string line in ReadLines(reader)
{
...
}
}
```
Which will work great for the first id, but then the reader will be at the end of the file for the second id on and no matches will be found. | ```
from line in ReadLines(reader)
where Ids.Contains(line.Split('\t')[1])
select line;
```
You can tweak the Contains with ? to get around splits that don't have an item at 1.
Is this what you're trying to do? I think the second from is like a cross join which Isn't necessary as I understand your problem. | Second "from" statement in LINQ | [
"",
"c#",
"linq",
""
] |
I have an array X of 10 elements. I would like to create a new array containing all the elements from X that begin at index 3 and ends in index 7. Sure I can easily write a loop that will do it for me but I would like to keep my code as clean as possible. Is there a method in C# that can do it for me?
Something like (pseudo code):
```
Array NewArray = oldArray.createNewArrayFromRange(int BeginIndex , int EndIndex)
```
**`Array.Copy` doesn't fit my needs**. I need the items in the new array to be clones. `Array.copy` is just a C-Style `memcpy` equivalent, it's not what I'm looking for. | You could add it as an extension method:
```
public static T[] SubArray<T>(this T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
static void Main()
{
int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] sub = data.SubArray(3, 4); // contains {3,4,5,6}
}
```
---
Update re cloning (which wasn't obvious in the original question). If you *really* want a deep clone; something like:
```
public static T[] SubArrayDeepClone<T>(this T[] data, int index, int length)
{
T[] arrCopy = new T[length];
Array.Copy(data, index, arrCopy, 0, length);
using (MemoryStream ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, arrCopy);
ms.Position = 0;
return (T[])bf.Deserialize(ms);
}
}
```
This does require the objects to be serializable (`[Serializable]` or `ISerializable`), though. You could easily substitute for any other serializer as appropriate - `XmlSerializer`, `DataContractSerializer`, protobuf-net, etc.
Note that deep clone is tricky without serialization; in particular, `ICloneable` is hard to trust in most cases. | You can use [`Array.Copy(...)`](http://msdn.microsoft.com/en-us/library/z50k9bft.aspx) to copy into the new array after you've created it, but I don't think there's a method which creates the new array *and* copies a range of elements.
If you're using .NET 3.5 you *could* use LINQ:
```
var newArray = array.Skip(3).Take(5).ToArray();
```
but that will be somewhat less efficient.
See [this answer](https://stackoverflow.com/questions/886488/copy-one-string-array-to-another/886498#886498) to a similar question for options for more specific situations. | How do I clone a range of array elements to a new array? | [
"",
"c#",
"arrays",
".net",
"clone",
"deep-copy",
""
] |
Working on an algorithm to look at a STL container of STL strings (or other strings, making it general)
Basically it loops through something like a std::list and returns the length of the longest beginning in common. It's for processing lists of files, like this:
```
C:\Windows\System32\Stuff.exe
C:\Windows\Things\InHere.txt
C:\Windows\Foo\Bar.txt
```
This should return 11, because "`C:\Windows\`" is in common.
Never written a templatized function before, and my compiler is complaining. Here's my code:
Header:
```
// longestBegin.h -- Longest beginning subsequence solver
template <typename SequenceSequenceT, typename SequenceT, typename T >
size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates);
```
---
Implementation:
```
// longestBegin.cpp -- Longest beginning subsequence solver
#include <stdafx.h>
template <typename SequenceSequenceT, typename SequenceT, typename T >
size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates)
{
SequenceT firstString = *firstCandidates;
size_t longestValue = firstString.length();
firstCandidates++;
for(size_t idx = 0; idx < longestValue; idx++)
{
T curChar = firstString[idx];
for(InputIterator curCandidate = firstCandidates;curCandidate != lastCandidates; curCandidate++)
{
if ((*curCandidate)[idx] != curChar)
return idx - 1;
}
}
return longestValue;
}
```
I have a funny feeling I'm missing something fundamental here......
The compiler bombs with the following error:
```
error C2998: 'size_t longestBegin' : cannot be a template definition
```
Any ideas? Thanks!
Billy3 | Your parameter names in the `template` line need to include any types of function parameters or return types. This means that you need to mention `InputIterator` in your template parameter list. Try changing your function declaration to:
```
template <typename InputIterator>
size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates)
```
Your next problem is: how does the compiler know what `SequenceT` is? The answer is that it's the result of dereferencing an `InputIterator`. Iterators that aren't pointers have a nested `typedef` called `reference`, which is just what you need here. Add this to the start of your function so the compiler knows what `SequenceT` is:
```
template <typename InputIterator>
size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates)
{
typedef typename InputIterator::reference SequenceT;
[etc.]
```
You could have kept `SequenceT` as a template parameter, but then the compiler couldn't guess what it is from looking at the arguments, and you'd have to call your function by typing e.g. `longestBegin<string>(arguments)`, which isn't necessary here.
Also, you'll notice that this doesn't work if `InputIterator` is a pointer -- pointers don't have nested typedefs. So you can use a special struct called `std::iterator_traits` from the `<iterator>` standard header that can sort out these problems for you:
```
//(At the top of your file)
#include <iterator>
template <typename InputIterator>
size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates)
{
typedef typename std::iterator_traits<InputIterator>::reference SequenceT;
[etc.]
```
Finally, unless the first string is always the longest, you could end up accessing a string past the end of its array inside the second for loop. You can check the length of the string before you access it:
```
//(At the top of your file)
#include <iterator>
template <typename InputIterator>
size_t longestBegin(InputIterator firstCandidates, InputIterator lastCandidates)
{
typedef typename std::iterator_traits<InputIterator>::reference SequenceT;
SequenceT firstString = *firstCandidates;
size_t longestValue = firstString.length();
firstCandidates++;
for(size_t idx = 0; idx < longestValue; idx++)
{
T curChar = firstString[idx];
for(InputIterator curCandidate = firstCandidates;curCandidate != lastCandidates; curCandidate++)
{
if (curCandidate->size() >= idx || (*curCandidate)[idx] != curChar)
return idx - 1;
}
}
return longestValue;
}
```
Also note that the function returns `(size_t)(-1)` if there is no common prefix. | You can't forward declare templates, I believe. Try moving the implementation into the header file. | Templates and Syntax | [
"",
"c++",
"templates",
""
] |
I am using JQuery to inject dynamically script tags in the body tab of a webpage. I got something like :
```
function addJS(url) {
$("body").append('<script type="text/javascript" src='+url+'></script>');
}
```
I add several scripts this way, and try to use them right after. E.G :
*lib.js*
```
function core() {...}
alert("I'am here !");
```
*init.js*
```
addJS("lib.js");
c = new core();
```
*test.html*
```
<html>
<head>
<title>test</title>
<script type="text/javascript" src="init.js"></script>
</head>
<body>
Hello
</body>
</html>
```
Loading test.html pops up "I'm here" and then ends up with an error "core is not defined". Of course merging both of the JS files will make them work perfectly.
I just don't get it o\_O.
**EDIT**
I simplified this example, but Jeff answer made me understand that it was a mistake. So here are some details :
init.js is not in the head of test.html when it reload because I inject it with a code exectuted on a bookmarklet.
So the real execution process is the following :
reload test.html > run the bookmarklet > jquery and init.js are inserted > lib.js is inserted
Sorry for the confusion.
**EDIT 2**
Now I have the solution to my problem (that was quick :-)) but I am still interested to the answer to my question. Why does this go wrong ? | You get the "core is not defined" error because the scripts are loaded asynchronous. Which means that your browser will start loading lib.js in the background, and continue executing init.js, and then encounter "new core()" before the lib.js has finished loading.
The getScript function has a callback that will be triggered after the script is finished loading:
```
$.getScript('lib.js', function() {
var c = new core();
});
``` | jQuery has this functionality built in with [getScript](http://docs.jquery.com/Ajax/jQuery.getScript#urlcallback). | How to dynamically load Javascript files and use them right away? | [
"",
"javascript",
"bookmarklet",
""
] |
I want to share some information between two classes (A and B), which are running in different java programs. Instead of writing a whole communication protocol I want to use the java build-in rmi classes for that purpose. Currently class B is able to run a method which belongs to class A remotely. Is it somehow possible to use the same "connection" within class A to call a method of class B? Otherwise I probably have to implement a second rmi service ...
BR,
Markus | If `B` implements `Remote`, it can be export and passed as a parameter in an RMI call to `A`. In this scenario, there's no need to register `B` in an RMI registry, since the client is being passed a reference to it explicitly. | I implemented 2 way RMI between cleint and server with server exposing its stub using Registry
1. The client gets a stub of the server
2. Then the client puts its stub as Observer to the server's addObserver method
3. The server notifies the clients using this stub
The following code will gives a better idea
```
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.util.Observable;
import java.util.Observer;
import java.net.*;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;
interface ReceiveMessageInterface extends Remote
{
/**
* @param x
* @throws RemoteException
*/
void receiveMessage(String x) throws RemoteException;
/**
* @param observer
* @throws RemoteException
*/
void addObserver(Remote observer) throws RemoteException;
}
/**
*
*/
class RmiClient extends UnicastRemoteObject
{
/**
* @param args
*/
static public void main(String args[])
{
ReceiveMessageInterface rmiServer;
Registry registry;
String serverAddress = args[0];
String serverPort = args[1];
String text = args[2];
System.out.println("sending " + text + " to " + serverAddress + ":" + serverPort);
try
{ // Get the server's stub
registry = LocateRegistry.getRegistry(serverAddress, (new Integer(serverPort)).intValue());
rmiServer = (ReceiveMessageInterface) (registry.lookup("rmiServer"));
// RMI client will give a stub of itself to the server
Remote aRemoteObj = (Remote) UnicastRemoteObject.exportObject(new RmiClient(), 0);
rmiServer.addObserver(aRemoteObj);
// call the remote method
rmiServer.receiveMessage(text);
// update method will be notified
}
catch (RemoteException e)
{
e.printStackTrace();
}
catch (NotBoundException e)
{
System.err.println(e);
}
}
public void update(String a) throws RemoteException
{
// update should take some serializable object as param NOT Observable
// and Object
// Server callsbacks here
}
}
/**
*
*/
class RmiServer extends Observable implements ReceiveMessageInterface
{
String address;
Registry registry;
/**
* {@inheritDoc}
*/
public void receiveMessage(String x) throws RemoteException
{
System.out.println(x);
setChanged();
notifyObservers(x + "invoked me");
}
/**
* {@inheritDoc}
*/
public void addObserver(final Remote observer) throws RemoteException
{
// This is where you plug in client's stub
super.addObserver(new Observer()
{
@Override
public void update(Observable o,
Object arg)
{
try
{
((RmiClient) observer).update((String) arg);
}
catch (RemoteException e)
{
}
}
});
}
/**
* @throws RemoteException
*/
public RmiServer() throws RemoteException
{
try
{
address = (InetAddress.getLocalHost()).toString();
}
catch (Exception e)
{
System.out.println("can't get inet address.");
}
int port = 3232;
System.out.println("this address=" + address + ",port=" + port);
try
{
registry = LocateRegistry.createRegistry(port);
registry.rebind("rmiServer", this);
}
catch (RemoteException e)
{
System.out.println("remote exception" + e);
}
}
/**
*
* @param args
*/
static public void main(String args[])
{
try
{
RmiServer server = new RmiServer();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}
``` | Is it possible to use RMI bidirectional between two classes? | [
"",
"java",
"connection",
"rmi",
""
] |
I know that the following should work:
```
Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine)
```
My problem with this call is that if for some reason someone decided to remove the "windir" Env Var , this won't work.
Is there an even more secure way to get the System drive? | One thing i actually maybe misunderstand is that you want the System Drive, but by using "windir" you'll get the windows folder. So if you need a *secure way* to get the windows folder, you should use the good old API function GetWindowsDirectory.
Here is the function prepared for C# usage. ;-)
```
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint GetWindowsDirectory(StringBuilder lpBuffer, uint uSize);
private string WindowsDirectory()
{
uint size = 0;
size = GetWindowsDirectory(null, size);
StringBuilder sb = new StringBuilder((int)size);
GetWindowsDirectory(sb, size);
return sb.ToString();
}
```
So if you really need the drive on which windows is running, you could afterwards call
```
System.IO.Path.GetPathRoot(WindowsDirectory());
``` | ```
string windir = Environment.SystemDirectory; // C:\windows\system32
string windrive = Path.GetPathRoot(Environment.SystemDirectory); // C:\
```
Note: This property internally uses the GetSystemDirectory() Win32 API. It doesn't rely on environment variables. | What is the most secure way to retrieve the system Drive | [
"",
"c#",
".net",
"windows",
"environment-variables",
"system-administration",
""
] |
I want to center my WPF app on startup on the primary screen. I know I have to set myWindow.Left and myWindow.Top, but where do I get the values?
I found `System.Windows.Forms.Screen.PrimaryScreen`, which is apparently not WPF. Is there a WPF alternative that gives me the screen resolution or something like that? | Put this in your window constructor
```
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
```
> .NET FrameworkSupported in: 4, 3.5,
> 3.0
>
> .NET Framework Client ProfileSupported
> in: 4, 3.5 SP1 | **xaml**
```
<Window ... WindowStartupLocation="CenterScreen">...
``` | How to center a WPF app on screen? | [
"",
"c#",
"wpf",
"screen-positioning",
""
] |
I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment.
The odd thing is that i can set
```
test_suite = 'nose.collector'
```
in setup.py and run the tests just fine as
```
python setup.py test
```
but when running nosetests straight, there are all sorts of import errors.
I've tried it with both a system-wide installation of nose and a virtualenv nose package and no luck.
Any thoughts?
Thanks!! | Are you able to run `myenv/bin/python /usr/bin/nosetests`? That should run Nose using the virtual environment's library set. | You need to have a copy of nose installed in the virtual environment. In order to force installation of nose into the virtualenv, even though it is already installed in the global site-packages, run `pip install` with the `-I` flag:
```
(env1)$ pip install nose -I
```
From then on you can just run `nosetests` as usual. | Problems using nose in a virtualenv | [
"",
"python",
"virtualenv",
"nose",
"nosetests",
""
] |
I read some articles written on "ClassCastException", but I couldn't get a good idea on what it means. What is a ClassCastException? | Straight from the API Specifications for the [`ClassCastException`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassCastException.html):
> Thrown to indicate that the code has
> attempted to cast an object to a
> subclass of which it is not an
> instance.
So, for example, when one tries to cast an `Integer` to a `String`, `String` is not an subclass of `Integer`, so a `ClassCastException` will be thrown.
```
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
``` | It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.
Let's think of a collection of classes.
```
class A {...}
class B extends A {...}
class C extends A {...}
```
1. You can cast any of these things to Object, because all Java classes inherit from Object.
2. You can cast either B or C to A, because they're both "kinds of" A
3. You can cast a reference to an A object to B *only if* the real object is a B.
4. You can't cast a B to a C even though they're both A's. | Explanation of ClassCastException in Java | [
"",
"java",
"casting",
"classcastexception",
""
] |
Hi I have a image table in my database. These are stored as blob along with details such as image type & name.
I am having a problem showing the image, all I get is a white box with a red cross in it.
code:
```
<?php
include '../connection.php';
$ID = $_GET['id'];
$query = "SELECT * FROM `images` WHERE `image_id` = '$ID'";
$result=mysql_query($query);
$row = mysql_fetch_array($result);
$image = $row['image'];
$image_type= $row['image_type'];
header("Content-type: $image_type");
print $image;
exit;
?>
```
Thanks | Well here is a short answer.
```
<?php
include '../connection.php';
$id = (int)$_GET['id'];
$query = "SELECT * FROM `images` WHERE `image_id` = '$id'";
$result=mysql_query($query);
$row = mysql_fetch_array($result);
$image = $row['image'];
$image_type= $row['image_type'];
$size = $row['image_size'];
//alternative
/* list($image, $image_type, $size) = array(
$row['image'],
$row['image_type'],
$row['image_size']
);
*/
$ext = explode('/', $image_type);
$name = $id . '.' . $ext[1];
header("Content-type: $image_type");
header("Content-length: $size");
header("Content-Disposition: attachment; filename=$name");
print $image;
exit;
```
Check your blobtype to be a least MEDIUMBLOB which is able to store data up to 16M | To debug this, I'd suggest commenting-out the Content-type header line, then hitting the url directly in the browser. This will allow you to see any errors, warnings or notices that PHP might be emitting. | show image from blob mysql | [
"",
"php",
"mysql",
""
] |
Is there any real practical difference between a [`SortedList<TKey,TValue>`](https://msdn.microsoft.com/en-us/library/ms132319(v=vs.110).aspx) and a [`SortedDictionary<TKey,TValue>`](https://msdn.microsoft.com/en-us/library/f7fta44c(v=vs.110).aspx)? Are there any circumstances where you would specifically use one and not the other? | Yes - their performance characteristics differ significantly. It would probably be better to call them `SortedList` and `SortedTree` as that reflects the implementation more closely.
Look at the MSDN docs for each of them ([`SortedList`](http://msdn.microsoft.com/en-us/library/ms132319.aspx), [`SortedDictionary`](http://msdn.microsoft.com/en-us/library/f7fta44c.aspx)) for details of the performance for different operations in different situtations. Here's a nice summary (from the `SortedDictionary` docs):
> The `SortedDictionary<TKey, TValue>` generic
> class is a binary search tree with
> O(log n) retrieval, where n is the
> number of elements in the dictionary.
> In this, it is similar to the
> `SortedList<TKey, TValue>` generic
> class. The two classes have similar
> object models, and both have O(log n)
> retrieval. Where the two classes
> differ is in memory use and speed of
> insertion and removal:
>
> * `SortedList<TKey, TValue>` uses less
> memory than `SortedDictionary<TKey,
> TValue>`.
> * `SortedDictionary<TKey, TValue>` has
> faster insertion and removal
> operations for unsorted data, O(log n)
> as opposed to O(n) for
> `SortedList<TKey, TValue>`.
> * If the list is populated all at once
> from sorted data, `SortedList<TKey,
> TValue>` is faster than
> `SortedDictionary<TKey, TValue>`.
(`SortedList` actually maintains a sorted array, rather than using a tree. It still uses binary search to find elements.) | Here is a tabular view if it helps...
From a **performance** perspective:
```
+------------------+---------+----------+--------+----------+----------+---------+
| Collection | Indexed | Keyed | Value | Addition | Removal | Memory |
| | lookup | lookup | lookup | | | |
+------------------+---------+----------+--------+----------+----------+---------+
| SortedList | O(1) | O(log n) | O(n) | O(n)* | O(n) | Lesser |
| SortedDictionary | O(n)** | O(log n) | O(n) | O(log n) | O(log n) | Greater |
+------------------+---------+----------+--------+----------+----------+---------+
* Insertion is O(log n) for data that are already in sort order, so that each
element is added to the end of the list. If a resize is required, that element
takes O(n) time, but inserting n elements is still amortized O(n log n).
list.
** Available through enumeration, e.g. Enumerable.ElementAt.
```
From an **implementation** perspective:
```
+------------+---------------+----------+------------+------------+------------------+
| Underlying | Lookup | Ordering | Contiguous | Data | Exposes Key & |
| structure | strategy | | storage | access | Value collection |
+------------+---------------+----------+------------+------------+------------------+
| 2 arrays | Binary search | Sorted | Yes | Key, Index | Yes |
| BST | Binary search | Sorted | No | Key | Yes |
+------------+---------------+----------+------------+------------+------------------+
```
To *roughly* paraphrase, if you require raw performance `SortedDictionary` could be a better choice. If you require lesser memory overhead and indexed retrieval `SortedList` fits better. [See this question for more on when to use which.](https://stackoverflow.com/questions/1376965/when-to-use-a-sortedlisttkey-tvalue-over-a-sorteddictionarytkey-tvalue)
You can read more [here](http://msdn.microsoft.com/en-us/library/5z658b67%28v=vs.110%29.aspx), [here](http://www.growingwiththeweb.com/2013/02/what-data-structure-net-collections-use.html), [here](http://www.codethinked.com/an-overview-of-system_collections_generic), [here](http://diranieh.com/NetDataStructures/NET/Collections.htm) and [here](http://people.cs.aau.dk/%7Enormark/oop-csharp/html/notes/collections_themes-dictionary-sect.html). | What's the difference between SortedList and SortedDictionary? | [
"",
"c#",
".net",
"generics",
"sortedlist",
"sorteddictionary",
""
] |
I was wondering, is it possible to join the result of a query with itself, using PostgreSQL? | You can do so with WITH:
```
WITH subquery AS(
SELECT * FROM TheTable
)
SELECT *
FROM subquery q1
JOIN subquery q2 on ...
```
Or by creating a VIEW that contains the query, and joining on that:
```
SELECT *
FROM TheView v1
JOIN TheView v2 on ...
```
Or the brute force approach: type the subquery twice:
```
SELECT *
FROM (
SELECT * FROM TheTable
) sub1
LEFT JOIN (
SELECT * FROM TheTable
) sub2 ON ...
``` | Do you mean, the result of a query on a table, to that same table. If so, then Yes, it's possible... e.g.
```
--Bit of a contrived example but...
SELECT *
FROM Table
INNER JOIN
(
SELECT
UserID, Max(Login) as LastLogin
FROM
Table
WHERE
UserGroup = 'SomeGroup'
GROUP BY
UserID
) foo
ON Table.UserID = Foo.UserID AND Table.Login = Foo.LastLogin
``` | Self-join of a subquery | [
"",
"sql",
"postgresql",
""
] |
Let's suppose I have an interface named "Controller". Several classes implement this interface and I don't know these classes (e.g. the class names are located in an xml-file). Now for this Controller-implementing classes to work they have to get some references to other objects (maybe data objects). And this is my question, namely what is the best way to initialize such objects (the Controller ones)?
I thought of several solutions but I'm not really sure what's the best approach here.
**First**: When instantiating the object from the class name I could search for the "special" constructor (via reflection) which has the object references that the Controller-object needs. But from what I read in other questions this is less likely a good solution because I would force a special constructor to exist in the class. And sometimes I read that reflection in general is evil and is better avoided.
**Second**: I add a special init(a,b,c)-method to the Controller-interface which would need to be called directly after the object was created. This would force a sequence of calls (first init(..), then rest) to the object to make it working which is likely bad too. Btw, are init()-methods generelly a bad thing in interfaces?
**Third**: After reading [this](https://stackoverflow.com/questions/26903/how-can-you-require-a-constructor-with-no-parameters-for-types-implementing-an-in/26928#26928) comment I thought about the following: Instead of having the class name of the class implementing the Controller-interface (in the xml file) I have the class name of a factory which belongs to the concrete Controller-class. And this factory would implement an interface with the method createController(a,b,c) and the factory then would know which class it would have to instantiate and also which constructor to call to carry over the other references (like data objects). Drawback of this would be the additional class just to instantiate the Controller-class and maybe a little overhead in general.
What do you think is the best way of doing this? Or can you think of something else which might be better than these three ways?
Thanks! | Of the approaches you mention, I'd pick the second (factory-based one). However, since what you're doing *is* a form of dependency injection, also consider Guice, <http://code.google.com/p/google-guice/> -- it may enable you to automate much of this work. | What you are trying to do is very similar to what Spring does.
In your xml file, your controller node would have child nodes to specify properties to be set.
Your controller is instatiated by calling the default constructor. Then properties are set using reflection. | Initializing an object with references without accessing a non-default constructor | [
"",
"java",
"interface",
"constructor",
"initialization",
""
] |
I'd want your input which gcc compiler flags to use when optimizing for Xeons?
There's no 'xeon' in mtune or march so which is the closest match? | Xeon is a marketing term, as such it covers a long list of processors with very different internals.
If you meant the newer Nehalem processors (Core i7) then [this slide](https://software.intel.com/sites/default/files/m/4/7/e/15507330-Intel-Nehalem-Core-Architecture-82-page.pdf) indicates that as of 4.3.1 gcc should be use -march=generic (though your own testing of your own app may find other settings that outperform this). The 4.3 series also added -msse4.2 if you wish to optimize that aspect of FP maths.
Here is [some discussion](http://software.intel.com/en-us/forums/intel-vtune-performance-analyzer/topic/63801/) comparing tuning in Intel's compiler versus some gcc flags. | An update for recent GCC / Xeon.
* **[Sandy-Bridge-based](http://en.wikipedia.org/wiki/Sandy_Bridge) Xeon** (E3-12xx series, E5-14xx/24xx series, E5-16xx/26xx/46xx series).
`-march=corei7-avx` for GCC < 4.9.0 or `-march=sandybridge` for GCC >= 4.9.0.
This enables the [Advanced Vector Extensions support](http://en.wikipedia.org/wiki/Advanced_Vector_Extensions) as well as the AES and [PCLMUL](https://en.wikipedia.org/wiki/CLMUL_instruction_set) instruction sets for Sandy Bridge. Here's the overview from the GCC i386/x86\_64 options page:
> Intel Core i7 CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, AVX, AES and PCLMUL instruction set support.
* **[Ivy-Bridge-based](http://en.wikipedia.org/wiki/Ivy_Bridge_%28microarchitecture%29) Xeon** (E3-12xx v2-series, E5-14xx v2/24xx v2-series, E5-16xx v2/26xx v2/46xx v2-series, E7-28xx v2/48xx v2/88xx v2-series).
`-march=core-avx-i` for GCC < 4.9.0 or `-march=ivybridge` for GCC >= 4.9.0.
This includes the Sandy Bridge (corei7-avx) options while also tacking in support for the new Ivy instruction sets: FSGSBASE, [RDRND](http://en.wikipedia.org/wiki/RdRand) and [F16C](http://en.wikipedia.org/wiki/F16C). From GCC options page:
> Intel Core CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, AVX, AES, PCLMUL, FSGSBASE, RDRND and F16C6 instruction set support.
* **[Haswell-based](http://en.wikipedia.org/wiki/Haswell_(microarchitecture)) Xeon** (E3-1xxx v3-series, E5-1xxx v3-series, E5-2xxx v3-series).
`-march=core-avx2` for GCC 4.8.2/4.8.3 or `-march=haswell` for GCC >= 4.9.0.
From GCC options page:
> Intel Haswell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2 and F16C instruction set support.
* **[Broadwell-based](https://en.wikipedia.org/wiki/Broadwell_%28microarchitecture%29) Xeon** (E3-12xx v4 series, E5-16xx v4 series)
`-march=core-avx2` for GCC 4.8.x or `-march=broadwell` for GCC >= 4.9.0.
From GCC options page:
> Intel Broadwell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX and PREFETCHW instruction set support.
* **[Skylake-based](https://en.wikipedia.org/wiki/Skylake_%28microarchitecture%29) Xeon** (E3-12xx v5 series) and **[KabyLake-based](https://en.wikipedia.org/wiki/Kaby_Lake) Xeon** (E3-12xx v6 series):
`-march=core-avx2` for GCC 4.8.x or `-march=skylake` for GCC 4.9.x or `-march=skylake-avx512` for GCC >= 5.x
[AVX-512](https://en.wikipedia.org/wiki/AVX-512) are 512-bit extensions to the 256-bit Advanced Vector Extensions SIMD instructions.
From GCC options page:
> Intel Skylake Server CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ and AVX512CD instruction set support.
* **[Coffee Lake-based](https://en.wikipedia.org/wiki/Skylake_%28microarchitecture%29) Xeon** (E-21xx): `-march=skylake-avx512`.
* **[Cascade Lake-based](https://en.wikipedia.org/wiki/Cascade_Lake_(microarchitecture)) Xeon** (Platinum 8200/9200 series, Gold 5200/6200 series, Silver 4100/4200 series, Bronze 3100/3200 series): `-march=cascade-lake` (requires [gcc 9.x](https://gcc.gnu.org/gcc-9/changes.html#x86)).
From GCC options page:
> enables MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD and AVX512VNNI.
[AVX-512 Vector Neural Network Instructions](https://en.wikichip.org/wiki/x86/avx512vnni) (AVX512 VNNI) is an x86 extension, part of the AVX-512, designed to accelerate convolutional neural network-based algorithms.
* **[Cooper Lake-based](https://en.wikichip.org/wiki/intel/microarchitectures/cooper_lake) Xeon** (Platinum, Gold, Silver, Bronze): `-march=cooperlake` (requires [gcc 10.1](https://gcc.gnu.org/gcc-9/changes.html#x86)).
The switch enables the AVX512BF16 ISA extensions.
---
To find out what the compiler will do with the `-march=native` option you can use:
```
gcc -march=native -Q --help=target
``` | gcc optimization flags for Xeon? | [
"",
"c++",
"c",
"optimization",
"gcc",
"compiler-flags",
""
] |
For Python, it can create a pre-compiled version file.pyc so that the program can be run without interpreted again. Can Ruby, PHP, and Perl do the same on the command line? | There is no portable bytecode specification for Ruby, and thus also no standard way to load precompiled bytecode archives. However, almost all Ruby implementations use some kind of bytecode or intcode format, and several of them can dump and reload bytecode archives.
[YARV](http://Ruby-Lang.Org/) always compiles to bytecode before executing the code, however that is usually only done in memory. There are ways to dump out the bytecode to disk. [At the moment, there is no way to read it back *in*](https://GitHub.Com/RubySpec/MatzRuby/blob/trunk/iseq.c#L1427-1429), however. This will change in the future: work is underway on a bytecode verifier for YARV, and once that is done, bytecode can safely be loaded into the VM, without fear of corruption. Also, the JRuby developers have indicated that they are willing to implement a [YARV VM emulator inside JRuby](https://GitHub.Com/JRuby/JRuby/blob/da23e51968ffc17d750fca340f4b9538e5e2b425/src/org/jruby/ast/executable/YARVMachine.java), once the YARV bytecode format and verifier are stabilized, so that you could load YARV bytecode into JRuby. (Note that this version is [obsolete](https://GitHub.Com/JRuby/JRuby/commit/2257c8f811fab8d675a942c86ab712922dc46c6f/).)
[Rubinius](http://Rubini.us/) also always compiles to bytecode, and it has a [format for compiled files](https://GitHub.Com/EvanPhx/Rubinius/blob/master/kernel/compiler/compiled_file.rb) (`.rbc` files, analogous to JVM `.class` files) and there is talk about a bytecode archive format (`.rba` files, analogous to JVM `.jar` files). There is a chance that Rubinius might implement a YARV emulator, if deploying apps as YARV bytecode ever becomes popular. Also, the JRuby developers have indicated that they are willing to implement a [Rubinius bytecode emulator inside JRuby](https://GitHub.Com/JRuby/JRuby/blob/da23e51968ffc17d750fca340f4b9538e5e2b425/src/org/jruby/ast/executable/RubiniusMachine.java), if Rubinius bytecode becomes a popular way of deploying Ruby apps. (Note that this version is [obsolete](https://GitHub.Com/JRuby/JRuby/commit/2257c8f811fab8d675a942c86ab712922dc46c6f/).)
[XRuby](http://XRuby.GoogleCode.Com/) is a pure compiler, it compiles Ruby sourcecode straight to JVM bytecode (`.class` files). You can deploy these `.class` files just like any other Java application.
[JRuby](http://JRuby.Org/) started out as an interpreter, but it has both a JIT compiler and an [AOT compiler](https://GitHub.Com/JRuby/JRuby/tree/master/src/org/jruby/compiler/) (`jrubyc`) that can compile Ruby sourcecode to JVM bytecode (`.class` files). Also, work is underway to create a [*new* compiler that can compile (type-annotated) Ruby code to JVM bytecode](https://GitHub.Com/JRuby/JRuby/blob/master/tool/compiler2.rb) that actually looks like a Java class and can be used from Java code without barriers.
[Ruby.NET](http://RubyDotNETCompiler.GoogleCode.Com/) is a pure compiler that compiles Ruby sourcecode to CIL bytecode (PE `.dll` or `.exe` files). You can deploy these just like any other CLI application.
[IronRuby](http://IronRuby.Net/) also compiles to CIL bytecode, but typically does this in-memory. However, you can pass [commandline switches to it](https://GitHub.Com/IronRuby/IronRuby/blob/master/Merlin/Main/Languages/Ruby/Ruby/Hosting/RubyOptionsParser.cs#L275-276), so it dumps the `.dll` and `.exe` files out to disk. Once you have those, they can be deployed normally.
[BlueRuby](https://SDN.SAP.Com/irj/scn/wiki?path=/display/Research/BlueRuby) automatically pre-parses Ruby sourcecode into BRIL (BlueRuby Intermediate Language), which is basically a serialized parsetree. (See [*Blue Ruby - A Ruby VM in SAP ABAP*](https://SDN.SAP.Com/irj/scn/go/portal/prtroot/docs/library/uuid/408a9a3b-03f9-2b10-b29c-f0a3374b19d8)(PDF) for details.)
I *think* (but I am definitely not sure) that there is a way to get [Cardinal](https://GitHub.Com/Cardinal/Cardinal/) to dump out [Parrot](http://ParrotCode.Org/) bytecode archives. (Actually, Cardinal only compiles to PAST, and then Parrot takes over, so it would be Parrot's job to dump and load bytecode archives.) | Perl 5 can dump the bytecodes to disk, but it is buggy and nasty. [Perl 6](http://perlcabal.org/syn/) has a very clean method of creating bytecode executables that [Parrot](http://www.parrot.org/) can run.
Perl's just-in-time compilation is fast enough that this doesn't matter in most circumstances. One place where it does matter is in a CGI environment which is what [mod\_perl](http://perl.apache.org/) is for. | Can Ruby, PHP, or Perl create a pre-compiled file for the code like Python? | [
"",
"php",
"ruby",
"perl",
"pre-compilation",
""
] |
I have a statement that looks something like this:
```
MERGE INTO someTable st
USING
(
SELECT id,field1,field2,etc FROM otherTable
) ot on st.field1=ot.field1
WHEN NOT MATCHED THEN
INSERT (field1,field2,etc)
VALUES (ot.field1,ot.field2,ot.etc)
```
where **otherTable** has an autoincrementing **id** field.
I would like the insertion into **someTable** to be in the same order as the **id** field of **otherTable**, such that the *order* of **id**s is preserved when the non-matching fields are inserted.
A quick look at the [docs](http://technet.microsoft.com/en-us/library/bb510625.aspx) would appear to suggest that there is no feature to support this.
Is this possible, or is there another way to do the insertion that would fulfil my requirements?
EDIT: One approach to this would be to add an additional field to **someTable** that captures the ordering. I'd rather not do this if possible.
... upon reflection the approach above seems like the way to go. | Why would you care about the order of the ids matching? What difference would that make to how you query the data? Related tables should be connected through primary and foreign keys, not order records were inserted. Tables are not inherently ordered a particular way in databases. Order should come from the order by clause.
More explanation as to why you want to do this might help us steer you to an appropriate solution. | I cannot speak to what the Questioner is asking for here because it doesn't make ***any*** sense.
## So let's assume a different problem:
Let's say, instead, that I have a Heap-Table with no Identity-Field, but it does have a "*Visited*" Date field.
The Heap-Table logs Person WebPage Visits and I'm loading it into my Data Warehouse.
In this Data Warehouse I'd like to use the Surrogate-Key "*WebHitID*" to reference these relationships.
Let's use Merge to do the initial load of the table, then continue calling it to keep the tables in sync.
I know that if I'm inserting records into an table, then I'd prefer the ID's (that are being generated by an Identify-Field) to be sequential based on whatever Order-By I choose (let's say the "*Visited*" Date).
It is not uncommon to expect an Integer-ID to correlate to when it was created relative to the rest of the records in the table.
I know this is not always 100% the case, but humor me for a moment.
## This is possible with Merge.
Using (what feels like a ***hack***) TOP will allow for Sorting in our Insert:
```
MERGE DW.dbo.WebHit AS Target --This table as an Identity Field called WebHitID.
USING
(
SELECT TOP 9223372036854775807 --Biggest BigInt (to be safe).
PWV.PersonID, PWV.WebPageID, PWV.Visited
FROM ProdDB.dbo.Person_WebPage_Visit AS PWV
ORDER BY PWV.Visited --Works only with TOP when inside a MERGE statement.
) AS Source
ON Source.PersonID = Target.PersonID
AND Source.WebPageID = Target.WebPageID
AND Source.Visited = Target.Visited
WHEN NOT MATCHED BY Target THEN --Not in Target-Table, but in Source-Table.
INSERT (PersonID, WebPageID, Visited) --This Insert populates our WebHitID.
VALUES (Source.PersonID, Source.WebPageID, Source.Visited)
WHEN NOT MATCHED BY Source THEN --In Target-Table, but not in Source-Table.
DELETE --In case our WebHit log in Prod is archived/trimmed to save space.
;
```
You can see I opted to use TOP 9223372036854775807 (the biggest Integer there is) to pull everything.
If you have the resources to merge more than that, then you should be chunking it out.
While this screams "***hacky workaround***" to me, it should get you where you need to go.
I have tested this on a small sample set and verified it works.
I have not studied the performance impact of it on larger complex sets of data though, so YMMV with and without the TOP. | MERGE INTO insertion order | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008",
"merge",
""
] |
Hey all, I was working on a recursive generator to create the fixed integer partitions of a number and I was confused by a scoping issue.
The code is similar to this snippet.
```
def testGen(a,n):
if n <= 1:
print('yield', a)
yield a
else:
for i in range(2):
a[i] += n
for j in testGen(a,n-i-1):
yield j
```
My confusion is illustrated below.
```
>>> list(testGen([1,2],4))
yield [10, 2]
yield [10, 4]
yield [10, 7]
yield [12, 11]
yield [12, 13]
[[12, 13], [12, 13], [12, 13], [12, 13], [12, 13]]
```
I can get the right answer simply by using a copy of the array (e.g. passing in `a[:]` to the recursive call) but I still don't understand the above behavior.
Why are the print statements and yield values different? | The print statement displays the list at that particular point in time. Your code changes the list as you run it, so by the time you examine the list at the end, you see its value then.
You can observe this by stepping through:
```
>>> g = testGen([1,2],4)
>>> g.next()
('yield', [10, 2]) # note brackets in print statement because I'm on python 2.5
[10, 2]
>>> g.next()
('yield', [10, 4])
[10, 4]
>>> g.next()
('yield', [10, 7])
[10, 7]
>>> g.next()
('yield', [12, 11])
[12, 11]
>>> g.next()
('yield', [12, 13])
[12, 13]
``` | I would guess you are mutating the array, so when you print it has a particular value, then the next time you print it has actually updated the value, and so on. At the end, you have 5 references to the same array, so of course you have the same value 5 times. | Scope of Python Recursive Generators | [
"",
"python",
"recursion",
"scope",
"generator",
""
] |
I have a big file, it's expected to be around 12 GB. I want to load it all into memory on a beefy 64-bit machine with 16 GB RAM, but I think Java does not support byte arrays that big:
```
File f = new File(file);
long size = f.length();
byte data[] = new byte[size]; // <- does not compile, not even on 64bit JVM
```
Is it possible with Java?
The compile error from the Eclipse compiler is:
```
Type mismatch: cannot convert from long to int
```
javac gives:
```
possible loss of precision
found : long
required: int
byte data[] = new byte[size];
``` | Java array indices are of type `int` (4 bytes or 32 bits), so I'm afraid you're limited to 231 − 1 or 2147483647 slots in your array. I'd read the data into another data structure, like a 2D array. | ```
package com.deans.rtl.util;
import java.io.FileInputStream;
import java.io.IOException;
/**
*
* @author william.deans@gmail.com
*
* Written to work with byte arrays requiring address space larger than 32 bits.
*
*/
public class ByteArray64 {
private final long CHUNK_SIZE = 1024*1024*1024; //1GiB
long size;
byte [][] data;
public ByteArray64( long size ) {
this.size = size;
if( size == 0 ) {
data = null;
} else {
int chunks = (int)(size/CHUNK_SIZE);
int remainder = (int)(size - ((long)chunks)*CHUNK_SIZE);
data = new byte[chunks+(remainder==0?0:1)][];
for( int idx=chunks; --idx>=0; ) {
data[idx] = new byte[(int)CHUNK_SIZE];
}
if( remainder != 0 ) {
data[chunks] = new byte[remainder];
}
}
}
public byte get( long index ) {
if( index<0 || index>=size ) {
throw new IndexOutOfBoundsException("Error attempting to access data element "+index+". Array is "+size+" elements long.");
}
int chunk = (int)(index/CHUNK_SIZE);
int offset = (int)(index - (((long)chunk)*CHUNK_SIZE));
return data[chunk][offset];
}
public void set( long index, byte b ) {
if( index<0 || index>=size ) {
throw new IndexOutOfBoundsException("Error attempting to access data element "+index+". Array is "+size+" elements long.");
}
int chunk = (int)(index/CHUNK_SIZE);
int offset = (int)(index - (((long)chunk)*CHUNK_SIZE));
data[chunk][offset] = b;
}
/**
* Simulates a single read which fills the entire array via several smaller reads.
*
* @param fileInputStream
* @throws IOException
*/
public void read( FileInputStream fileInputStream ) throws IOException {
if( size == 0 ) {
return;
}
for( int idx=0; idx<data.length; idx++ ) {
if( fileInputStream.read( data[idx] ) != data[idx].length ) {
throw new IOException("short read");
}
}
}
public long size() {
return size;
}
}
}
``` | Java array with more than 4gb elements | [
"",
"java",
"arrays",
"64-bit",
""
] |
I'm trying to make a simple forum just to get the hang of the Spring Security and MVC frameworks.
For simplicity's sake, let's I have a JSP to view a forum post, which looks like the following:
```
<body>
...
Title: ${forumPost.title} <br>
Author: ${forumPost.author.name} <br>
Message: {forumPost.message} <br>
<security:authorize ifAnyGranted="ROLE_ADMIN">
Edit: <a href="/edit">Edit</a>
</security:authorize>
...
</body>
```
My problem is: not only should an Administrator be able to edit this post, but the original author should be able to as well. Therefore, I only want ROLE\_ADMIN and the original author to be able to see the Edit link. However I'm not sure how to filter by user with the *security:authorize* tag, or if I'll need to go about this a different way.
Any suggestions would be much appreciated. Thanks! | Assuming that you have a controller that sits behind this page, I would simply add a `canEditPost` field to the `ModelAndView` that looks something like (semi-pseudocode):
```
private boolean isAdmin() {
Authentication currentAuthObj = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> authorities = Arrays.asList(currentAuthObj.getAuthorites());
for (GrantedAuthority auth : authorities) {
if ("ROLE_ADMIN".equals(auth.getAuthority())) {
return true;
}
}
return false;
}
boolean currentUserIsAuthor = ...;
modelAndView.addObject("canEditPost",
Boolean.valueOf(currentUserIsAuthor || isAdmin());
```
And then in your view just reference $canEditPost.
It's generally better for the view to just reference a simple flag in the model than have the view/template doing the actual logic. | Does your `Author` object implement `equals` in such a way that each author is unique?
If so, you could simply check if the `Author` is the same as the current user (You'd have two sets of tags). | Conditionally Render In JSP By User | [
"",
"java",
"spring",
"jsp",
"spring-mvc",
"spring-security",
""
] |
What are the scoping rules for variables in a jsp page with pages added to them using tags?
My understanding is that an included page is essentially copied verbatim into the page, which would lead me to assume that if I've declared a variable in a Parent JSP that it would be available in the child ones.
However Eclipse complains about this (understandably because I could feasibly include the pages in any page or use them as stand alone. And when I try to start the tomcat server it fails to start.
I basically want to get a couple of variables from the session in the parent page and use them in the child pages. This doesn't work.
So I've struck ont he idea of getting them from the session in each of the child pages, however I was wondering if I could give them all the same variable names, or if I'd have to pick different variable names for them in each page so they didn't clash.
Also what about imports if I import log4net in the parent jss do I also have to import it in the child ones? | In JSP there are two ways of including other jsp pages.
```
<%@include file="include.jsp"%>
```
and
```
<jsp:include page="include.jsp" />
```
If you use the former, then any variable declared on the parent JSP will be in scope in the include.jsp (of course Eclipse will not see this as you surmised) as it is effectively copied in by the compiler.
If you use the second approach, the inclusion is done at runtime and the include page has its own scope.
Ditto for imports. Although it is safe to redundantly import them in the include page.
If I'm using the former I prefer to suffix them with .jspf to signify a JSP fragment. I can than turn off some of Eclipses warning in the fragment files. But in general I try to avoid using that method and prefer the second approach.
More information can be found in the docs here: [Include directive](http://profesores.elo.utfsm.cl/~agv/elo330/2s03/projects/Tomcat/doc/1.2/syntaxref129.html) and [JSP include](http://tecfa.unige.ch/guides/jsp/jsp-ref10/syntaxref10.fm11.html). | Use the following, if you want to use variable within the path of the page to be included:
```
<% pageContext.include("/cities/" + (String) request.getAttribute("country_code") + ".jsp"); %>
``` | Variables in jsp pages with "included" pages | [
"",
"java",
"jsp",
"jakarta-ee",
""
] |
Is it better for sake of compatibility/JIT-Compiling performance to use UPPER CASE or lower case, in JS/HTML? For eg:
```
<DIV> my content </DIV>
<div> my content </div>
ALERT(DOCUMENT.LOCATION);
alert(document.location);
```
This is not a newbie question, I know lowercase is the de-facto standard. But since I've seen some uppercase JS+HTML, I was wondering which would be better to write in. (like SQL is fully uppercase?) | I don't think it'd make a difference, speed-wise.
XHTML: Lowercase tags is what the W3C specified.
JavaScript: It probably wouldn't work, because I have *never* seen anyone's code use all caps in JS.
SQL is fully uppercase to differentiate the actions, functions, etc from the actual data. You can use lowercase, but it becomes less readable (to some, me included).
IMO, wading through a heap of uppercase tags is less readable than lowercase tags. I'd say user agents don't care what case the tags are. Here's a little bit of history: when I made a website in 1999, uppercase tags were the standard.
You can still find some dodgy non updated websites out there that still write
> 'Use `<B></B>` to make text bold' | It is incorrect (in xhtml, at least) to use `<DIV>...</DIV>`; it is a `<div>...</div>`.
Likewise, I'd use lower-case in the javascript (for `alert(document.location);`), as **that is their names** ;-p | JavaScript/HTML in UPPER or lower case? | [
"",
"javascript",
"html",
"case-sensitive",
"case-insensitive",
""
] |
I want to get over a nasty problem that shows up yesterday during a demo to a client. We're using `jQuery`, loading it from google api. But yesterday, our ISP begin to cause some problems, and didn't load `jq.js` properly.
So, what I really want is to load a local file from the server if google api has an extrange behaviour (not that it's going to happen often, but at least doing local demos we won't get harmed again).
I know that `<script type="txt/javascript" src="googleapi"> somejs </script>` executes some js when file in src doesn't load, but don't know any way to get the file load there.
Thanks in advance | inside you can put the following lines:
```
var localScript = document.createElement("script");
localScript.type = "text/javascript";
localScript.src = "localJQ.js";
document.body.appendChild(localScript);
``` | Edit :
I was a bit jumpy. The solution given by peirix is correct. I'll just use his code, to not let the wrong solution pollute this area. You can do
```
var localScript = document.createElement("script");
localScript.type = "text/javascript";
localScript.src = "localJQ.js";
document.body.appendChild(localScript);
```
to load Javascript dynamically.
Even this is prone to race conditions, however, if there are scripts in your page that depend on this script. Use with care.
This presentation - [Even Faster Websites](http://docs.google.com/Present?docid=ddfdgz6g_2056fq35k2fm) - elaborates on more techniques to load external files through javascript. | How to load a js file with Javascript | [
"",
"asp.net",
"javascript",
"jquery",
""
] |
How can I tell if a point belongs to a certain line?
Examples are appreciated, if possible. | I just wrote an function which handles a few extra requirements since I use this check in a drawing application:
* Fuzziness - There must be some room for error since the function is used to select lines by clicking on them.
* The line got an EndPoint and a StartPoint, no infinite lines.
* Must handle straight vertical and horizontal lines, (x2 - x1) == 0 causes division by zero in the other answers.
```
private const double SELECTION_FUZZINESS = 3;
internal override bool ContainsPoint(Point point)
{
LineGeometry lineGeo = geometry as LineGeometry;
Point leftPoint;
Point rightPoint;
// Normalize start/end to left right to make the offset calc simpler.
if (lineGeo.StartPoint.X <= lineGeo.EndPoint.X)
{
leftPoint = lineGeo.StartPoint;
rightPoint = lineGeo.EndPoint;
}
else
{
leftPoint = lineGeo.EndPoint;
rightPoint = lineGeo.StartPoint;
}
// If point is out of bounds, no need to do further checks.
if (point.X + SELECTION_FUZZINESS < leftPoint.X || rightPoint.X < point.X - SELECTION_FUZZINESS)
return false;
else if (point.Y + SELECTION_FUZZINESS < Math.Min(leftPoint.Y, rightPoint.Y) || Math.Max(leftPoint.Y, rightPoint.Y) < point.Y - SELECTION_FUZZINESS)
return false;
double deltaX = rightPoint.X - leftPoint.X;
double deltaY = rightPoint.Y - leftPoint.Y;
// If the line is straight, the earlier boundary check is enough to determine that the point is on the line.
// Also prevents division by zero exceptions.
if (deltaX == 0 || deltaY == 0)
return true;
double slope = deltaY / deltaX;
double offset = leftPoint.Y - leftPoint.X * slope;
double calculatedY = point.X * slope + offset;
// Check calculated Y matches the points Y coord with some easing.
bool lineContains = point.Y - SELECTION_FUZZINESS <= calculatedY && calculatedY <= point.Y + SELECTION_FUZZINESS;
return lineContains;
}
``` | In the simplest form, just plug the coordinates into the line equation and check for equality.
Given:
```
Point p (X=4, Y=5)
Line l (Slope=1, YIntersect=1)
```
Plug in X and Y:
```
Y = Slope * X + YIntersect
=> 5 = 1 * 4 + 1
=> 5 = 5
```
So yes, the point is on the line.
If your lines are represented in (X1,Y1),(X2,Y2) form, then you can calculate slope with:
```
Slope = (y1 - y2) / (x1-x2)
```
And then get the Y-Intersect with this:
```
YIntersect = - Slope * X1 + Y1;
```
Edit: I fixed the Y-Intersect (which has been X1 / Y1 ...)
You'll have to check that `x1 - x2` is not `0`. If it is, then checking if the point is on the line is a simple matter of checking if the Y value in your point is equal to either `x1` or `x2`. Also, check that the X of the point is not 'x1' or 'x2'. | How can I tell if a point belongs to a certain line? | [
"",
"c#",
".net",
"algorithm",
"gdi+",
"line",
""
] |
I am reading in a text file using `FileInputStream` that puts the file contents into a byte array. I then convert the byte array into a String using new String(byte).
Once I have the string I'm using `String.split("\n")` to split the file into a String array and then taking that string array and parsing it by doing a `String.split(",")` and hold the contents in an Arraylist.
I have a *200MB+* file and it is running out of memory when I start the JVM up with a 1GB of memory. I know I must be doing something in correctly somewhere, I'm just not sure if the way I'm parsing is incorrect or the data structure I'm using.
It is also taking me about 12 seconds to parse the file which seems like a lot of time. Can anyone point out what I may be doing that is causing me to run out of memory and what may be causing my program to run slow?
The contents of the file look as shown below:
```
"12334", "100", "1.233", "TEST", "TEXT", "1234"
"12334", "100", "1.233", "TEST", "TEXT", "1234"
.
.
.
"12334", "100", "1.233", "TEST", "TEXT", "1234"
```
Thanks | It sounds like you're doing something wrong to me - a whole lotta object creation going on.
How representative is that "test" file? What are you really doing with that data? If that's typical of what you really have, I'd say there's lots of repetition in that data.
If it's all going to be in Strings anyway, start with a BufferedReader to read each line. Pre-allocate that List to a size that's close to what you need so you don't waste resources adding to it each time. Split each of those lines at the comma; be sure to strip off the double quotes.
You might want to ask yourself: "Why do I need this whole file in memory all at once?" Can you read a little, process a little, and never have the whole thing in memory at once? Only you know your problem well enough to answer.
Maybe you can fire up jvisualvm if you have JDK 6 and see what's going on with memory. That would be a great clue. | I'm not sure how efficient it is memory-wise, but my first approach would be using a [Scanner](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html) as it is incredibly easy to use:
```
File file = new File("/path/to/my/file.txt");
Scanner input = new Scanner(file);
while(input.hasNext()) {
String nextToken = input.next();
//or to process line by line
String nextLine = input.nextLine();
}
input.close();
```
Check the API for how to alter the delimiter it uses to split tokens. | Text File Parsing in Java | [
"",
"java",
"file",
"parsing",
""
] |
How can I read inputs (letters, numbers) from my file.txt wherein it reads infinitely but only stops when it encounters special symbols? At the same time when it is numbers i.e
```
123,345,abc
```
it should translate the ascii code and add the 2 values that results as 123 + 345 = 468
**EDITED QUESTION**
Here's my code; I really had a problem with reading those bytes in my file.txt. I want to convert its value where Isimilarly added it in my file.txt
```
public class .... {
static char tmp = 0;
public static void main(String[] args) {
try {
Reader myReader = new FileReader("MyFolder/myFile2.txt");
List<Character> myList = new ArrayList<Character>();
/*for(int myData = myInputStream.read();
myData != -1;
myData = myInputStream.read()){
System.out.print(" " + (char)myData);
}*/
for(int myData = myReader.read();
myData != -1;
myData = myReader.read()){
if((char)myData != ','){
myList.add((char)myData);
}
else{
continue;
}
}
for(Character i: myList)
{
tmp = 1;
}
String myString = String.valueOf(tmp);
int num1 = Integer.parseInt(myString);
int num2 = Integer.parseInt(myString);
int equal = num1 + num2;
System.out.print(equal);
myReader.close();
}
catch(FileNotFoundException e){
}
catch(IOException e){
}
}
}
``` | Here's some basic code to do what I think you're asking for, building off of what you already have.
```
public class .... {
private static final Pattern COMMA = Pattern.compile(",");
public static void main(String[] args) {
try {
BufferedReader myReader =
new BufferedReader(new FileReader("MyFolder/myFile2.txt"));
List<Integer> myList = new ArrayList<Integer>();
int total = 0;
String line;
while ((line = myReader.readLine()) != null) {
for (String token : COMMA.split(line)) {
try {
total += Integer.parseInt(token);
} catch (NumberFormatException ex) {
System.err.println(token + " is not a number");
}
}
}
System.out.print(total);
myReader.close();
} catch(FileNotFoundException e){
} catch(IOException e){
}
}
}
```
Note that it would be better to restructure this so it isn't all in `main()`, and the exception handling isn't very good, but I'm just going for the basics here. | You're working way too hard, and you're mixing your parsing logic with your file traversal, which is making things seem way more complicated than they actually are:
-traverse the lines of the file;
```
BufferedReader r = new BufferedReader(new FileReader(myFile));
String line;
while ((line=r.readLine())!=null)
{
parseLine(line)
}
```
-parse the lines of the file into the form you expect. Have it fail if the form is wrong.
```
private void parseLine(String line)
{
try{
String[] values = line.split(",");
//do something useful assuming the line is properly formed
}
catch(Exception e)
{
//how do you want to handle badly formed lines?
}
``` | How can I read numbers from a file in Java? | [
"",
"java",
"file-io",
""
] |
**Usage scenario**
We have implemented a webservice that our web frontend developers use (via a php api) internally to display product data. On the website the user enters something (i.e. a query string). Internally the web site makes a call to the service via the api.
**Note: We use restlet, not tomcat**
**Original Problem**
Firefox 3.0.10 seems to respect the selected encoding in the browser and encode a url according to the selected encoding. This does result in different query strings for ISO-8859-1 and UTF-8.
Our web site forwards the input from the user and does not convert it (which it should), so it may make a call to the service via the api calling a webservice using a query string that contains german umlauts.
I.e. for a query part looking like
```
...v=abcädef
```
if "ISO-8859-1" is selected, the sent query part looks like
```
...v=abc%E4def
```
but if "UTF-8" is selected, the sent query part looks like
```
...v=abc%C3%A4def
```
**Desired Solution**
As we control the service, because we've implemented it, we want to check on **server side** wether the call contains non utf-8 characters, if so, respond with an 4xx http status
**Current Solution In Detail**
Check for each character ( == string.substring(i,i+1) )
1. if character.getBytes()[0] equals 63 for '?'
2. if Character.getType(character.charAt(0)) returns OTHER\_SYMBOL
**Code**
```
protected List< String > getNonUnicodeCharacters( String s ) {
final List< String > result = new ArrayList< String >();
for ( int i = 0 , n = s.length() ; i < n ; i++ ) {
final String character = s.substring( i , i + 1 );
final boolean isOtherSymbol =
( int ) Character.OTHER_SYMBOL
== Character.getType( character.charAt( 0 ) );
final boolean isNonUnicode = isOtherSymbol
&& character.getBytes()[ 0 ] == ( byte ) 63;
if ( isNonUnicode )
result.add( character );
}
return result;
}
```
**Question**
Will this catch all invalid (non utf encoded) characters?
Does any of you have a better (easier) solution?
**Note:** I checked URLDecoder with the following code
```
final String[] test = new String[]{
"v=abc%E4def",
"v=abc%C3%A4def"
};
for ( int i = 0 , n = test.length ; i < n ; i++ ) {
System.out.println( java.net.URLDecoder.decode(test[i],"UTF-8") );
System.out.println( java.net.URLDecoder.decode(test[i],"ISO-8859-1") );
}
```
This prints:
```
v=abc?def
v=abcädef
v=abcädef
v=abcädef
```
and it does **not** throw an IllegalArgumentException *sigh* | I asked the same question,
[Handling Character Encoding in URI on Tomcat](https://stackoverflow.com/questions/1233076/handling-character-encoding-in-uri-on-tomcat)
I recently found a solution and it works pretty well for me. You might want give it a try. Here is what you need to do,
1. Leave your URI encoding as Latin-1. On Tomcat, add URIEncoding="ISO-8859-1" to the Connector in server.xml.
2. If you have to manually URL decode, use Latin1 as charset also.
3. Use the fixEncoding() function to fix up encodings.
For example, to get a parameter from query string,
```
String name = fixEncoding(request.getParameter("name"));
```
You can do this always. String with correct encoding is not changed.
The code is attached. Good luck!
```
public static String fixEncoding(String latin1) {
try {
byte[] bytes = latin1.getBytes("ISO-8859-1");
if (!validUTF8(bytes))
return latin1;
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
// Impossible, throw unchecked
throw new IllegalStateException("No Latin1 or UTF-8: " + e.getMessage());
}
}
public static boolean validUTF8(byte[] input) {
int i = 0;
// Check for BOM
if (input.length >= 3 && (input[0] & 0xFF) == 0xEF
&& (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) {
i = 3;
}
int end;
for (int j = input.length; i < j; ++i) {
int octet = input[i];
if ((octet & 0x80) == 0) {
continue; // ASCII
}
// Check for UTF-8 leading byte
if ((octet & 0xE0) == 0xC0) {
end = i + 1;
} else if ((octet & 0xF0) == 0xE0) {
end = i + 2;
} else if ((octet & 0xF8) == 0xF0) {
end = i + 3;
} else {
// Java only supports BMP so 3 is max
return false;
}
while (i < end) {
i++;
octet = input[i];
if ((octet & 0xC0) != 0x80) {
// Not a valid trailing byte
return false;
}
}
}
return true;
}
```
EDIT: Your approach doesn't work for various reasons. When there are encoding errors, you can't count on what you are getting from Tomcat. Sometimes you get � or ?. Other times, you wouldn't get anything, getParameter() returns null. Say you can check for "?", what happens your query string contains valid "?" ?
Besides, you shouldn't reject any request. This is not your user's fault. As I mentioned in my original question, browser may encode URL in either UTF-8 or Latin-1. User has no control. You need to accept both. Changing your servlet to Latin-1 will preserve all the characters, even if they are wrong, to give us a chance to fix it up or to throw it away.
The solution I posted here is not perfect but it's the best one we found so far. | You can use a CharsetDecoder configured to throw an exception if invalid chars are found:
```
CharsetDecoder UTF8Decoder =
Charset.forName("UTF8").newDecoder().onMalformedInput(CodingErrorAction.REPORT);
```
See [CodingErrorAction.REPORT](http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/CodingErrorAction.html#REPORT) | How to determine if a String contains invalid encoded characters | [
"",
"java",
"string",
"unicode",
"encoding",
""
] |
I have a requirement to hide the contextmenustrip when a particular flag is not set. As i don't think we can explicitly control the show/hide of the context menu strip, i decided to trap the right mouse button click on the control with which the contextmenustrip is associated. It is a UserControl, so i tried handling it's MouseClick event inside which i check if the flag is set and if the button is a right button. However to my amazement, the event doesn't get fired upon Mouse Right Click, but fires only for Left Click.
Is there any thing wrong with me or is there any workaround?
**RIGHT CLICK IS GETTING DETECTED, Question TITLE and Description Changed**
After Doing some more research, i got the rightclick to fire, when i Handled the Mouse\_Down Event on the Control. However Am still clueless, as how *to explicitly prevent the ContextMenuStrip From Loading*. Another question being, why MouseClick didn't detect Right Button Click?
---
Current WorkAround
Registering the event handler
```
userControl1.Control1.MouseDown += new MouseEventHandler(Control1_MouseDown);
void Control1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right && flag == false)
{
userControl1.Control1.ContextMenuStrip = null;
}
else
{
userControl1.Control1.ContextMenuStrip = contextMenuStrip1;
}
}
```
this is the current workaround i'm doing.
But how can i change it in the Opening Event of the ContextMenuStrip | Your solution will fail anyway when the context menu is invoked with the context menu key (or what it's called) on the keyboard. You can use the `Opening` event to cancel the opening of a context menu. | There is a work around.
Lets say Menu Item A sets the flag that controls the context menu on control B.
In the click event for A, you set b.ContextMenu = nothing to switch it off, and set b.ContextMenu back to the context menu control to switch it back on. | Explicitly Prevent ContextMenuStrip from Loading in C# | [
"",
"c#",
"user-controls",
"mouseclick-event",
"right-mouse-button",
""
] |
I'm starting a small/medium-sized python project, likely in Test Driven Development. My backgrounds are more in C and java than python (I used ant and makefile)
I know that in python you might not need a build tool, but I will, because I'll use cython and PyInstaller (the thing should work on a couple of different UNIXes, without depending directly on python) and I'd like the convenience of selecting the tests form CLI, building the docs, maybe check dependencies, etc.
[Somebody](http://blog.ianbicking.org/pythons-makefile.html) is complaining that python lacks a make-like tool.
I know that few tools exist, like [scon](http://www.scons.org/) and [paver](http://www.blueskyonmars.com/projects/paver/), but I'd like to hear from real users and not just their website. Does anybody use [paver](http://www.blueskyonmars.com/projects/paver/)?
What's about the usual setup.py that comes with many packages? I looked into a few to see if there is a common usage, but I didn't find anything interesting (maybe I used the wrong examples)
Do you recommend sticking with things I already know (ant and Makefile) at least to start? If so, is there any ant extension you recommend for python (+cython+pyinstaller+pyUnit)?
---
EDIT: to avoid further answers like jwp's one, note that, for this project, I absolutely need my program being a standalone executable because it is absolutely *impossible* to have a python VM on the target platform where the executable will run. I have exactly the same hw available for compiling, so luckly I don't need to cross-compile (but I'd do the development on a more friendly Linux).
I'd also like to test if my code compile in Cython from the beginning, not to premature optimize, but just to be sure that I'm not going too far with the use of incompatible features, which would require a painful refactoring if Cython would be seriously needed.
So please focus on my actual question | Your requirements suggest rather [Scons](http://www.scons.org/) which, according to their website, has more control over variety of building tasks than [Paver](http://www.blueskyonmars.com/projects/paver/). In the latter you would end up using a lot of `sh()` which runs a regular command line programs.
Recently, I started using [Paver](http://www.blueskyonmars.com/projects/paver/) which is really great to run tests, build documentations with [Sphinx](http://sphinx.pocoo.org/), but I use only pure Python.
If you want to see what's possible with Paver I highly recommend those 2 articles:
[converting-from-make-to-paver](http://doughellmann.com/2009/01/18/converting-from-make-to-paver.html) and [writing-technical-documentation](http://doughellmann.com/2009/02/02/writing-technical-documentation-with-sphinx-paver-and-cog.html) by Doug Hellmann and you definitely want to check his pavement.py [configuration file](http://www.doughellmann.com/downloads/PyMOTW-1.89.tar.gz). | (Edit: Avoid "premature" optimization advice. The recommendations for tooling in this answer are now outdated: [PEP-0632](https://peps.python.org/pep-0632/).)
If it is at all possible, I'd suggest avoiding extension modules(C/cython) **in the beginning**. Get your all code written in Python, use a simple [`distutils`](http://www.python.org/doc/current/distutils/index.html) based configuration, run your tests using `-m` (`python -m mypkg.test.testall`, or whatever; import [`unittest`](http://www.python.org/doc/current/library/unittest.html)).
Once you get your project to a comfortable state, then start tackling some optimizations with cython and the extra project management that comes with that. distutils can build extension modules, so I'm not sure you'll need make/scons.. | which build tool(s) do you recommend for python? | [
"",
"python",
"unit-testing",
"tdd",
"build-automation",
"pyinstaller",
""
] |
Ok here is the question
I have three tables
```
events
- id
- name
questions
- id
- event_id
- name
answers
- id
- question_id
- description
```
While generating the add form, i can simply search for all the questions belonging to particular event, and show the questions in single HTML form.
But consider the edit scenario. An event manager can in due time add or delete some questions from an event. So in such case, when the user tries to edit already posted answer, I generate the HTML form with the new questions as blank field and existing answers are prefilled input boxes. How can I handle the submission of this form?
When the user submits, should i delete all past answers and do a INSERT on the answers table for all the answer values? or is it a good practice to UPDATE existing answers first and INSERT only new values?
The former obiviously being easier with DELETE followed by INSERT. While the later is somewhat tedious. The problem with former solution is that the id of the answers table will increase every time.. | Some people favour the delete/insert approach because, like you say, it is simpler.
Personally I think the update/insert/delete approach, while more work, is more correct.
If you do updates you can then have an audit trail of changes to a particular item. With just insert/delete it's either much harder or plain impossible to have that kind of linkage and history.
As for how to handle the submission of the form, for fields that can be updated (ie they're existing records), you need to be able to identify the field somehow. Personally I just encode something like the primary key in the field name.
If you do this you must of course ensure that you don't have a security hole by validating that the ID supplied is valid and the edit allowed ie never trust the client.
This could take the form of:
```
<input type="text" name="name_117" value="Some value">
<input type="text" name="name_118" value="Some other value">
<input type="text" name="name_1243" value="Yet another value">
```
and you have to process all the input parameters, decode the identifier and act accordingly.
Lastly, another problem with insert/delete is that you can't do it (or it just gets really hard) if the items you're deleting/inserting relate to other tables in the database. If you have a question table and store the answers people give, normally you'll reference the question as a foreign key. You lose that association if you delete/insert instead of updating. | Agree with Cletus post, writing seperately for an extra reason and an idea:
The delete/insert approach has a concurrency issue, when your website gets some heavy traffic. Someone else could do an insert after your delete, and then you'll end up with multiple answer lists per user.
MySQL supports the [ON DUPLICATE KEY UPDATE](http://dev.mysql.com/doc/refman/5.1/en/insert.html) syntax. That might be an easy way to combine the insert and the update, if you have an appropriate primary key. | Combining SQL Insert and Delete | [
"",
"sql",
"mysql",
""
] |
In my code, I currently have an exception handling setup which logs exceptions to text files. When I'm debugging the code, however, I'd rather not handle the exceptions and let execution stop rather than read the file, set a breakpoint, etc. Is there an easy way to do this using the Build and Release configurations (something like a preprocessor directive I could use to comment out some of the exception handling code)?
It turns out that there's a better solution than the original question asked for, see the first answer. | C# does [have preprocessor directives](http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx) (e.g. if, define, etc...) that you could use for this purpose.
However, you could also modify the settings under "Debug -> Exceptions..." in Visual Studio so that the debugger breaks each time an exception is thrown (before execution goes to the catch block). | Try something like this:
```
if ( System.Diagnostics.Debugger.IsAttached )
System.Diagnostics.Debugger.Break();
else
LogException();
``` | How can I stop execution for ALL exceptions during debugging in Visual Studio? | [
"",
"c#",
"visual-studio-2008",
"build",
""
] |
I am trying to produce a C# wrapper for a COM object that I have (named SC\_COM.dll), but am having some issues linking it with Visual Studio 2008 (running Vista). I need to do this registration-free with the COM DLL--I'm using a manifest file to let Visual Studio know about SC\_COM.dll, and that appears to be working. I used TblImp.exe to generate a type library (SC\_COMtlb.dll) that I'm referencing in Visual Studio 2008 so I can do early binding with the DLL that I need. The DLLs are both in the same directory as the manifest and the executable.
Here's the issue: When I instantiate the object and try and call one of its methods in C#, it throws the following error:
> Error detected: Unable to cast COM object of type 'SC\_COMtlb.SCAccessObjClass' to interface type 'SC\_COMtlb.ISCUploader'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{C677308A-AC0F-427D-889A-47E5DC990138}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E\_NOINTERFACE)).
I'm not entirely certain what this error means--I've done a search on the error code, and it appears to be a relatively general C# error. So am I going about linking the COM object the wrong way here, or is there some other important step I may be missing?
I should probably note that I'm not entirely sure how the type library (S\C\_COMtlb.dll) that I produced knows where the actual COM DLL is, since it's not registered with the system--I assume it just looks in the same directory. Could this potentially be the issue, and if so, how can I better link the two? | Try adding this to your App.exe.manifest:
```
<comInterfaceExternalProxyStub
name="ISCUploader"
iid="{C677308A-AC0F-427D-889A-47E5DC990138}"
proxyStubClsid32="{00020424-0000-0000-C000-000000000046}"
baseInterface="{00000000-0000-0000-C000-000000000046}"
tlbid = "{PUT-YOUR-TLB-GUID-HERE}" />
```
Where TLBID can be found from your Visual Studio generated Native.Namespace.Assembly.Name.manifest, looking like this:
```
<typelib tlbid="{A-GUID-IS-HERE--USE-IT}"
version="1.0" helpdir="" resourceid="0" flags="HASDISKIMAGE" />
```
I was banging my head against this for quite some time, but I found these helpful references and pieced it together and it's working for me:
* [Why do I get E\_NOINTERFACE when creating an object that supports that interface?](http://blogs.msdn.com/oldnewthing/archive/2004/12/13/281910.aspx)
* [Registration-Free Skype4Com and multithreaded apartment](http://forum.skype.com/index.php?showtopic=243771)
* [Registration-Free Activation of COM Components: A Walkthrough](http://msdn.microsoft.com/en-us/library/ms973913.aspx) | the error code means that Visual Studio *thinks* that a certain object is supposed to implement a certain interface, but when I tries to "connect" to that interface the object responds that it doesn't know about it.
I would guess that the problem is in SC\_COM.dll. TLBIMP.EXE extracts class and interface information from metadata stored within the DLL and builds wrappers for the class.
For example, if SC\_COM is written in C++, this could happen if the creator of the DLL indicated in the IDL file that a class implements that interface, but the actual code doesn't support that interface.
Here's another common source of problems this DLL might have: sometimes you have a class implementing an ISomething2 interface which derives from an ISomething interface, but the class implementation to only recognize ISomething2. If you implement a derived interface, you must recognize its base interface as well. This is a common mistake.
Do you have (and control) the source code for the DLL? | C# wrapper interface error: E_NOINTERFACE | [
"",
"c#",
"com",
"rcw",
""
] |
Is it possible to detect repeated number patterns with a regular expression?
So for example, if I had the following string "034503450345", would it be possible to match the repeated sequence 0345? I have a feeling this is beyond the scope of regex, but I thought I would ask here anyway to see if I have missed something. | Yes, you can - here's a Python test case
```
import re
print re.search(r"(\d+).*\1", "8034503450345").group(1)
# Prints 0345
```
The regular expression says "find some sequence of digits, then any amount of other stuff, then the same sequence again."
On a barely-related note, here's one of my favourite regular expressions - a prime number detector:
```
import re
for i in range(2, 100):
if not re.search(r"^(xx+)\1+$", "x"*i):
print i
``` | This expression will match one or more repeating groups:
```
(.+)(?=\1+)
```
Here is the same expression broken down, (using commenting so it can still be used directly as a regex).
```
(?x) # enable regex comment mode
( # start capturing group
.+ # one or more of any character (excludes newlines by default)
) # end capturing group
(?= # begin lookahead
\1+ # match one or more of the first capturing group
) # end lookahead
```
To match a specific pattern, change the `.+` to that pattern, e.g. `\d+` for one or more numbers, or `\d{4,}` to match 4 or more numbers.
To match a specific number of the pattern, change `\1+`, e.g to `\1{4}` for four repetitions.
To allow the repetition to not be next to each other, you can add `.*?` inside the lookahead. | Regular Expression to detect repetition within a string | [
"",
"c#",
"regex",
""
] |
```
$output = "<loginsuccess>";
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
}
$output .= "</loginsuccess>";
```
I need now a simple condition where if the result is empty then i need to return no inside the xml [ login success ].
Is this a correct way....
```
if($row = mysql_fetch_array($result)) {
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
} } else {
$output.="no";
}
``` | Try this instead:
```
$i = 1;
while($row = mysql_fetch_array($result))
{
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
$i++;
}
if ($i == 1)
$output .= "no";
``` | ```
if (mysql_num_rows($result) == 0) {
$output .= '<loginsuccess>no</loginsuccess>';
} else {
// your code
}
``` | Condition where the result is empty in PHP | [
"",
"php",
""
] |
As all of you may know, Java code is compiled and interpreted by JVMs.
My questions deal with optimization:
Is it optimized at run-time by the JVM only or also at compile-time?
In order to write efficient code, where can I find the list of supported optimizations?
Or are JVM optimizations powerful enough so that I just have to write code that is readable and easy to maintain regardless of speed performance? | Most optimisation is done by the JVM. There's generally more scope for optimisation at the JIT level than at compile-time. (The "optimise" flag was actually taken out of `javac`, because it turned out that some "optimisations" actually hurt performance in the real world.)
In general (and this applies to many languages/platforms, not just Java):
* Write code that is as readable and maintainable as possible.
* Have performance goals and benchmarks so you can always measure performance
* Put effort into making your *architecture* perform; it's hard to change that later (compared with changing implementation)
* Think about performance more in terms of complexity of algorithms than "make it 10% faster": a change from O(n^2) to O(n) is (generally) much more important. (It very much depends on what the real world usage will be though - if you're only going to be dealing with small values of `n`, the "theoretically better" algorithm can easily end up being slower due to constant factors.)
* Use a profiler to determine where your bottlenecks are
* Only micro-optimise at the cost of readability when the profiler suggests it's worth doing
* Measure after such an optimisation - you may not have actually had much impact, in which case roll back | The Java HotSpot JIT compiler can detect "hotspots" and adaptively modify the executing code so it delivers better perfomance. Read about it [here](http://java.sun.com/products/hotspot/whitepaper.html).
On the other hand, if you want to write code which is efficient to begin with, read a book such as "[Hardcore Java](http://oreilly.com/catalog/9780596005689)" by Robert Simmons or "[Java Concurrency in Practice](http://www.javaconcurrencyinpractice.com/)" by Brian Goetz. | How to write efficient Java code? | [
"",
"java",
"optimization",
"compiler-construction",
"jvm",
""
] |
I want to read PDF files from my .net application. Are there any free libraries available to do this? | If you are looking for free PDF Read/Write .Net library, then you can visit
<https://itextpdf.com/> (previously itextsharp)
Note: As mentioned by Dexters, this is library no more free for commercial purpose. It comes under [Affero General Public License (AGPL)](http://itextpdf.com/terms-of-use/agpl.php) | You could take a look at PDFSharp: <http://www.pdfsharp.com/PDFsharp/> | PDF Reader in .NET | [
"",
"c#",
".net",
"pdf",
"pdf-reader",
""
] |
I am trying to write a wrapper around a legacy COM object and install the wrapper into the GAC. The goal would be to automate the setup of specific configuration information the component requires, and make a common strongly typed interface for all of my applications to use.
My solution thus far is to keep an XML configuration file in the same directory as the original COM DLL, and load the configuration in the class constructor. Unfortunately, I have been unable to find the location of the registered COM dll...
How do I get the full file path of the COM dll referenced by a COM object interop dll? | Once you've created an object from the respective COM server, its DLL must have been loaded. Assuming that the underlying COM server is implemented in "mycomserver.dll", you could use P/Invoke and call GetModuleHandle( "mycomserver.dll" ) -- that gives you the path of the DLL. | Presumably you could get the [`GuidAttribute`](http://social.msdn.microsoft.com/Search/en-US/?query=GuidAttribute) or [`CoClassAttribute`](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.coclassattribute.aspx) values from the interop DLL that map to the CLSID and IID values of your COM DLL. Then you can look up the appropriate DLL path in the registry. | Find COM DLL path from Com Interop Assembly | [
"",
"c#",
".net",
"com",
""
] |
Is there a way to persist a variable across a go?
```
Declare @bob as varchar(50);
Set @bob = 'SweetDB';
GO
USE @bob --- see note below
GO
INSERT INTO @bob.[dbo].[ProjectVersion] ([DB_Name], [Script]) VALUES (@bob,'1.2')
```
See this [SO](https://stackoverflow.com/questions/937271/is-there-a-way-to-select-a-database-from-a-variable) question for the 'USE @bob' line. | The `go` command is used to split code into separate batches. If that is exactly what you want to do, then you should use it, but it means that the batches are actually separate, and you can't share variables between them.
In your case the solution is simple; you can just remove the `go` statements, they are not needed in that code.
Side note: You can't use a variable in a `use` statement, it has to be the name of a database. | Use a temporary table:
```
CREATE TABLE #variables
(
VarName VARCHAR(20) PRIMARY KEY,
Value VARCHAR(255)
)
GO
Insert into #variables Select 'Bob', 'SweetDB'
GO
Select Value From #variables Where VarName = 'Bob'
GO
DROP TABLE #variables
go
``` | Is there a way to persist a variable across a go? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2012",
"sql-server-2000",
""
] |
In the recent 10 year when discussing java and/or garbage collection, the only performance penalty that I have not been able to defend is that garbage collection algorithms more or less breaks when running in a paged memory architecture, and parts of the heap is getting paged out.
Unix systems (and especially Linux) agressively pages out memory that has not been touched for a while, and while that is good for your average leaking c application, it kill javas perfomance in memory tight situations.
I know the best practice is to keep the max heap less than the physical memory. (Or you will see your application swap to death) but the idea - at least in the unix world, is that the memory could be better spent for filesystem caches etc.
My question is:
Are there any paging (aware) garbage collecting algorithms? | You are correct, the garbage collector and the virtual memory manager have to collaborate otherwise the GC will trash the system. Such a GC/kernel collaboration has been investigated by Matthew Hertz, Yi Feng and Emery D. Berger. In order to obtain good performance, they had to extend the kernel slightly and also tweak the garbage collector.
Under high memory pressure, their benchmark took something like 160x longer using the GenMS Java GC. With the new, page-aware GC, the benchmark was only 1.6 times slower. In other words, with a properly tuned GC, there is a 100x performance gain.
<http://lambda-the-ultimate.org/node/2391> | I'm going to contend that this is not as big an issue as you think.
To make sure that we're describing the same thing: a complete collection requires the JVM to walk the object graph to identify every reachable object; the ones left over are garbage. While doing so, it will touch every page in the application heap, which will cause every page to be faulted into memory if it's been swapped out.
I think that's a non-concern for several reasons: First, because modern JVMs use generational collectors, and most objects never make their way out of the young generations, which are almost guaranteed to be in the resident set.
Second, because the objects that move out of the young generation still tend to be accessed frequently, which again means they should be in the resident set. This is a more tenuous argument, and there are in fact lots of cases where long-lived objects won't get touched except by the GC (one reason that I don't believe in memory-limited caches).
The third reason (and there may be more) is because the JVM (at least, the Sun JVM) uses a mark-sweep-compact collector. So after GC, the active objects in the heap occupy a smaller number of pages, again increasing the RSS. This, incidentally, is the main driver for Swing apps to explicitly call System.gc() when they're minimized: by compacting the heap, there's less to swap in when they get maximized again.
---
Also, recognize that heap fragmentation of C/C++ objects can get extreme, and young objects will be sprinkled amongst older, so the RSS has to be larger. | JVM garbage collection and a paging memory architecture | [
"",
"java",
"garbage-collection",
""
] |
I've inherited an app that uses Spring. The original developers are not available. The Spring jar file is just "spring.jar", so there's no version# in the filename to help me. I'd like to download the Spring source corresponding to the jar file. The MANIFEST.MF file has "Spring-Version: 1.2" however that's not precise enough. I've looked at version 1.2.1 and 1.2.9 and it doesn't match up quite right. The key thing is that `org.springframework.web.servlet.view.AbstractCachingViewResolver` has a `prepareView` method which is called from `resolveViewName` and it does not seem to be in 1.2.1 or 1.2.9.
Is there any easy way to track down the right version? | This will do it:
```
import org.springframework.core.SpringVersion;
public class VersionChecker
{
public static void main(String [] args)
{
System.out.println("version: " + SpringVersion.getVersion());
}
}
```
Compile and run this with spring.jar in your CLASSPATH and it'll display the version for you. See the [javadocs](http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/core/SpringVersion.html) as well. | If your project uses Maven, you can run the following at the command line to see it:
```
$ mvn dependency:tree | grep org.springframework | grep 'spring-core:jar'
``` | Need Spring version# - only have spring.jar file | [
"",
"java",
"spring",
""
] |
Paramiko's [SFTPClient](http://www.metasnark.com/paramiko/docs/paramiko.SFTP-class.html) apparently does not have an `exists` method. This is my current implementation:
```
def rexists(sftp, path):
"""os.path.exists for paramiko's SCP object
"""
try:
sftp.stat(path)
except IOError, e:
if 'No such file' in str(e):
return False
raise
else:
return True
```
Is there a better way to do this? Checking for substring in Exception messages is pretty ugly and can be unreliable. | See the [`errno` module](http://docs.python.org/library/errno.html#errno.ENOENT) for constants defining all those error codes. Also, it's a bit clearer to use the `errno` attribute of the exception than the expansion of the `__init__` args, so I'd do this:
```
except IOError, e: # or "as" if you're using Python 3.0
if e.errno == errno.ENOENT:
...
``` | Paramiko literally raises `FileNotFoundError`
```
def sftp_exists(sftp, path):
try:
sftp.stat(path)
return True
except FileNotFoundError:
return False
``` | Check whether a path exists on a remote host using paramiko | [
"",
"python",
"ssh",
"scp",
"paramiko",
""
] |
i have two classes which have some common methods like
funcA(), funcB()
and some methods are only related to its class...
what i did is made interface of TestInterface
```
public interface TestInterface
{
void funcA()
void funcB()
}
public class ClassA : TestInterface
{
public void funcA()
{
Console.WriteLine("This is ClassA FuncA()");
}
public void funcB()
{
Console.WriteLine("This is ClassA FuncB()");
}
public void myFuncA()
{
Console.WriteLine("This is My Own Function A");
}
}
public class ClassB : TestInterface
{
public void funcA()
{
Console.WriteLine("This is ClassB FuncA()");
}
public void funcB()
{
Console.WriteLine("This is ClassB FuncB()");
}
public void myFuncB()
{
Console.WriteLine("This is My Own Function B");
}
}
public static void main()
{
TestInterface test = new ClassA();
test.funcA();
}
```
as u see in above two classes. i have two functions myFuncA() and myFuncB() are not part of interface. they only belongs to their own class.
how can i call them from the main method. where i am creating object of TestInterface and initializing it with some child class.???
---
actually i have separate classes in DAL.
they have some common methods. and some methods related to their own class.
i want to implement Factory Pattern on this.
what should i do now? | ```
is it good to add methods of ClassA and ClassB into interface and provide null implementation in other class?
like
public interface TestInterface
{
void funcA();
void funcB();
void myFuncA();
void myFuncB();
}
public class ClassA:TestInterface
{
public void funcA()
{
// some code here
}
public void funcB()
{
// some code here
}
public void myFuncA()
{
// my own code here
}
public void funcB()
{
// null implementation
}
}
```
and vise versa of this in ClassB | If you're asking whether you can do something like:
```
public static void Main(string[] a)
{
TestInterface test = new ClassA();
test.myFuncA();
}
```
the answer is no. You would have to cast it to ClassA first. The fact that you think you need to do this indicates there is probably something wrong with your design. | Problem in Interfaces (polymorphism) C# | [
"",
"c#",
"interface",
"polymorphism",
""
] |
Frequently, I just want to drop a bit of jQuery on an individual page. Given my early understanding of Sitefinity, I think...
1. I can't easily put JS in the <head>.
2. I could put JS in a Generic Content control, but then my JS is sitting inline in the <body>. Maybe I need to relax, but I don't usually like to put much JS in the <body>.
It feels like this kind of scenario is an afterthought. Is JS a 2nd-class citizen in Sitefinity? | JavaScript does not live in the head. Yahoo even [says](http://developer.yahoo.net/blog/archives/2007/07/high_performanc_5.html) it is better for performance | I agree with epascarello you really shouldn't be putting your javascript in the head anyway.
And just in case you didn't know about this the [jQuery framework is part of Sitefinity](http://blogs.sitefinity.com/GeorgiChokov/Posts/09-03-25/How_to_use_jQuery_and_other_JavaScript_Libraries_in_Sitefinity.aspx). The article also shows you how you can include external libraries in sitefinity from anywhere withing your project whether it be master page or user control. | Best approach for including bits of Javascript on individual pages in Sitefinity | [
"",
"javascript",
"sitefinity",
""
] |
I've designed an application that uses the repository pattern, and then a separate service layer such as this:
```
public class RegistrationService: IRegistrationService
{
public void Register(User user)
{
IRepository<User> userRepository = new UserRepository();
// add user, etc
}
}
```
As you can see, I am instantiating my repository inside of the Register method. Now as I want to write some unit tests, I can't really get to it and replace it with a fake repository can I?
I don't want to add the repository as class variable though (and set it through a constructor) because I think that would make my code "smelly" (not all repositories are needed for all methods, and I don't need the calling layer to know about repositories etc.).
Suggestions? | You need to use Dependency Injection. UserRepository is a dependency of your RegistrationService class. To make your classes properly unit testable (i.e. in isolation of their dependencies), you need to "invert" what controls your dependency creation. Currently, you have direct control, and are creating them internally. Just invert that control, and allow something external (such as an IoC container like Castle Windsor) inject them:
```
public class RegistrationService: IRegistrationService
{
public RegistrationService(IRepository<User> userRepo)
{
m_userRepo = userRepo;
}
private IRepository<User> m_userRepo;
public void Register(User user)
{
// add user, etc with m_userRepo
}
}
```
I think I forgot to add. Once you allow your dependencies to be injected, you open up the possability of them being mockable. Since your RegistrationService now takes its dependent user repository as input to its constructor, you can create a mock repository and pass that in, instead of an actual repository. | Dependency Injection can come in really handy for these kinds of things:
```
public class RegistrationService: IRegistrationService
{
public void Register(User user)
{
this(user, new UserRepository());
}
public void Register(User user, IRepository<User> userRepository)
{
// add user, etc
}
}
```
This way you get the ability to use UserRepository as your default, and pass in a custom (Mock or Stub for testing) IRepository for whatever else you need. You may also want to change the scoping of the 2nd register method in case you don't want to expose it to everything.
An even better alternative would be to use an IoC container which would buy you syntax that is even more decoupled than the above example. You could get something like this:
```
public class RegistrationService: IRegistrationService
{
public void Register(User user)
{
this(user, IoC.Resolve<IRepository<User>>());
}
public void Register(User user, IRepository<User> userRepository)
{
// add user, etc
}
}
```
There are many IoC containers out there, as listed by other people's answers, or you could [roll your own](http://www.dnrtv.com/default.aspx?showNum=126). | TDD - Want to test my Service Layer with a fake Repository, but how? | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"repository-pattern",
""
] |
I'm using Mysql and I was assuming it was better to separate out a users personal information and their login and password into two different tables and then just reference them between the two.
**Note** : To clarify my post, I understand the techniques of securing the password (hash, salt, etc). I just know that if I'm following practices from other parts of my life (investing, data backup, even personal storage) that in the worst case scenario (comprised table or fire) that having information split among tables provides the potential to protect your additional data. | Don't store passwords. If it's ever sitting on a disk, it can be stolen. Instead, store password hashes. [Use the right hashing algorithm](https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords), like bcrypt (which includes a salt).
**EDIT**: The OP has responded that he understands the above issue.
There's no need to store the password in a physically different table from the login. If one database table is compromised, it's not a large leap to access another table in that same database.
If you're sufficiently concerned about security and security-in-depth, you might consider storing the user credentials in a completely separate data store from your domain data. One approach, commonly done, is to store credentials in an LDAP directory server. This might also help with any single-sign-on work you do later. | The passwords should be stored as a cryptographic hash, which is a non-reversible operation that prevents reading the plain text. When authenticating users, the password input is subjected to the same hashing process and the hashes compared.
Avoid the use of a fast and cheap hash such as MD5 or SHA1; the objective is to make it expensive for an attacker to compute rainbow tables (based on hash collisions); a fast hash counteracts this. Use of an expensive hash is not a problem for authentication scenarios, since it will have no effect on a single run of the hash.
In addition to hashing, salt the hash with a randomly generated value; a nonce, which is then stored in the database and concatenated with the data prior to hashing. This increases the number of possible combinations which have to be generated when computing collisions, and thus increases the overall time complexity of generating rainbow tables.
Your password hash column can be a fixed length; your cryptographic hash should output values which can be encoded into a fixed length, which will be the same for all hashes.
Wherever possible, avoid rolling your own password authentication mechanism; use an existing solution, such as `bcrypt`.
An excellent explanation of how to handle passwords, and what you need to concern yourself with, can be found at [http://www.matasano.com/log/958/enough-with-the-rainbow-tables-what-you-need-to-know-about-secure-password-schemes](http://www.matasano.com/log/958/enough-with-the-rainbow-tables-what-you-need-to-know-about-secure-password-schemes/).
As a final note, please remember that if an attacker obtains access to your database, then your immediate concern should probably be with any sensitive or personally-identifying information they may have access to, and any damage they may have done. | How to best store user information and user login and password | [
"",
"php",
"mysql",
"security",
"passwords",
""
] |
How do I convert a `long` to a `string` in C++? | You could use stringstream.
```
#include <sstream>
// ...
std::string number;
std::stringstream strstream;
strstream << 1L;
strstream >> number;
```
There is usually some proprietary C functions in the standard library for your compiler that does it too. I prefer the more "portable" variants though.
The C way to do it would be with sprintf, but that is not very secure. In some libraries there is new versions like sprintf\_s which protects against buffer overruns. | In C++11, there are actually [std::to\_string](https://en.cppreference.com/w/cpp/string/basic_string/to_string) and [std::to\_wstring](https://en.cppreference.com/w/cpp/string/basic_string/to_wstring) functions in <string>.
```
string to_string(int val);
string to_string(long val);
string to_string(long long val);
string to_string(unsigned val);
string to_string(unsigned long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string (long double val);
``` | How do I convert a long to a string in C++? | [
"",
"c++",
""
] |
I am designing a project where all the main components share a single common DomainObject (yeah I stole the term from O/RM world, but its not *quite* an O/RM project.) The DomainObject maintains the objects change state (dirty/clean) and allows itself to be rolled back or committed (AcceptChanges(), RejectChanges() ). When AcceptChanges() is called on an object, it fires an event and that event would trigger the writing of hte values to the underlying datastore. Also, it passes a parameter allowing the persistance to be cancelled in the event.
> 1) Classroom (a DomainObject) is instantiated and its properties modified.
> 2) Classroom.AcceptChanges() is called, triggering the OnAcceptEvent and passing the DomainObjectChangeEventArgs, which contain a boolean property called Cancel
> 3) If Not Cancelled by the event, changes are accepted and the state of hte Classroom is updated.
> 4) The project then calls AcceptChanges on any internal properties that are also DomainObjects, such as Student.
> 5) Each Student triggers the OnAcceptEvent passing a DomainObjectChangeEventArgs...etc.
Now, asking the community at large:
A) Would you have the cancel indicator on the Classroom's AcceptEvent stop the entire process forcing it to no longer evaluate and possibly Accept any Students, or would you code the Cancel to just apply to the classroom.
b) Would the Cancel indicator on any Student be expected to stop the processing on any additional Students?
My initial thought is that the cancel indicator on the Classroom's event should stop the entire process, therefore allowing a graceful preservation of the pre-accepted state of the classroom and all the students without involving the overhead of a transaction. But I am not necessarilly convinced that I am correct.
What would you do? | I'd call the event CanSave, which returns an enum { OK, Cancel }. Prior to persisting anything I'd query the whole object graph, looking for a cancel. Each object can validate itself and cancel if it's not currently in a *persistable* state... averting most, but by no means all, rollbacks.
But what can you do with a Cancel? One of the prime edicts of good software is "**Allways** allow the user to save there work". Programmers wouldn't abide an IDE which won't save uncompilable source-code, so why would you expect your users to put-up with it?
Cancel states **should** be truly exceptional states... like can't write to readonly file --> "Save As" instead? Or a null key-field --> "username is required".
So what's the alternative? Save to an intermediate format, one which can store "invalid" data... like a text file.
Aside: I've often thought that database-apps are missing a "validate" button, allowing the user to find out "is this OK?" without actually committing to it.
Just food for thought.
Cheers. Keith. | I think you are on the money. | C# Architecture Question | [
"",
"c#",
"architecture",
""
] |
I have a class with this constructor:
```
Artikel(String name, double preis){
this.name = name;
verkaufspreis = preis;
Art = Warengruppe.S;
```
I have a second class with this constructor:
```
Warenkorb(String kunde, Artikel[] artikel){
this.kunde = kunde;
artikelliste = artikel;
sessionid = s.nextInt();
summe = 0;
for(Artikel preis : artikel){
summe += preis.verkaufspreis;
}
}
```
How do i get an Artikel into the Warenkorb and the artikelliste array? | ```
new Warenkorb("Dieter", new Artikel[] {new Artikel("Kartoffel", 0.25))};
```
Is this what you are trying to do? | And, looks like you're using Java 1.5+ anyway, try this alternative for Warenkorb:
```
Warenkorb(String kunde, Artikel...artikel){
this.kunde = kunde;
artikelliste = artikel;
sessionid = s.nextInt();
summe = 0;
for(Artikel preis : artikel){
summe += preis.verkaufspreis;
}
}
```
Written like this, you can get rid of the ugly Array notation and construct a Warenkorb like this:
```
new Warenkorb("Dieter", new Artikel("Kartoffel", 0.25)};
new Warenkorb("Günther", new Artikel("Kartoffel", 0.25), new Artikel("Tomate", 0.25)};
``` | Constructor parameter is an array of objects | [
"",
"java",
"arrays",
"constructor",
""
] |
I store all of my images behind the webroot (before `/var/www/`), which means that the web server is unable to send cache headers back for my pictures. What do I need to add to this to make the user's web cache work? Currently, this is getting hit every time by the same browser.
My `<img>` path on my pages look something like this:
```
<img src="pic.php?u=1134&i=13513&s=0">
```
**Edit:** Could it be that it is because "`pic.php?u=1134&i=13513&s=0`" is not a valid file name or something?
```
// pic.php
<?php
// open the file in a binary mode
$user = $_GET['u'];
$id = $_GET['i'];
$s = $_GET['s'];
if (!isset($user) && !isset($s) && $isset($id))
{
// display a lock!
exit(0);
}
require_once("bootstrap_minimal.php"); //setup db connection, etc
// does this image_id belong to the user?
$stmt = $db->query('SELECT image_id, user_id, file_name, private FROM images WHERE image_id = ?', $id);
$obj = $stmt->fetchObject();
if (is_object($obj))
{
// is the picture is the users?
if ($obj->user_id != $_SESSION['user_id'])
{
// is this a private picture?
if ($obj->private == 1)
{
// check permissions...
// display a lock in needed!
}
}
}
else
{
// display a error pic?!
exit(0);
}
if ($s == 0)
{
$picture = $common->getImagePathThumb($obj->file_name);
}
else
{
$picture = $common->getImagePath($obj->file_name);
}
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($picture));
$fp = fopen($picture, 'rb');
// dump the picture and stop the script
fpassthru($fp);
exit;
?>
``` | You need to add something like:
```
$expiry = 3600*24*7; // A week
header('Expires: ' . gmdate('D, d M Y H:i:s' time() + $expiry) . ' GMT');
header('Cache-control: private, max-age=' . $expiry);
``` | Apache only caches static files by default. You need to send a cache control header via the `header()` function. [This article](http://www.mnot.net/cache_docs/#IMP-SCRIPT) has a lot of information on the topic.
Alternatively, you could use the PHP file to redirect to the actual location of the image. (This is probably the easiest way if you don't know anything about headers.) | Why do images served from my web server not cache on the client? | [
"",
"php",
"apache",
"caching",
""
] |
I'm trying to create an application which scans a drive. The tricky part though, is that my drive contains a set of folders that have folders within folders and contain documents. I'm trying to scan the drive, take a "snapshot" of all documents & folders and dump into a .txt file.
The first time i run this app, the output will be a text file with all the folders & files.
The second time i run this application, it will take the 2 text files (the one produced from the 2nd time i run the app and the .txt file from the 1st time i have run the app) and compare them...reporting what has been moved/overridden/deleted.
Does anybody have any code for this? I'm a newbie at this C# stuff and any help would be greatly appreciated.
Thanks in advance. | One thing that we learned in the 80's was that if it's really tempting to use recursion for file system walking, but the moment you do that, someone will make a file system with nesting levels that will cause your stack to overflow. It's far better to use heap-based walking of the file system.
Here is a class I knocked together which does just that. It's not super pretty, but it does the job quite well:
```
using System;
using System.IO;
using System.Collections.Generic;
namespace DirectoryWalker
{
public class DirectoryWalker : IEnumerable<string>
{
private string _seedPath;
Func<string, bool> _directoryFilter, _fileFilter;
public DirectoryWalker(string seedPath) : this(seedPath, null, null)
{
}
public DirectoryWalker(string seedPath, Func<string, bool> directoryFilter, Func<string, bool> fileFilter)
{
if (seedPath == null)
throw new ArgumentNullException(seedPath);
_seedPath = seedPath;
_directoryFilter = directoryFilter;
_fileFilter = fileFilter;
}
public IEnumerator<string> GetEnumerator()
{
Queue<string> directories = new Queue<string>();
directories.Enqueue(_seedPath);
Queue<string> files = new Queue<string>();
while (files.Count > 0 || directories.Count > 0)
{
if (files.Count > 0)
{
yield return files.Dequeue();
}
if (directories.Count > 0)
{
string dir = directories.Dequeue();
string[] newDirectories = Directory.GetDirectories(dir);
string[] newFiles = Directory.GetFiles(dir);
foreach (string path in newDirectories)
{
if (_directoryFilter == null || _directoryFilter(path))
directories.Enqueue(path);
}
foreach (string path in newFiles)
{
if (_fileFilter == null || _fileFilter(path))
files.Enqueue(path);
}
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
```
Typical usage is this:
```
DirectoryWalker walker = new DirectoryWalker(@"C:\pathToSource\src", null, (x => x.EndsWith(".cs")));
foreach (string s in walker)
{
Console.WriteLine(s);
}
```
Which recursively lists all files that end in ".cs" | A better approach than your text file comparisons would be to use the [FileSystemWatcher Class](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx).
> Listens to the file system change notifications and raises events when a directory, or file in a directory, changes.
You could log the changes and then generate your reports as needed from that log. | Scanning a drive with drilldowns using C#? | [
"",
"c#",
"file",
"comparison",
""
] |
Does anybody know of a open source Java library that will do robust diffing of the text parts of pdf files?
Ideally I would like something that would produce a diff in the form of a patch. | Extract the pdf text with <http://incubator.apache.org/pdfbox/> and create a diff with <http://code.google.com/p/google-diff-match-patch>. | If the PDFs are different only in text, you could also rasterize the pages and then look at the differences that way - we use that for regression testing output on our PDF code. | Java Pdf Diff library | [
"",
"java",
"pdf",
"diff",
""
] |
I am implementing a Fuzzy Date control in C# for a winforms application. The Fuzzy Date should be able to take fuzzy values like
* Last June
* 2 Hours ago
* 2 Months ago
* Last week
* Yesterday
* Last year
and the like
Are there any sample implementations of "Fuzzy" Date Time Pickers?
Any ideas to implement such a control would be appreciated
**PS**:
I am aware of the fuzzy date algorithm spoken about [here](https://stackoverflow.com/questions/822124/fuzzy-date-algorithm) and [here](https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time), I am really looking for any ideas and inspirations for developing such a control | The parsing is quite easy. It can be implemented as bunch of regexps and some date calculations.
The sample below can be easily extended to suit your needs.
I've roughly tested it and it works at least for the following strings:
* next month, next year,
* next 4 months, next 3 days
* 3 days ago, 5 hours ago
* tomorrow, yesterday
* last year, last month,
* last tue, next fri
* last june, next may,
* jan 2008, 01 january 2009,
* june 2019, 2009/01/01
The helper class:
```
class FuzzyDateTime
{
static List<string> dayList = new List<string>() { "sun", "mon", "tue", "wed", "thu", "fri", "sat" };
static List<IDateTimePattern> parsers = new List<IDateTimePattern>()
{
new RegexDateTimePattern (
@"next +([2-9]\d*) +months",
delegate (Match m) {
var val = int.Parse(m.Groups[1].Value);
return DateTime.Now.AddMonths(val);
}
),
new RegexDateTimePattern (
@"next +month",
delegate (Match m) {
return DateTime.Now.AddMonths(1);
}
),
new RegexDateTimePattern (
@"next +([2-9]\d*) +days",
delegate (Match m) {
var val = int.Parse(m.Groups[1].Value);
return DateTime.Now.AddDays(val);
}
),
new RegexDateTimePattern (
@"([2-9]\d*) +months +ago",
delegate (Match m) {
var val = int.Parse(m.Groups[1].Value);
return DateTime.Now.AddMonths(-val);
}
),
new RegexDateTimePattern (
@"([2-9]\d*) days +ago",
delegate (Match m) {
var val = int.Parse(m.Groups[1].Value);
return DateTime.Now.AddDays(-val);
}
),
new RegexDateTimePattern (
@"([2-9]\d*) *h(ours)? +ago",
delegate (Match m) {
var val = int.Parse(m.Groups[1].Value);
return DateTime.Now.AddMonths(-val);
}
),
new RegexDateTimePattern (
@"tomorrow",
delegate (Match m) {
return DateTime.Now.AddDays(1);
}
),
new RegexDateTimePattern (
@"today",
delegate (Match m) {
return DateTime.Now;
}
),
new RegexDateTimePattern (
@"yesterday",
delegate (Match m) {
return DateTime.Now.AddDays(-1);
}
),
new RegexDateTimePattern (
@"(last|next) *(year|month)",
delegate (Match m) {
int direction = (m.Groups[1].Value == "last")? -1 :1;
switch(m.Groups[2].Value)
{
case "year":
return new DateTime(DateTime.Now.Year+direction, 1,1);
case "month":
return new DateTime(DateTime.Now.Year, DateTime.Now.Month+direction, 1);
}
return DateTime.MinValue;
}
),
new RegexDateTimePattern (
String.Format(@"(last|next) *({0}).*", String.Join("|", dayList.ToArray())), //handle weekdays
delegate (Match m) {
var val = m.Groups[2].Value;
var direction = (m.Groups[1].Value == "last")? -1 :1;
var dayOfWeek = dayList.IndexOf(val.Substring(0,3));
if (dayOfWeek >= 0) {
var diff = direction*(dayOfWeek - (int)DateTime.Today.DayOfWeek);
if (diff <= 0 ) {
diff = 7 + diff;
}
return DateTime.Today.AddDays(direction * diff);
}
return DateTime.MinValue;
}
),
new RegexDateTimePattern (
@"(last|next) *(.+)", // to parse months using DateTime.TryParse
delegate (Match m) {
DateTime dt;
int direction = (m.Groups[1].Value == "last")? -1 :1;
var s = String.Format("{0} {1}",m.Groups[2].Value, DateTime.Now.Year + direction);
if (DateTime.TryParse(s, out dt)) {
return dt;
} else {
return DateTime.MinValue;
}
}
),
new RegexDateTimePattern (
@".*", //as final resort parse using DateTime.TryParse
delegate (Match m) {
DateTime dt;
var s = m.Groups[0].Value;
if (DateTime.TryParse(s, out dt)) {
return dt;
} else {
return DateTime.MinValue;
}
}
),
};
public static DateTime Parse(string text)
{
text = text.Trim().ToLower();
var dt = DateTime.Now;
foreach (var parser in parsers)
{
dt = parser.Parse(text);
if (dt != DateTime.MinValue)
break;
}
return dt;
}
}
interface IDateTimePattern
{
DateTime Parse(string text);
}
class RegexDateTimePattern : IDateTimePattern
{
public delegate DateTime Interpreter(Match m);
protected Regex regEx;
protected Interpreter inter;
public RegexDateTimePattern(string re, Interpreter inter)
{
this.regEx = new Regex(re);
this.inter = inter;
}
public DateTime Parse(string text)
{
var m = regEx.Match(text);
if (m.Success)
{
return inter(m);
}
return DateTime.MinValue;
}
}
```
Usage example:
```
var val = FuzzyDateTime.Parse(textBox1.Text);
if (val != DateTime.MinValue)
label1.Text = val.ToString();
else
label1.Text = "unknown value";
``` | One of the systems our users use allows them to enter dates like so:
* T // Today
* T + 1 // Today plus/minus a number of days
* T + 1w // Today plus/minus a number of weeks
* T + 1m // Today plus/minus a number of months
* T + 1y // Today plus/minus a number of years
They seem to like it, and requested it in our app, so I came up with the following code. ParseDateToString will take a string of one of the forms above, plus a few others, calculate the date, and return it in "MM/DD/YYYY" format. It's easy enough to change it to return the actual DateTime object, as well as to add support for hours, minutes, seconds, or whatever you want.
```
using System;
using System.Text.RegularExpressions;
namespace Utils
{
class DateParser
{
private static readonly DateTime sqlMinDate = DateTime.Parse("01/01/1753");
private static readonly DateTime sqlMaxDate = DateTime.Parse("12/31/9999");
private static readonly Regex todayPlusOrMinus = new Regex(@"^\s*t(\s*[\-\+]\s*\d{1,4}([dwmy])?)?\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase); // T +/- number of days
private static readonly Regex dateWithoutSlashies = new Regex(@"^\s*(\d{6}|\d{8})\s*$", RegexOptions.Compiled); // Date in MMDDYY or MMDDYYYY format
private const string DATE_FORMAT = "MM/dd/yyyy";
private const string ERROR_INVALID_SQL_DATE_FORMAT = "Date must be between {0} and {1}!";
private const string ERROR_DATE_ABOVE_MAX_FORMAT = "Date must be on or before {0}!";
private const string ERROR_USAGE = @"Unable to determine date! Please enter a valid date as either:
MMDDYY
MMDDYYYY
MM/DD/YY
MM/DD/YYYY
You may also use the following:
T (Today's date)
T + 1 (Today plus/minus a number of days)
T + 1w (Today plus/minus a number of weeks)
T + 1m (Today plus/minus a number of months)
T + 1y (Today plus/minus a number of years)";
public static DateTime SqlMinDate
{
get { return sqlMinDate; }
}
public static DateTime SqlMaxDate
{
get { return sqlMaxDate; }
}
/// <summary>
/// Determine if user input string can become a valid date, and if so, returns it as a short date (MM/dd/yyyy) string.
/// </summary>
/// <param name="dateString"></param>
/// <returns></returns>
public static string ParseDateToString(string dateString)
{
return ParseDateToString(dateString, sqlMaxDate);
}
/// <summary>
/// Determine if user input string can become a valid date, and if so, returns it as a short date (MM/dd/yyyy) string. Date must be on or before maxDate.
/// </summary>
/// <param name="dateString"></param>
/// <param name="maxDate"></param>
/// <returns></returns>
public static string ParseDateToString(string dateString, DateTime maxDate)
{
if (null == dateString || 0 == dateString.Trim().Length)
{
return null;
}
dateString = dateString.ToLower();
DateTime dateToReturn;
if (todayPlusOrMinus.IsMatch(dateString))
{
dateToReturn = DateTime.Today;
int amountToAdd;
string unitsToAdd;
GetAmountAndUnitsToModifyDate(dateString, out amountToAdd, out unitsToAdd);
switch (unitsToAdd)
{
case "y":
{
dateToReturn = dateToReturn.AddYears(amountToAdd);
break;
}
case "m":
{
dateToReturn = dateToReturn.AddMonths(amountToAdd);
break;
}
case "w":
{
dateToReturn = dateToReturn.AddDays(7 * amountToAdd);
break;
}
default:
{
dateToReturn = dateToReturn.AddDays(amountToAdd);
break;
}
}
}
else
{
if (dateWithoutSlashies.IsMatch(dateString))
{
/*
* It was too hard to deal with 3, 4, 5, and 7 digit date strings without slashes,
* so I limited it to 6 (MMDDYY) or 8 (MMDDYYYY) to avoid ambiguity.
* For example, 12101 could be:
* 1/21/01 => Jan 21, 2001
* 12/1/01 => Dec 01, 2001
* 12/10/1 => Dec 10, 2001
*
* Limiting it to 6 or 8 digits is much easier to deal with. Boo hoo if they have to
* enter leading zeroes.
*/
// All should parse without problems, since we ensured it was a string of digits
dateString = dateString.Insert(4, "/").Insert(2, "/");
}
try
{
dateToReturn = DateTime.Parse(dateString);
}
catch
{
throw new FormatException(ERROR_USAGE);
}
}
if (IsDateSQLValid(dateToReturn))
{
if (dateToReturn <= maxDate)
{
return dateToReturn.ToString(DATE_FORMAT);
}
throw new ApplicationException(string.Format(ERROR_DATE_ABOVE_MAX_FORMAT, maxDate.ToString(DATE_FORMAT)));
}
throw new ApplicationException(String.Format(ERROR_INVALID_SQL_DATE_FORMAT, SqlMinDate.ToString(DATE_FORMAT), SqlMaxDate.ToString(DATE_FORMAT)));
}
/// <summary>
/// Converts a string of the form:
///
/// "T [+-] \d{1,4}[dwmy]" (spaces optional, case insensitive)
///
/// to a number of days/weeks/months/years to add/subtract from the current date.
/// </summary>
/// <param name="dateString"></param>
/// <param name="amountToAdd"></param>
/// <param name="unitsToAdd"></param>
private static void GetAmountAndUnitsToModifyDate(string dateString, out int amountToAdd, out string unitsToAdd)
{
GroupCollection groups = todayPlusOrMinus.Match(dateString).Groups;
amountToAdd = 0;
unitsToAdd = "d";
string amountWithPossibleUnits = groups[1].Value;
string possibleUnits = groups[2].Value;
if (null == amountWithPossibleUnits ||
0 == amountWithPossibleUnits.Trim().Length)
{
return;
}
// Strip out the whitespace
string stripped = Regex.Replace(amountWithPossibleUnits, @"\s", "");
if (null == possibleUnits ||
0 == possibleUnits.Trim().Length)
{
amountToAdd = Int32.Parse(stripped);
return;
}
// Should have a parseable integer followed by a units indicator (d/w/m/y)
// Remove the units indicator from the end, so we have a parseable integer.
stripped = stripped.Remove(stripped.LastIndexOf(possibleUnits));
amountToAdd = Int32.Parse(stripped);
unitsToAdd = possibleUnits;
}
public static bool IsDateSQLValid(string dt) { return IsDateSQLValid(DateTime.Parse(dt)); }
/// <summary>
/// Make sure the range of dates is valid for SQL Server
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static bool IsDateSQLValid(DateTime dt)
{
return (dt >= SqlMinDate && dt <= SqlMaxDate);
}
}
}
```
The only example in your list that might be difficult would be "Last June", but you could just calculate the string to pass in by figuring out how many months it's been since last June.
```
int monthDiff = (DateTime.Now.Month + 6) % 12;
if(monthDiff == 0) monthDiff = 12;
string lastJuneCode = string.Format("T - {0}m", monthDiff);
```
Of course, that'll depend on the accuracy of DateTime's AddMonths function, and I haven't really tested edge cases for that. It should give you a DateTime last June, and you could just use that to find the first and last of the month.
Everything else should be fairly easy to map or parse with regular expressions. For example:
* Last week => "t - 1w"
* Yesterday => "t - 1d"
* Last year => "t - 1y"
* Next week => "t + 1w"
* Tomorrow => "t + 1d"
* Next year => "t + 1y" | Fuzzy Date Time Picker Control in C# .NET? | [
"",
"c#",
"winforms",
"datetime",
"user-controls",
"fuzzy",
""
] |
Is it possible to list all the applications on a machine that can open a specific file type, using only the files extension? for example if I have a text file (.txt), I want a list of all applications that can open .txt files. | Check out the `HKEY_CLASSES_ROOT` hive in your registry. It's all in there. | There is no master list of every application that can open a specific file that I am aware of. | List all applications that handle a specified file type | [
"",
"c#",
"windows",
"associations",
"file-type",
""
] |
I'm writing a method to lift certain data out of an SQL query string, and I need to regex match any word inside of curly braces ONLY when it appears *outside* of single-quotes. I also need it to factor in the possibility of escaped (preceded by backslash) quotes, as well as escaped backslashes.
In the following examples, I need the regex to match {FOO} and not {BAR}:
```
blah blah {FOO} blah 'I\'m typing {BAR} here with an escaped backslash \\'
blah blah {FOO} 'Three backslashes {BAR} and an escaped quote \\\\\\\' here {BAR}'
```
I'm using preg\_match in PHP to get the word in the braces ("FOO", in this case). Here's the regex string I have so far:
```
$regex = '/' .
// Match the word in braces
'\{(\w+)\}' .
// Only if it is followed by an even number of single-quotes
'(?=(?:[^\']*\'[^\']*\')*[^\']*$)' .
// The end
'/';
```
My logic is that, since the only thing I'm parsing is a legal SQL string (besides the brace-thing I added), if a set of braces is followed by an *even* number of non-escaped quotes, then it must be outside of quotes.
The regex I provided is 100% successful EXCEPT for taking escaped quotes into consideration. I just need to make sure there is no odd number of backslashes before a quote match, but for the life of me I can't seem to convey this in RegEx. Any takers? | The way to deal with escaped quotes and backslashes is to consume them in matched pairs.
```
(?=(?:(?:(?:[^\'\\]++|\\.)*+\'){2})*+(?:[^\'\\]++|\\.)*+$)
```
In other words, as you scan for the next quote, you skip any pair of characters that starts with a backslash. That takes care of both escaped quotes and escaped backslashes. This lookahead will allow escaped characters outside of quoted sections, which probably isn't necessary, but it probably won't hurt either.
p.s., Notice the liberal use of possessive quantifiers (`*+` and `++`); without those you could have performance problems, especially if the target strings are large. Also, if the strings can contain line breaks, you may need to do the matching in DOTALL mode (aka, "singleline" or "/s" mode).
However, I agree with mmyers: if you're trying to parse SQL, you *will* run into problems that regexes can't handle at all. Of all the things that regexes are bad at, SQL is one of the worst. | Simply, and perhaps naively, str\_replace out all your double backslashes. Then str\_replace out escaped single quotes. At that point it's relatively simple to find matches that are not between single quotes (using your existing regex, for example). | RegEx in PHP: Matching a pattern outside of non-escaped quotes | [
"",
"php",
"regex",
""
] |
I need to use `Server.MapPath()` to combine some files path that I store in the `web.config`.
However, since `Server.MapPath()` relies on the current HttpContext (I think), I am unable to do this. When trying to use the method, even though its "available", I get the following exception:
> Server operation is not available in this context.
Is there another method that can map a web root relative directory such as `~/App_Data/` to the full physical path such as `C:\inetpub\wwwroot\project\App_data\` ? | You could try [System.Web.Hosting.HostingEnvironment.MapPath()](http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath.aspx).
No HttpContext required. | Use `AppDomain.CurrentDomain.BaseDirectory` because `Context` might return null !! | How can I use Server.MapPath() from global.asax? | [
"",
"c#",
"asp.net",
"global-asax",
"server.mappath",
"application-start",
""
] |
I have a need to pass a custom object to a remote web service. I have read that it may be necessary to implement ISerializable, but I've done that and I'm encountering difficulties. What is the proper way in C# to pass a custom object to a web service method? | The objects you provide as arguments as part of the service request must be marked with [Serializable] and based on some of the answers posted before mine you also need to make sure your custom object does not contain any parameters in the constructor.
Also keep in mind any logic you have inside your class will not get created in the proxy class that gets created on the client side. All you will see on the client side is a default constructor and properties. So if you add methods to your custom objects keep in mind that the client will not see them or be able to use them.
Same thing goes for any logic you might put into any of the properties.
Example
```
[Serializable]
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
``` | Looks like a duplicate to this [question](https://stackoverflow.com/questions/347047/passing-a-custom-object-to-the-web-service)
Anyway, all objects involved in WS interactions should be XML-serializable, not ISerializable (which is binary serialization). Moreover, they should be described in the service contract (WSDL), otherwise clients won't be able to consume them. [This article](http://msdn.microsoft.com/en-us/library/564k8ys4(VS.85).aspx) should be useful to understand XML-serialization with XML Web Services.
However, if you are talking about **really custom** objects (i.e. any type). You should consider passing them in binary form: either as base64-encoded, or as attachments. The question I linked to has an answer how to do that. | Passing custom objects to a web service | [
"",
"c#",
".net",
"web-services",
""
] |
I would like to programmaticaly determine the DPI of a user's display in order to show a web page at a precise number of units (centimeters/inches). I know it a weird request: it's for a visualization research project and it's kind of a control. We currently do it by having the user place a credit card to the screen and match a resizable div (via Mootools) to the real credit card, and voila we can get the DPI and display the page correctly.
Can anyone think of a programmatic way to do this? | If you're doing this in javascript/mootools, [CSS units](http://www.w3schools.com/cssref/css_units.asp) are your friend. You can specify sizes in inches or centimeters, or even points (1/72 of an inch). If you absolutely need DPI for whatever reason even though you can specify sizes in those units, simply size the "resizable" div you are using to a known size and calculate from the translated pixel size.
**Edit:**
> *Unfortunately, the CSS units of
> points, cm, and in are not physically
> correct. They are only relatively
> correct. This was the first thing I
> tried until I realized it wasn't
> working and checked the CSS spec.. to
> my dismay.* – **Brandon Pelfrey**
That's a good point; browsers tend to fake it by assuming a default DPI (I think 72 or 96) and going with that.
Well, if you need precision sizing like you're asking for, you're out of luck. You'll never be able to get it without being able to read both the current resolution of the monitor the browser is on and the "viewable screen area" of that monitor. Ain't no way you're gonna get that via Javascript.
I suggest that you make the default assumption that browsers do and size according to the CSS units. You can then allow your users to "adjust the sizing" using the method you mentioned, but *only if it's necessary*. Do this with on a separate page with the DPI calculation stored as part of the users session or as a cookie.
Alternatively, once Microsoft fixes [this bug](https://stackoverflow.com/questions/479758/silverlight-device-independent-coordinates), you could use Silverlight's "device independent units" for accurate scaling. | You can't. DPI is a function of the pixel resolution of the screen and the physical dimensions of the display. The latter is not available in any browser interface I am aware of. | Programmatically determine DPI via the browser? | [
"",
"javascript",
"mootools",
"dpi",
""
] |
I have what I thought was a simple select with jQuery to change some text on a paragraph. It works perfect the traditional way i.e.
```
document.getElementById('message_text').innerHTML = "hello";
```
But with jQuery it doesn't. I have checked the values of `$('#message_text')` and sure enough I see the items.
```
$('#message_text').innerHTML = "hello";
```
Am I doing something wrong?
Anyone have any ideas? | When you do something like `$('#message_text')` what you have there is not a regular DOM object, but a jQuery wrapped set (even though in this case it'd only be one element.) If you wanted to access a particular DOM property, you could do this:
```
$('#message_text')[0].innerHTML = 'whatever';
$('#message_text').get(0).innerHTML = 'whatever';
```
However, this isn't necessary in this case as jQuery has two functions to do what you want:
[`html()`](http://docs.jquery.com/Html):
```
$('#message_text').html('whatever');
```
[`text()`](http://docs.jquery.com/Attributes/text):
```
$('#message_text').text('whatever');
```
The difference between the two is that `html()` will allow HTML while `text()` will escape any HTML tags you pass to it. Use the one you need over manually manipulating the HTML with innerHTML. | The jQuery function [`$()`](http://docs.jquery.com/%24) is not returning a *HTMLElement* object like `getElementById()` does but a *jQuery* object. And there you just have the [`html()`](http://docs.jquery.com/Html) method as equivalent to `innerHTML`. So:
```
$('#message_text').html('hello');
``` | jquery changing innerhtml of a P isn't working | [
"",
"javascript",
"jquery",
""
] |
Today I saw that Microsoft announced 0.85 version of:
["Windows® API Code Pack for Microsoft® .NET Framework"](http://code.msdn.microsoft.com/WindowsAPICodePack)
This pack is targeted for Windows7 OS, although most features is supposed to work under Vista.
One of this pack's features is support for DirectX 11.
Knowing that few years ago Microsoft stopped development of Managed DirectX, and in mean time developed XNA Game Studio, it's hard to see purpose of this.
Simplified deployment?
Maybe W7 desktop applications are meant to relies heavily on DirectX?
Or?
Anyone have a good comment related to this resurrected managed DX? | At the moment, Microsoft does NOT in fact have any plans to bring back MDX. However, they have XNA, which you and some others have mentioned. MDX was just a thin wrapper around the DirectX functionality. That is, you had some device functions, you had some IO functions, and those got wrapped into managed classes, nothing more. XNA is much more than that, having its own content pipeline, a much higher-level support for shaders, 3D models, textures, device management, etc. It is also cross-platform in that it runs on the PC, Xbox360, as well as the Zune.
So, on short, no plans are for resurrecting MDX, but there are alternatives, such as the mentioned XNA. There is also another, non-Microsoft, project, SlimDX. It is a managed wrapper around DirectX, much like MDX was, except it seems much more pleasurable to use, at first glance. I have not used it much myself, but from reading what others have to say, it seems to be doing a good job.
Hope this answers your question. | I'd like to mention that SlimDX's next release will have full DirectX11 support, along with other Win7 APIs. it's wider than what the code pack has to offer.
<http://ventspace.wordpress.com/2009/06/09/c-and-directx-11-yes-you-can/> | Is Microsoft ressurecting Managed DirectX? | [
"",
"c#",
".net",
"windows",
"windows-7",
"directx",
""
] |
## Duplicate
> [Should C# methods that *can* be static be static?](https://stackoverflow.com/questions/731763/should-c-methods-that-can-be-static-be-static/731779#731779)
---
Please forgive me if this question seems elementary - I'm looking over some source code that otherwise looks pretty good, but it's raised some questions...
If a given class has no member data - i.e. it doesn't maintain any sort of state, are there any benefits in not marking that class as a static class with static methods?
Are there any benefits in not marking methods which don't maintain state as static?
Thanks!
EDIT: Since someone brought it up, the code I'm looking at is written in c#. | Yes. I can think of some reasons:
1. Ease of mocking and unit testing
2. Ease of adding state
3. You could pass it around (as an `interface` or something) | I would say there is a benefit to making them static methods of the class, and on top of that making the class abstract. That way, it's clear to the programmer that this class was never intended to be instantiated and the methods are still available. | Static class vs instanced class | [
"",
"c#",
"static",
"state",
"instance",
""
] |
I built a webapp that works perfectly fine in my localhost (tomcat). But when I tried to deploy, velocity crashes in init(), leaving me with this strange stack trace here (sorry for the size):
```
ERROR [main] (VelocityConfigurator.java:62) - Error initializing Velocity!
org.apache.velocity.exception.VelocityException: Failed to initialize an instance of org.apache.velocity.runtime.log.Log4JLogChute with the current runtime configuration.
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:206)
at org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:255)
at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:795)
at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:250)
at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:589)
at org.apache.velocity.runtime.RuntimeSingleton.init(RuntimeSingleton.java:229)
at org.apache.velocity.app.Velocity.init(Velocity.java:107)
at com.webcodei.velociraptor.velocity.VelocityConfigurator.initVelocity(VelocityConfigurator.java:57)
at com.webcodei.velociraptor.velocity.VelocityConfigurator.configure(VelocityConfigurator.java:42)
at com.webcodei.velociraptor.VelociListener.contextInitialized(VelociListener.java:26)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4336)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:761)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:741)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1023)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1015)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:448)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.RuntimeException: Error configuring Log4JLogChute :
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.apache.velocity.util.ExceptionUtils.createWithCause(ExceptionUtils.java:67)
at org.apache.velocity.util.ExceptionUtils.createRuntimeException(ExceptionUtils.java:45)
at org.apache.velocity.runtime.log.Log4JLogChute.initAppender(Log4JLogChute.java:133)
at org.apache.velocity.runtime.log.Log4JLogChute.init(Log4JLogChute.java:85)
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:157)
... 33 more
Caused by: java.io.FileNotFoundException: velocity.log (Permission denied)
at java.io.FileOutputStream.openAppend(Native Method)
at java.io.FileOutputStream.(FileOutputStream.java:177)
at java.io.FileOutputStream.(FileOutputStream.java:102)
at org.apache.log4j.FileAppender.setFile(FileAppender.java:290)
at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:194)
at org.apache.log4j.FileAppender.(FileAppender.java:109)
at org.apache.log4j.RollingFileAppender.(RollingFileAppender.java:72)
at org.apache.velocity.runtime.log.Log4JLogChute.initAppender(Log4JLogChute.java:118)
... 35 more
ERROR [main] (VelocityConfigurator.java:63) - java.lang.RuntimeException: Error configuring Log4JLogChute :
org.apache.velocity.exception.VelocityException: Failed to initialize an instance of org.apache.velocity.runtime.log.Log4JLogChute with the current runtime configuration.
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:206)
at org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:255)
at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:795)
at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:250)
at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:589)
at org.apache.velocity.runtime.RuntimeSingleton.init(RuntimeSingleton.java:229)
at org.apache.velocity.app.Velocity.init(Velocity.java:107)
at com.webcodei.velociraptor.velocity.VelocityConfigurator.initVelocity(VelocityConfigurator.java:57)
at com.webcodei.velociraptor.velocity.VelocityConfigurator.configure(VelocityConfigurator.java:42)
at com.webcodei.velociraptor.VelociListener.contextInitialized(VelociListener.java:26)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4336)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:761)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:741)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1023)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1015)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:448)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.RuntimeException: Error configuring Log4JLogChute :
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.apache.velocity.util.ExceptionUtils.createWithCause(ExceptionUtils.java:67)
at org.apache.velocity.util.ExceptionUtils.createRuntimeException(ExceptionUtils.java:45)
at org.apache.velocity.runtime.log.Log4JLogChute.initAppender(Log4JLogChute.java:133)
at org.apache.velocity.runtime.log.Log4JLogChute.init(Log4JLogChute.java:85)
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:157)
... 33 more
Caused by: java.io.FileNotFoundException: velocity.log (Permission denied)
at java.io.FileOutputStream.openAppend(Native Method)
at java.io.FileOutputStream.(FileOutputStream.java:177)
at java.io.FileOutputStream.(FileOutputStream.java:102)
at org.apache.log4j.FileAppender.setFile(FileAppender.java:290)
at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:194)
at org.apache.log4j.FileAppender.(FileAppender.java:109)
at org.apache.log4j.RollingFileAppender.(RollingFileAppender.java:72)
at org.apache.velocity.runtime.log.Log4JLogChute.initAppender(Log4JLogChute.java:118)
... 35 more
ERROR [main] (VelocityConfigurator.java:64) - Failed to initialize an instance of org.apache.velocity.runtime.log.Log4JLogChute with the current runtime configuration.
org.apache.velocity.exception.VelocityException: Failed to initialize an instance of org.apache.velocity.runtime.log.Log4JLogChute with the current runtime configuration.
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:206)
at org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:255)
at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:795)
at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:250)
at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:589)
at org.apache.velocity.runtime.RuntimeSingleton.init(RuntimeSingleton.java:229)
at org.apache.velocity.app.Velocity.init(Velocity.java:107)
at com.webcodei.velociraptor.velocity.VelocityConfigurator.initVelocity(VelocityConfigurator.java:57)
at com.webcodei.velociraptor.velocity.VelocityConfigurator.configure(VelocityConfigurator.java:42)
at com.webcodei.velociraptor.VelociListener.contextInitialized(VelociListener.java:26)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4336)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:761)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:741)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1023)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1015)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:448)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.RuntimeException: Error configuring Log4JLogChute :
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.apache.velocity.util.ExceptionUtils.createWithCause(ExceptionUtils.java:67)
at org.apache.velocity.util.ExceptionUtils.createRuntimeException(ExceptionUtils.java:45)
at org.apache.velocity.runtime.log.Log4JLogChute.initAppender(Log4JLogChute.java:133)
at org.apache.velocity.runtime.log.Log4JLogChute.init(Log4JLogChute.java:85)
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:157)
... 33 more
Caused by: java.io.FileNotFoundException: velocity.log (Permission denied)
at java.io.FileOutputStream.openAppend(Native Method)
at java.io.FileOutputStream.(FileOutputStream.java:177)
at java.io.FileOutputStream.(FileOutputStream.java:102)
at org.apache.log4j.FileAppender.setFile(FileAppender.java:290)
at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:194)
at org.apache.log4j.FileAppender.(FileAppender.java:109)
at org.apache.log4j.RollingFileAppender.(RollingFileAppender.java:72)
at org.apache.velocity.runtime.log.Log4JLogChute.initAppender(Log4JLogChute.java:118)
... 35 more
```
Does anyone knows the workaround? Or at least understood the error? I've done some googling but no clues.. only this [page](http://www.nabble.com/org.apache.velocity.runtime.log.Log4JLogChute-initialization-failed-td22099662.html) facing the same problem but no solution.. | I think this line has the answer. Looks like there is an issue creating the velocity.log file. What does your configuration file look like?
```
Caused by: java.io.FileNotFoundException: velocity.log (Permission denied)
``` | Velocity tries to put the logfile in the directory Tomcat was started from, and I believe that is actually /.
You can force Velocity to log to Tomcat's standard log by adding these lines to your velocity.properties:
```
runtime.log.logsystem.class=org.apache.velocity.runtime.log.SimpleLog4JLogSystem
runtime.log.logsystem.log4j.category=velocity
runtime.log.logsystem.log4j.logger=velocity
```
The velocity.properties should go into /WEB-INF/velocity.properties but you can override that in you servlet definition in web.xml.
If you're initialising Velocity by properties and not the velocity.properties:
```
VelocityEngine engine = new VelocityEngine();
Properties props = new Properties();
props.put("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
props.put("runtime.log.logsystem.log4j.category", "velocity");
props.put("runtime.log.logsystem.log4j.logger", "velocity");
engine.init(props);
```
Read more here:
<http://velocity.apache.org/engine/devel/developer-guide.html#usinglog4jwithexistinglogger>
and here:
<http://minaret.biz/tips/tomcatLogging.html#velocity> | Error in velocity and log4J | [
"",
"java",
"servlets",
"log4j",
"stack-trace",
"velocity",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.