Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have been using Weblogic as my company used it. Now I want to try JBoss as an alternative. I'm using Eclipse with MyEclipse 7.1 plugin. I downloaded and unzipped JBoss 5.0.1GA with Java JDK 1.5.0.14. I set the server up using MyEclipse interface and got the following error (couldn't find solution elsewhere online):
```
10:42:54,240 INFO [TransactionManagerService] Initializing recovery manager
10:42:54,300 FATAL [arjLoggerI18N] [com.arjuna.ats.internal.arjuna.recovery.fail] RecoveryManagerImple: cannot bind to socket on address /127.0.0.1 and port 4,712
10:42:54,310 ERROR [AbstractKernelController] Error installing to Create: name=TransactionManager state=Configured
com.arjuna.ats.arjuna.exceptions.FatalError: Recovery manager already active (or recovery port and address are in use)!
at com.arjuna.ats.internal.arjuna.recovery.RecoveryManagerImple.<init>(RecoveryManagerImple.java:146)
at com.arjuna.ats.arjuna.recovery.RecoveryManager.<init>(RecoveryManager.java:372)
at com.arjuna.ats.arjuna.recovery.RecoveryManager.manager(RecoveryManager.java:132)
at com.arjuna.ats.arjuna.recovery.RecoveryManager.manager(RecoveryManager.java:113)
at com.arjuna.ats.jbossatx.jta.TransactionManagerService.create(TransactionManagerService.java:207)
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:585)
at org.jboss.reflect.plugins.introspection.ReflectionUtils.invoke(ReflectionUtils.java:59)
at org.jboss.reflect.plugins.introspection.ReflectMethodInfoImpl.invoke(ReflectMethodInfoImpl.java:150)
at org.jboss.joinpoint.plugins.BasicMethodJoinPoint.dispatch(BasicMethodJoinPoint.java:66)
```
.`............................`
Any ideas what is wrong in here?
Thanks,
Tam | My first guess is that the server is trying to use a port that is alredy in use.
Do you have any other web servers installed? I know some have services that start up automatically.
To check for this on a windows box I usually reboot and the very first program I start up is the web server so it locks any ports it needs. | I had the same problem. In my case it was Skype that caused this problem. When I shutdown skype, the server starts ok again. | setting up JBoss5 with MyEclipse | [
"",
"java",
"jboss",
"myeclipse",
""
] |
Let me preface by I am just starting Python so if this is really a simple question ^\_^
I have a html file with the following content:
```
{%for d in results%}
<div class="twt">
<img src="{{ d.profile_image_url }}" width="48px" height="48px" /> <span> {{ d.text }} </span>
<span class="date">{{ d.created_at }}</span>
</div>
{% endfor %}
```
which works well but I also would like to declare a variable on this page. Let's say for this example, we can it RowNumber which will increment for each d displayed, spitting out the current RowNumber.
I tried doing:
```
{{ RowNumber = 0}}
{{ RowNumber ++ }}
```
But it doesn't seem to allow me to declare RowNumber. | Check out the [documentation](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for) on the `for` loop.
It automatically creates a variable called `forloop.counter` that holds the current iteration index.
As far as the greater question on how to declare variables, there is no out-of-the-box way of doing this with Django, and it is not considered a missing feature but a feature. If you really wanted to do this it is possible with [custom tags](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags) but for the most part the philosophy you want to follow is that mostly anything you want to do that would require this should be done in the view and the template should be reserved for very simple logic. For your example of summing up a total, for example, you could use the [add](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#add) filter. Likewise, you can [create your own filters](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters) just like with tags. | If you want to set any variable inside a Django template, you can use [this small template tag I've written](https://surdu.me/2011/02/18/set-variable-django-template.html). | Django Template - New Variable Declaration | [
"",
"python",
"django",
"django-templates",
""
] |
When users create an account on my site I want to make server validation for emails to not accept *every* input.
I will send a confirmation, in a way to do a [handshake validation](https://stackoverflow.com/questions/156430/regexp-recognition-of-email-address-hard/156441#156441).
I am looking for **something simple, not *the best***, but not too simple that doesn't validate anything. I don't know where limitation must be, since any regular expression will not do the correct validation because is not possible to do it with regular expressions.
I'm trying to limit the sintax and visual complexity inherent to regular expressions, because in this case any will be correct.
What regexp can I use to do that? | ```
^\S+@\S+$
``` | It's possible to write a regular expression that only accept email addresses that follow the standards. However, there are some email addresses out there that doesn't strictly follow the standards, but still work.
Here are some simple regular expressions for basic validation:
Contains a @ character:
```
@
```
Contains @ and a period somewhere after it:
```
@.*?\.
```
Has at least one character before the @, before the period and after it:
```
.+@.+\..+
```
Has only one @, at least one character before the @, before the period and after it:
```
^[^@]+@[^@]+\.[^@]+$
```
User AmoebaMan17 suggests this modification to eliminate whitespace:
```
^[^@\s]+@[^@\s]+\.[^@\s]+$
```
And for accepting only one period ***[external edit: not recommended, does not match valid email adresses]***:
```
^[^@\s]+@[^@\s\.]+\.[^@\.\s]+$
``` | What is a good regular expression for catching typos in an email address? | [
"",
"c#",
"regex",
"email-validation",
""
] |
I am adding some script using the StringBuilder. The script is as shown below.
```
<script type='text/javascript'><!-- //<![CDATA[
var m3_u = (location.protocol == 'https:' ? 'https://rre.rrt.com/sss.php' : 'https://rre.rrt.com/sss.php');
var m3_r = Math.floor(Math.random() * 99965449);
if (!document.MAX_used) document.MAX_used = ',';
document.write("<scr" + "ipt type='text/javascript' src='" + m3_u);
document.write("?zoneid=311120&target=_top");
document.write('&cb=' + m3_r);
if (document.MAX_used != ',') document.write("&exclude=" + document.MAX_used);
document.write(document.charset ? '&charset=' + document.charset : (document.characterSet ? '&charset=' + document.characterSet : ''));
document.write("&loc=" + escape(window.location));
if (document.referrer) document.write("&referer=" + escape(document.referrer));
if (document.context) document.write("&context=" + escape(document.context));
if (document.mmm_fo) document.write("&mmm_fo=1");
document.write("'><\/scr" + "ipt>");
//]]>-->
</script><noscript><a href='https://rre.rrt.com/sss.php?n=ad4565c1&cb=2244' target='_top'><img src='https://rre.rrt.com/sss.php?zoneid=36540&n=a535c1' border='0' alt='' /></a></noscript>
```
When I add this using String Builder, it gives error "Too many characters in character literal" This is how I am doing. How to do it?
```
sb.append(@"<script type='text/javascript'><!-- //<![CDATA[
var m3_u = (location.protocol == 'https:' ? 'https://rre.rrt.com/sss.php' : 'https://rre.rrt.com/sss.php');
var m3_r = Math.floor(Math.random() * 99965449);
if (!document.MAX_used) document.MAX_used = ',';
document.write("<scr" + "ipt type='text/javascript' src='" + m3_u);
document.write("?zoneid=311120&target=_top");
document.write('&cb=' + m3_r);
if (document.MAX_used != ',') document.write("&exclude=" + document.MAX_used);
document.write(document.charset ? '&charset=' + document.charset : (document.characterSet ? '&charset=' + document.characterSet : ''));
document.write("&loc=" + escape(window.location));
if (document.referrer) document.write("&referer=" + escape(document.referrer));
if (document.context) document.write("&context=" + escape(document.context));
if (document.mmm_fo) document.write("&mmm_fo=1");
document.write("'><\/scr" + "ipt>");
//]]>-->
</script><noscript><a href='https://rre.rrt.com/sss.php?n=ad4565c1&cb=2244' target='_top'><img src='https://rre.rrt.com/sss.php?zoneid=36540&n=a535c1' border='0' alt='' /></a></noscript>
");
``` | The whole point of using a `StringBuilder` is to **build** the string part by part. If you break up the long string into logical portions, then it becomes easier for you to figure out any errors as well as make modifications (*and believe me, it becomes much easier to read!*).
Also, When using verbatim string literals in C#, you still need to escape double quotes with another double quote. The following code compiles correctly:
```
sb.Append(@"<script type='text/javascript'>");
sb.Append(@"<!-- //<![CDATA[");
sb.Append(@"var m3_u = (location.protocol == 'https:' ? 'https://rre.rrt.com/sss.php' : 'https://rre.rrt.com/sss.php');");
sb.Append(@"var m3_r = Math.floor(Math.random() * 99965449);");
sb.Append(@"if (!document.MAX_used) document.MAX_used = ',';"");");
sb.Append(@"document.write(""<script type='text/javascript' src='"" + m3_u);");
sb.Append(@"document.write(""?zoneid=311120&target=_top"");");
sb.Append(@"document.write('&cb=' + m3_r);");
sb.Append(@"if (document.MAX_used != ',') document.write(""&exclude="" + document.MAX_used);");
sb.Append(@"document.write(document.charset ? '&charset=' + document.charset : ");
sb.Append(@"(document.characterSet ? '&charset=' + document.characterSet : ''));");
sb.Append(@"document.write(""&loc="" + escape(window.location));");
sb.Append(@"if (document.referrer) document.write(""&referer="" + escape(document.referrer));");
sb.Append(@"if (document.context) document.write(""&context="" + escape(document.context));");
sb.Append(@"if (document.mmm_fo) document.write(""&mmm_fo=1"");");
sb.Append(@"document.write(""'><\/script>"");");
sb.Append(@"//]]>-->");
sb.Append(@"</script>");
sb.Append(@"<noscript>");
sb.Append(@"<a href='https://rre.rrt.com/sss.php?n=ad4565c1&cb=2244' target='_top'>");
sb.Append(@"<img src='https://rre.rrt.com/sss.php?zoneid=36540&n=a535c1' border='0' alt='' /></a>");
sb.Append(@"</noscript>");
``` | .NET usually gives the error when you are trying to initalise a char type with more than one character.
From the conversation [here](http://www.groupsrv.com/dotnet/about29367.html) it seems you may also get the error when .NET gets confused by single quotes and assumes you are trying to use them to define a 'char' literal.
Given the heavy use of double and single quotes in your string above, I'd recommend splitting it up into smaller strings and .append() each one separately - maybe a seperate .append() call for each line of the string.
Then you will be able to narrow it down and find out which bit .NET is objecting to.
You should then be able to fix the problem by checking through the double and single quotes. I can't really decipher your append but it looks like you should be using escaped double quotes \" in some places.
edit: example of escaping double quotes:
e.g
```
sb.Append("document.write(\"<scr\" + \"ipt type='text/javascript' src='\" + m3_u);");
```
edit after Cerebrus suggestion:
If you want to use a verbatim string literal (with the @ prefix) then the double-quotes must be escaped by repeating them:
```
sb.Append(@"document.write(""<scr"" + ""ipt type='text/javascript' src='"" + m3_u);");
``` | Too many characters in character literal | [
"",
"javascript",
""
] |
Suppose I had the following method in an object:
```
public class foo
{
public bool DoSomethingAwesome()
{
bool bar = DidSomething() //suppose this sends an email;
return bar;
}
}
```
If I wanted to provide more detail on why DidSomething returned a false would the best practice be to assign a message to a Property to foo, or assign an Out parameter to DoSomethingAwesome? | I think this depends highly on the framework you're using (i.e. it's a convention).
* For Win32 - you had the SetLastError,
GetLastError.
* For .NET it's usually
throwing an Exception but that could be
changed to match your circumstances.
Probably an out param would be ok.
If you decide to go with the Exception route, MSDN has an entry with "[Design Guidelines for Exceptions](http://msdn.microsoft.com/en-us/library/ms229014.aspx)". And there's a great discussion in the book "[Framework Design Guidlines](https://rads.stackoverflow.com/amzn/click/com/0321545613)" - chapter 7, which I highly recommend! | It depends very much on what you're doing, but in the situation given—sending an email—I would throw different exceptions based on what went wrong. As sending an email should work pretty much every time, when something bad happens, I'd want to force the caller to handle it rather than ignoring it by default.
In other situtations, where the chance of failure is high, failure can be ignored, or `false` doesn't necessarily mean failure, I'd create an `enum` which has values for each type of failure and one for success, and return that rather than a `bool`. | Best way to explain why something failed | [
"",
"c#",
""
] |
I'm running an asp.net 2.0 web application. Suddenly this morning, ExecuteNonQuery started returning -1, even though the commands in the SP that ExecuteNonQuery is running, are executing (I see items inserted and updated in the DB), and there is no exception thrown.
This happens only when I am connected to our production DB. When I'm connected to our development DB they return the correct number of rows affected.
Also, interestingly enough, ExecuteDataSet doesn't have problems - it returns DataSets beautifully.
So it doesn't seem like a connection problem. But then, what else could it be? | You can also check the procedure to see if there's this line of code in there -
```
SET NOCOUNT ON
```
This will cause the ExecuteNonQuery to always return -1. | -1 means "No rows effected".
SELECT statement will also return -1.
Check the effect of the SP on dev and live environments.
Taken from [SqlCommand::ExecuteNonQuery Method](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx)
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1. | ExecuteNonQuery returns -1 even though the execution was successful | [
"",
"asp.net",
"sql",
""
] |
I work on an open source product called [EVEMon](http://evemon.battleclinic.com/) written in C# targeting the .NET 2.0 platform, I have one user who is suffering from a strange .NET crash that we have been unable to resolve.
```
Event Type: Error
Event Source: .NET Runtime 2.0 Error Reporting
Event Category: None
Event ID: 5000
Date: 4/29/2009
Time: 10:58:10 PM
User: N/A
Computer: removed this
Description:
EventType clr20r3, P1 evemon.exe, P2 1.2.7.1301, P3 49ea37c8, P4
system.windows.forms, P5 2.0.0.0, P6 4889dee7, P7 6cd3, P8 18, P9
system.argumentexception, P10 NIL.
Data:
//hex representation of the above Description
```
The application itself crashes with out displaying an error (despite having a error handling UI), the above messages was copied out of the Windows Event log. The end user has re-installed .NET and updated to the latest versions. The .PDB files are distributed with every release version of the program to aid in debugging and testing, the user with the problem in question has the full complement of PDB files for the correct version of EVEMon.
Is there a specific, tried and tested technique to analyse and diagnose this type of crash? and if so what tools and technologies are available to aid in debugging?
## Special Thanks
I would like to give special thanks to Steffen Opel and highlight that [his answer](https://stackoverflow.com/questions/814560/how-to-troubleshoot-net-2-0-error-reporting-messages-in-the-event-log/1082254#1082254) whilst not directly answering the question I was asking, addressed the bigger issue with my code base that the global error handling was missing an important component. | This is how I would tackle the problem for a end user with a crash.
1. Download and install Debugging Tools for Windows at <http://www.microsoft.com/whdc/devtools/debugging/default.mspx>
2. Once the tools are installed (they end up going to C:\Program Files\ by default) start a command line window.
3. Change to the directory which contains adplus (e.g "C:\Program Files\Debugging Tools for Windows (x86)").
4. Run the follwing command. This will start the application and attach adplus.
> `adplus -crash -o C:\debug\ -FullOnFirst -sc C:\path\to\your\app.exe`
## After the crash dump is created
Once the application crashes start WinDbg and load the .dmp file that is created in C:\debug. (File --> Open Crash Dump)
Execute these commands to see the stack trace and hopefully find the problem.
To load SOS for debugging
* Pre .NET 4.0
> ```
> .loadby sos mscorwks
> ```
* .NET 4.0
> ```
> .loadby sos clr
> ```
To see the stack trace
```
!clrstack
```
To see a more useful stack trace
```
!clrstack –p
```
To poke inside an object..perhaps see what caused the exception
```
!do <address>
```
e.g This is the result from a application that faulted randomly with an IO exception. WinDbg pointed out the path that was being referenced which was incorrect.
```
0:009> !do 017f2b7c
Name: System.String
MethodTable: 790fd8c4
EEClass: 790fd824
Size: 124(0x7c) bytes
(C:\WINDOWS\assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
String: \\server\path\not_here.txt
Fields:
MT Field Offset Type VT Attr Value Name
79102290 4000096 4 System.Int32 1 instance 54 m_arrayLength
79102290 4000097 8 System.Int32 1 instance 53 m_stringLength
790ff328 4000098 c System.Char 1 instance 5c m_firstChar
790fd8c4 4000099 10 System.String 0 shared static Empty
>> Domain:Value 00161df8:790d884c <<
7912dd40 400009a 14 System.Char[] 0 shared static WhitespaceChars
>> Domain:Value 00161df8:014113e8 <<
``` | Peeking into your source code (trunk) indicates that your unhandled exception handling seems to be incomplete in regard to Windows Forms applications:
You need to handle **both** non-UI thread exceptions and UI thread exceptions:
* For the former you need to implement a CLR unhandled exception handler via `AppDomain.CurrentDomain.UnhandledException`, which is in place already.
* For the latter you need to implement a Windows Forms unhandled exception handler via **`Application.ThreadException`**, which seems to be missing; this could indeed yield exactly those problems you are witnessing. For an implementation example see MSDN documentation of [Application.ThreadException Event](http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx).
Please note that right now you explicitly suppress catching unhandled Windows Forms exceptions via `Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException)`, you'll need to change this to `UnhandledExceptionMode.CatchException` to enable routing to your handler for `Application.ThreadException`, as correctly suggested by Jehof already. | How to troubleshoot .NET 2.0 Error Reporting messages in the event log? | [
"",
"c#",
".net",
"crash",
"event-log",
"crash-reports",
""
] |
Instead of tediously search for workarounds for each type of attribute and event when using the following syntax:
```
elem = document.createElement("div");
elem.id = 'myID';
elem.innerHTML = ' my Text '
document.body.insertBefore(elem,document.body.childNodes[0]);
```
Is there a way where I can just declare the entire HTML element as a string? like:
```
elem = document.createElement("<div id='myID'> my Text </div>");
document.body.insertBefore(elem,document.body.childNodes[0]);
``` | Instead of directly messing with **`innerHTML`** it might be better to create a fragment and then insert that:
```
function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);
```
Benefits:
1. You can use native DOM methods for insertion such as insertBefore, appendChild etc.
2. You have access to the actual DOM nodes before they're inserted; you can access the fragment's childNodes object.
3. Using document fragments is very quick; faster than creating elements outside of the DOM and in certain situations faster than innerHTML.
---
Even though **`innerHTML`** is used within the function, it's all happening outside of the DOM so it's much faster than you'd think... | You want this
```
document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID">...</div>' );
``` | Inserting HTML elements with JavaScript | [
"",
"javascript",
"html",
""
] |
I'm trying to serialize and deserialize a tree of Node objects. My abstract "Node" class as well as other abstract and concrete classes that derive from it are defined in my "Informa" project. In addition, I've created a static class in Informa for serialization / deserialization.
First I'm deconstructing my tree into a flat list of type **Dictionary(guid,Node)** where guid is the unique id of Node.
I am able to serialize all my Nodes with out a problem. But when I try to deserialize I get the following exception.
> Error in line 1 position 227. Element
> '<http://schemas.microsoft.com/2003/10/Serialization/Arrays:Value>'
> contains data of the
> 'Informa:Building' data contract. The
> deserializer has no knowlege of any
> type that maps to this contract. Add
> the type corresponding to 'Building'
> to the list of known types - for
> example, by usying the
> KnownTypeAttribute or by adding it to
> the list of known types passed to
> DataContract Serializer.
All classes that derive from Node, including Building, have the **[KnownType(typeof(type t))]** attribute applied to them.
My serialization and deserialization methods are below:
```
public static void SerializeProject(Project project, string filePath)
{
try
{
Dictionary<Guid, Node> nodeDic = DeconstructProject(project);
Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
//serialize
DataContractSerializer ser = new DataContractSerializer(typeof(Dictionary<Guid, Node>),"InformaProject","Informa");
ser.WriteObject(stream,nodeDic);
// Cleanup
stream.Close();
}
catch (Exception e)
{
MessageBox.Show("There was a problem serializing " + Path.GetFileName(filePath) + ". \n\nException:" + e.Message, "Doh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw e;
}
}
public static Project DeSerializeProject(string filePath)
{
try
{
Project proj;
// Read the file back into a stream
Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
DataContractSerializer ser = new DataContractSerializer(typeof(Dictionary<Guid, Node>), "InformaProject", "Informa");
Dictionary<Guid, Node> nodeDic = (Dictionary<Guid, Node>)ser.ReadObject(stream);
proj = ReconstructProject(nodeDic);
// Cleanup
stream.Close();
return proj;
}
catch (Exception e)
{
MessageBox.Show("There was a problem deserializing " + Path.GetFileName(filePath) + ". \n\nException:" + e.Message, "Doh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
``` | > All classes that derive from Node,
> including Building, have the
> [KnownType(typeof(type t))] attribute
> applied to them.
`KnownType` is usually applied to the *base* type - i.e.
```
[DataContract, KnownType(typeof(Building)), ...]
abstract class Node { ... }
```
(note - you can also specify the known-types in the `DataContractSerializer` constructor, without requiring attributes)
**EDIT RE YOUR REPLY**
If the framwork class doesn't know about all the derived types, then you need to specify the known types when creating the serializer:
```
[DataContract] abstract class SomeBase { }
[DataContract] class Foo : SomeBase { }
[DataContract] class Bar : SomeBase { }
...
// here the knownTypes argument is important
new DataContractSerializer(typeof(SomeBase),
new Type[] { typeof(Foo), typeof(Bar) });
```
This can be combined with (for example) `preserveObjectReferences` etc by replacing the `null` in the previous example.
**END EDIT**
However, without something reproducible (i.e. `Node` and `Building`), it is going to be hard to help much.
The other odd thing; trees structures are *very well suited* to things like `DataContractSerializer` - there is usually no need to flatten them first, since trees can be trivially expressed in xml. Do you really need to flatten it?
---
Example:
```
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
[DataContract, KnownType(typeof(Building))]
abstract class Node {
[DataMember]
public int Foo {get;set;}
}
[DataContract]
class Building : Node {
[DataMember]
public string Bar {get;set;}
}
static class Program
{
static void Main()
{
Dictionary<Guid, Node> data = new Dictionary<Guid, Node>();
Type type = typeof(Dictionary<Guid, Node>);
data.Add(Guid.NewGuid(), new Building { Foo = 1, Bar = "a" });
StringWriter sw = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(sw))
{
DataContractSerializer dcs = new DataContractSerializer(type);
dcs.WriteObject(xw, data);
}
string xml = sw.ToString();
StringReader sr = new StringReader(xml);
using (XmlReader xr = XmlReader.Create(sr))
{
DataContractSerializer dcs = new DataContractSerializer(type);
Dictionary<Guid, Node> clone = (Dictionary<Guid, Node>)
dcs.ReadObject(xr);
foreach (KeyValuePair<Guid, Node> pair in clone)
{
Console.WriteLine(pair.Key + ": " + pair.Value.Foo + "/" +
((Building)pair.Value).Bar);
}
}
}
}
``` | Alright here's a diagram that should make things more clear. I'm developing a plugin for another program that adds relationships and properties not already included in the program. These relationships/properties are defined in my tree structure. However, I'm trying to define this structure abstractly so that I could create implementations of the plugin for different programs, as well as access the information from multiple implementations in a single "viewer" program.
My Serialize/Deserialize methods are defined in the framework, but the framework does not know about all the implementations. I was hoping I could avoid having the implementation projects pass a list of types to the save/open/serialize/deserialize methods in the framework project, but it seems I can't avoid this? I guess that make sense though, the serialize/deserialize methods must have access to the types they are deserializing.
<http://dl.getdropbox.com/u/113068/informa_framework.jpg> <---Larger Version
[alt text http://dl.getdropbox.com/u/113068/informa\_framework.jpg](http://dl.getdropbox.com/u/113068/informa_framework.jpg)
So this doesn't really explain the problem with Building, as it is a concrete class in the framework project. I think what is happening is when I serialize the DataContractSerializer has access to all the objects and their KnowType parameter and saves them correctly. But when I deserialize I create my DataContractSerializer with Dictionary as the type. So it only knows about Nodes, but not the derived classes of nodes.
```
new DataContractSerializer(typeof(Dictionary<Guid, Node>))
```
I can't tell it what all the derived types are because like I said they are in other projects that the framework project doesn't know about. Soooooooo seems like the best solution is to have each implementation pass a list of Node types it uses to the serialization and deserialization methods in the framework project.
Does this make sense? Is there a better way to do this? | The deserializer has no knowlege of any type that maps to this contract | [
"",
"c#",
"serialization",
"datacontractserializer",
""
] |
I'm currently working on a small web application using Visual Studio 2008 Express. I'm attempting to retrieve an XML document from a server using a client library and then save the document into a database column (using Linq). The database column has the data type specified as `xml`. Unfortunately, I've been unsuccessful during my first few attempts.
Assuming that I've already got a reference to the data context object, here is the basics of what it is that I'm attempting to do:
```
// using a client library, requestthe XML document from the server
XmlDocument oXmlDoc = oClient.GetDataAsXML();
InformationLog oLog = new InformationLog();
oLog.InfoXML = oXmlDoc.InnerXml; // this is where the problem occurs
dbContext.InformationLogs.InsertOnSubmit(oLog);
dbContext.SubmitChanges();
```
Specifically, the error I get is:
```
Cannot implicitly convert type 'System.Xml.XmlNode' to 'System.Xml.Linq.XElement'
```
I'm new to ASP.NET MVC and Linq, so I know that I'm missing something. In addition to the answer, I'm also curious as to *why* it's impossible to simply save the XML as-is without any additional processing. | You should look to use XDocument rather than XmlDocument, and then try assigning the XDocument directly to your oLog.InfoXML property.
Without knowing how oClient.GetDataAsXML() works it's not clear whether you can easily create an XDocument from that call, but your life will be easier if you work in terms of XDocument instead of XmlDocument. | [Here's a great post on that](http://blogs.msdn.com/ericwhite/archive/2008/12/22/convert-xelement-to-xmlnode-and-convert-xmlnode-to-xelement.aspx). Basically you have the new XML types and old XML types clashing there. | Can't store XmlDocument in table column with data type 'xml' | [
"",
"c#",
"sql-server",
"asp.net-mvc",
"xml",
"linq",
""
] |
In Java, I need to make sure a String only contains `alphanumeric`, `space` and `dash` characters.
I found the class `org.apache.commons.lang.StringUtils` and the almost adequate method `isAlphanumericSpace(String)`... but I also need to include dashes.
What is the best way to do this? I don't want to use Regular Expressions. | Hum... just program it yourself using *String.chatAt*(**int**), it's pretty easy...
Iterate through all **char** in the string using a position index, then compare it using the fact that ASCII characters 0 to 9, a to z and A to Z use consecutive codes, so you only need to check that character x numerically verifies one of the conditions:
* between '0' and '9'
* between 'a' and 'z'
* between 'A and 'Z'
* a space ' '
* a hyphen '-'
Here is a basic code sample (using CharSequence, which lets you pass a String but also a StringBuilder as arg):
```
public boolean isValidChar(CharSequence seq) {
int len = seq.length();
for(int i=0;i<len;i++) {
char c = seq.charAt(i);
// Test for all positive cases
if('0'<=c && c<='9') continue;
if('a'<=c && c<='z') continue;
if('A'<=c && c<='Z') continue;
if(c==' ') continue;
if(c=='-') continue;
// ... insert more positive character tests here
// If we get here, we had an invalid char, fail right away
return false;
}
// All seen chars were valid, succeed
return true;
}
``` | You could use:
```
StringUtils.isAlphanumericSpace(string.replace('-', ' '));
``` | Java, Make sure a String contains only alphanumeric, spaces and dashes | [
"",
"java",
"string",
"parsing",
"contains",
""
] |
I am starting to use some Java code which was written by someone else. I have to understand, change and test it. The author is not available now. The package has some 50 files (and so classes) of different sizes. It would be great if I could just see/print out the names of the methods (public and private) and the public variables (like they are visible in the "outline window" in Eclipse). It would really help in understanding the code since I can just look at this and understand the general purpose of each class.
Can I do it in Eclipse other than by generating Javadoc, since Javadoc really creates too much details ? Is there a Eclipse plugin for this ? Or any other tool ?
Example:
For a Class file which represents a student, I could just get :
```
String name
int[] marks
int year
int idNumber
Student()
printName()
printMarks()
setName(String name)
```
... | javap might give you what you want too:
<http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javap.html> | In **Package Explorer**, right click on the package in question, select **Open Type Hierarchy** (Shortcut F4) gives a nice view of the hierarchy of objects in that package, selecting a class in that view will give you the class details. Not exactly what you're asking for but it'll help in understanding the package that you're changing. | Eclipse : list methods and variables of all classes | [
"",
"java",
"eclipse",
"documentation",
"javadoc",
""
] |
I understand that the default encoding of an HTTP Request is ISO 8859-1.
Am I able to use Unicode to decode an HTTP request given as a byte array?
If not, how would I decode such a request in C#?
**EDIT:** I'm developing a server, not a client. | As you said the default encoding of an HTTP POST request is ISO-8859-1. Otherwise you have to look at the Content-Type header that might then look like `Content-Type: application/x-www-form-urlencoded; charset=UTF-8`.
Once you have read the posted data into a byte array you may decide to convert this buffer to a string (remember all strings in .NET are UTF-16). It is only at that moment that you need to know the encoding.
```
byte[] buffer = ReadFromRequestStream(...)
string data = Encoding
.GetEncoding("DETECTED ENCODING OR ISO-8859-1")
.GetString(buffer);
```
And to answer your question:
> Am I able to use Unicode to decode an
> HTTP request given as a byte array?
Yes, if unicode has been used to encode this byte array:
```
string data = Encoding.UTF8.GetString(buffer);
``` | The code given below should help, if you are expecting large amount of data streaming down then doing it asynchronously is the best way to go about.
```
string myUrl = @"http://somedomain.com/file";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(myUrl);
//Set some reasonable limits on resources used by this request
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
request.Timeout = 15000;
response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(receiveStream, encode);
Char[] read = new Char[512];
// Reads 512 characters at a time.
int count = readStream.Read(read, 0, 512);
while (count > 0)
{
// Dumps the 512 characters on a string and displays the string.
String str = new String(read, 0, count);
count = readStream.Read(read, 0, 512);
}
``` | Can I use Unicode to decode an HTTP request? | [
"",
"c#",
"http",
"unicode",
"encoding",
"character-encoding",
""
] |
I have a web user control that generates the following html on the client.
I want to reference a specific RadioButton control using JavaScript.
I am not sure how to do this as the RadioButton ID is generated by asp.net.
For example I give the RadioButton ID = `1_RadioButton`
asp.net generates an ID = `ctl00_ContentPlaceHolder1_Material_1_RadioButton`
how can this javascript code find Radio Button controls?
```
<script type="text/javascript">
$(document).ready(function() {
if (document.getElementById("1_RadioButton").checked) {
$("#1_other").hide();
}
});
</script>
```
The following is what asp.net generates for the client.
```
<input id="ctl00_ContentPlaceHolder1_Material_1_RadioButton" type="radio" name="ctl00$ContentPlaceHolder1$Material$Academic" value="1_RadioButton" onclick="javascript:$('#1_other').show('fast');" />
<label for="ctl00_ContentPlaceHolder1_Material_1_RadioButton">Yes</label>
<input id="ctl00_ContentPlaceHolder1_Material_2_RadioButton" type="radio" name="ctl00$ContentPlaceHolder1$Material$Academic" value="2_RadioButton" checked="checked" onclick="javascript:$('#1_other').hide('fast');" />
<label for="ctl00_ContentPlaceHolder1_Material_2_RadioButton">No</label>
<input id="ctl00_ContentPlaceHolder1_Material_3_RadioButton" type="radio" name="ctl00$ContentPlaceHolder1$Material$Academic" value="3_RadioButton" onclick="javascript:$('#1_other').hide('fast');" />
<label for="ctl00_ContentPlaceHolder1_Material_3_RadioButton">Uncertain</label>
<div id='1_other'>
<input name="ctl00$ContentPlaceHolder1$Material$4_TextBox" type="text" value="bbb chabng" id="ctl00_ContentPlaceHolder1_Material_4_TextBox" />
</div>
``` | If that code is in the .aspx file use <%= MyRadioButton.ClientID %> in its place and the ASP.NET rendering engine will properly render the ID for you.
**Update:** For example:
```
<script type="text/javascript">
$(document).ready(function() {
if ($get("<%= MyRadioButton.ClientID %>").checked) {
$("#1_other").hide();
}
});
</script>
``` | ```
var radioButton = document.getElementById("<%= 1_RadioButton.ClientID %>");
```
And then go from there. Note - I'm not positive about the quotation marks. | javascript and asp.net web user controls | [
"",
"asp.net",
"javascript",
"jquery",
"web-user-controls",
""
] |
I am querying a database and I have 2 bit columns I need to combine (for this example if one is true the column must be true).
Something like: `Select col1 || col2 from myTable`
What is the easiest way of achieving this? | ```
select col1 | col2 from myTable
```
<http://msdn.microsoft.com/en-us/library/ms176122.aspx> | I'm assuming col1 and col2 are bit values, the closest Sql Server has to booleans.
To return 1 or 0:
```
select case when col1=1 or col2=1 then 1 else 0 end
from yourtable
```
To return true or false:
```
select case when col1=1 or col2=1 then 'true' else 'false' end
from yourtable
``` | How to combine 2 bit columns | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
In my program after clicking on the button - selected ListView entries should be copied to RichTextBox. ListView contains contact information, and the effect I want to accomplish is similar to the one in Oultook (when choosing contacts from contact book). Part of my code that serves this purpose looks like that:
```
private void toButton_Click(object sender, EventArgs e)
{
int start = 0;
for (int i = 0; i < contactsListView.SelectedItems.Count; i++)
{
if (contactsTextBox.TextLength != 0) contactsTextBox.Text += "; ";
start = contactsTextBox.TextLength;
contactsTextBox.Text += contactsListView.SelectedItems[i].Text + " " + contactsListView.SelectedItems[i].SubItems[1].Text + " [" + contactsListView.SelectedItems[i].SubItems[2].Text + "]";
contactsTextBox.Select(start, contactsTextBox.TextLength);
contactsTextBox.SelectionFont = new Font(contactsTextBox.SelectionFont, FontStyle.Underline);
contactsTextBox.DeselectAll();
contactsTextBox.SelectionFont = new Font(contactsTextBox.SelectionFont, FontStyle.Regular);
}
}
```
Unfortunately somehow FontStyle is inherited by entire text and everything I enter after entry from ListView is also underlined.
So my question is - how to underline only certain text (where I have made a mistake)?
There is similar topic on stackoverflow [here](https://stackoverflow.com/questions/136132/better-way-of-manipulating-richtext-in-c) unfortunately in my case solution stated there will be waste of resources. | Try this instead:
```
int start = 0;
for (int i = 0; i < contactsListView.SelectedItems.Count; i++)
{
if (contactsTextBox.TextLength != 0) contactsTextBox.Text += "; ";
start = contactsTextBox.TextLength;
contactsTextBox.Text += contactsListView.SelectedItems[i].Text +" " + contactsListView.SelectedItems[i].SubItems[1].Text + " [" + contactsListView.SelectedItems[i].SubItems[2].Text + "]";
}
this.contactsTextBox.Text += " ";
this.contactsTextBox.SelectionStart = 0;
this.contactsTextBox.SelectionLength = this.contactsTextBox.Text.Length-1;
contactsTextBox.SelectionFont = new Font(contactsTextBox.SelectionFont, FontStyle.Underline);
this.contactsTextBox.SelectionLength = 0;
```
Total hack, but basically, if you select the text after it's all there, but don't select ALL of it (which is why I add the extra " ") and then set the selection text, it has the desired effect. | Before adding more text to the end of the text box, position the cursor at the end, and set the font to the desired style. Then a call to rtb.AppendLine() should produce the desired results.
It's key to remember that the RTB control performs in the same manner as any other word processor. You set a style and start typing. Then anything you type after setting that style will take on those attributes that are under the corsor.
Update:
This appears to work perfectly.
```
Dim tTexts() As String = {"Dont underline me", "Underline me", "Dont underline me", "Underline me", "Dont underline me", "Underline me", "Dont underline me", "Underline me", "Dont underline me", "Underline me", "Dont underline me", "Underline me"}
Dim tUnderline As Boolean = False
Dim tIndex As Integer = 0
With oRTB
For tIndex = tTexts.GetLowerBound(0) To tTexts.GetUpperBound(0)
If tUnderline Then
.SelectionStart = .Text.Length
.SelectionFont = New Font("Arial", 12, FontStyle.Underline)
Else
.SelectionStart = .Text.Length
.SelectionFont = New Font("Arial", 12, FontStyle.Regular)
End If
.AppendText(tTexts(tIndex))
tUnderline = Not tUnderline
Next
End With
``` | How to selectively underline strings in RichTextBox? | [
"",
"c#",
"richtextbox",
"rtf",
""
] |
I have the following three tables:
[alt text http://img16.imageshack.us/img16/5499/linqtosqlquery.jpg](http://img16.imageshack.us/img16/5499/linqtosqlquery.jpg)
With LinqToSql I would like to retrieve a list of InventoryItems where (pointsName="Level" AND pointsValue <= maxStoreLevel) AND pointsName="Buy Price" and
Note that `maxStoreLevel` is an Integer and it is the value of the points row that has pointsName = "Level".
Since you can't use a where inside another where in Linq, I do not know how to go about retrieving the mentioned list.
Update: Here is the UML diagram as requested
[alt text http://img17.imageshack.us/img17/3403/umldiagram.jpg](http://img17.imageshack.us/img17/3403/umldiagram.jpg)
To further explain my scenario here's the data in my tables:
[alt text http://img4.imageshack.us/img4/7847/linqexample.jpg](http://img4.imageshack.us/img4/7847/linqexample.jpg)
Assuming maxStoreLevel is 1, "Hanzo's Helmet" has pointsValue = 1 where pointsName="Level" and also has a point called "Buy Price" therefore it's row should be returned (same goes with any other Inventoryitems with the same criteria) | OK, so this isn't as pretty as the lambda expressions and I'm still a little fuzzy on what exactly the where clause needs to be since PointsName can't be Level and Buy Price at the same time, but I needed to start the conversation somewhere. I'm guessing that you'll need to do 2 joins on the points table but since you know your setup better than I, I'm guessing you'll be able to take this and modify it as needed. Let me know what I'm missing...
```
var items = (From items in context.InventoryItems
join itemPoints in context.InventoryItemPoints on items.InventoryItemID equals itemPoints.InventoryItemID
join points in context.Points on itemPoints.pointsID equals points.pointsID
where (points.pointsName == "Level" && itemPoints.pointsValue == maxStoreLevel) && points.pointsName == "Buy Price"
select items).Distinct();
```
I knew the original wouldn't return rows as there was no way for the points name to have both values but based off your subsequent update, I think what you need is:
```
var items = (From items in context.InventoryItems
join levelItemPoints in context.InventoryItemPoints on items.InventoryItemID equals levelItemPoints.InventoryItemID
join levelPoints in context.Points on levelItemPoints.pointsID equals levelPoints.pointsID
join priceItemPoints in context.InventoryItemPoints on items.InventoryItemID equals priceItemPoints.InventoryItemID
join pricePoints in context.Points on priceItemPoints.pointsID equals pricePoints.pointsID
where (levelPoints.pointsName == "Level" && levelItemPoints.pointsValue == maxStoreLevel) && pricePoints.pointsName == "Buy Price"
select items).Distinct();
``` | Something like:
```
var items = inventoryItems.Where(
invItem => invItem.InventoryItemPoints.Contains(
iip => (iip.pointsName == "Buy Price" || iip.PointsName == "Level") &&
iip.pointsValue == maxStoreLevel);
```
but that's a bit of a guess based on what you've posted, if that's not it, a screenie of the dbml would be useful ;)
Update: OK - that's clearly rubbish (sorry, couple of glasses of wine too many :)
try this:
```
var items = dataContext.inventoryItems.Where(
invItem => ivnItem.InventoryItemPoints.Select(
iip => iip.Point.PointName).Contains(
"Buy Price")
&& invItem.InventoryItemPoints.Select(
iip => iip.pointsValue).Contains(maxStoreLevel));
```
Adding in the other pointNames should be easy enough... | LINQtoSQL Retrieving a table according to the values of another table where it has a many to many relationship with | [
"",
"c#",
"linq",
"linq-to-sql",
""
] |
I have List collection with around 35,000 strings
Typical string looks like this:
```
"<i>füüs</i>ampri tähis;lüh ld-st<i>anno</i>, aastal;<i>maj</i> lüh pr-st<i>argent</i>, raha (kursisedelitel)"
```
Basically this string contains bunch of words in Estonian :)
I need to allow user to perform RegExp search on 35,000 strings
If I perform search using /ab.\*/ expression, then search takes less than a second
If I perform search using /.\*ab/ expression, then search takes around 10 seconds
My question is: How can I make second search faster (less then 1.5 seconds)?
Thank You very much | Use [compiled regular expressions](http://en.csharp-online.net/CSharp_Regular_Expression_Recipes%E2%80%94Compiling_Regular_Expressions) for better performance
<http://en.csharp-online.net/CSharp_Regular_Expression_Recipes>—Compiling\_Regular\_Expressions
copy paste the full url, looks like there is rendering problem with this link. | It’s how regular expressions are processed that makes them perform so different. To explain that based on your examples:
* **`/.*ab/`** This expression consists on two sub-expressions, the `.*` and the literal `ab`. This would be processed as follows: In the normal greedy mode, where every quantor and thus the match is expanded to its maximum, the `.*` will first match the whole string. Then it will try to match the following `ab`. But as it is not possible (we’re already at the end of the string) backtracking will be used to find the last point where both sub-expressions match. So the match of `.*` is reduced by one character and again the `ab` is tested. If the whole expression cannot be matched, the match of `.*` again will be reduced by one character until the whole expression is matched. In the worst case there is no `ab` in the string and the algorithm will do *n*+1 backtracks and additional tests for `ab` until it can determine that a match is impossible.
* **`/ab.*/`** This expression consists of two sub-expressions too. But here the order is changed, first the literal `ab` and than the `.*`. This is processed as follows: The algorithm first tries to find the literal `ab` by comparing one character by another. If there is a match, it tries to find a match for `.*` that is obvious easy.
The main difference between those two regular expressions is, that the second has the static part at the beginning and the variable part at the end. This makes no backtracking necessary.
Try some regular expression analysis tool such as [RegexBuddy](http://www.regexbuddy.com/) to see the difference visually. | .NET RegExp engine search performance optimization | [
"",
"c#",
".net",
"regex",
"performance",
"optimization",
""
] |
I am trying to enhance my Logger class with some conditionals to control what to log and where to log. I've got two kinds of logging functions:
```
public static class Logger
{
[Conditional("Logging"), Conditional("VerboseLogging")]
public static void Log(string msg, string filename)
{
// log to file
}
[Conditional("VerboseLogging")]
public static void VerboseLog(string msg, string filename)
{
Log(msg, filename); // just defer call to Log(string msg)
}
}
```
However, running the following program
```
#define Logging
#define VerboseLogging
static void Main(string[] args)
{
Logger.Log("Logging", "");
Logger.VerboseLog("VerboseLogging", "");
}
```
yields only the output "Logging", missing "VerboseLogging".
Debugging the application showed that VerboseLogging indeed does get called, but it does not call `Log(msg, filename)`. The debugger simply jumps right over the function call to the end of the `VerboseLog()` function.
When I remove the conditionals from the `Log(string msg)` method, it works.
Does anybody have a clue as to why this happens or what to do so it will be called? | Note that you need to define `Logging` and `VerboseLogging` in your `Logger` file also, because `VerboseLog` will not call `Log` if `Logging` is not defined there.
To add a project-wide conditional define, right click on your Project, and select Project Properties. Then go to the Build tab and enter "Logging, VerboseLogging" to the "Conditional compilation symbols" text box. | Are the conditionals not upside down there? i.e.
```
[Conditional("Logging")]
public static void Log(string msg, string filename) { }
[Conditional("Logging"), Conditional("VerboseLogging")]
public static void VerboseLog(string msg, string filename) {
Log(msg, filename); // just defers call to Log()
}
``` | Conditional method calling conditional method not working in C# | [
"",
"c#",
".net",
"debugging",
"logging",
"conditional-statements",
""
] |
Does anyone know of a good class to read in .ged files
Gedcom is a file format that is used to store genealogical information.
My goal is to write something that would let me import a ged file and export a .dot file for graphviz so that I can make a visual representation of a family tree
thanks if you can help | Heres my best attempt so far.
It seems to be working for what i need though its defiently not full proof ( then again my family tree is rather large and that adds some complexity)
please let me know if you think i could make anything more elequient
```
struct INDI
{
public string ID;
public string Name;
public string Sex;
public string BirthDay;
public bool Dead;
}
struct FAM
{
public string FamID;
public string type;
public string IndiID;
}
List<INDI> Individuals = new List<INDI>();
List<FAM> Family = new List<FAM>();
private void button1_Click(object sender, EventArgs e)
{
string path = @"C:\mostrecent.ged";
ParseGedcom(path);
}
private void ParseGedcom(string path)
{
//Open path to GED file
StreamReader SR = new StreamReader(path);
//Read entire block and then plit on 0 @ for individuals and familys (no other info is needed for this instance)
string[] Holder = SR.ReadToEnd().Replace("0 @", "\u0646").Split('\u0646');
//For each new cell in the holder array look for Individuals and familys
foreach (string Node in Holder)
{
//Sub Split the string on the returns to get a true block of info
string[] SubNode = Node.Replace("\r\n", "\r").Split('\r');
//If a individual is found
if (SubNode[0].Contains("INDI"))
{
//Create new Structure
INDI I = new INDI();
//Add the ID number and remove extra formating
I.ID = SubNode[0].Replace("@", "").Replace(" INDI", "").Trim();
//Find the name remove extra formating for last name
I.Name = SubNode[FindIndexinArray(SubNode, "NAME")].Replace("1 NAME", "").Replace("/", "").Trim();
//Find Sex and remove extra formating
I.Sex = SubNode[FindIndexinArray(SubNode, "SEX")].Replace("1 SEX ", "").Trim();
//Deterine if there is a brithday -1 means no
if (FindIndexinArray(SubNode, "1 BIRT ") != -1)
{
// add birthday to Struct
I.BirthDay = SubNode[FindIndexinArray(SubNode, "1 BIRT ") + 1].Replace("2 DATE ", "").Trim();
}
// deterimin if there is a death tag will return -1 if not found
if (FindIndexinArray(SubNode, "1 DEAT ") != -1)
{
//convert Y or N to true or false ( defaults to False so no need to change unless Y is found.
if (SubNode[FindIndexinArray(SubNode, "1 DEAT ")].Replace("1 DEAT ", "").Trim() == "Y")
{
//set death
I.Dead = true;
}
}
//add the Struct to the list for later use
Individuals.Add(I);
}
// Start Family section
else if (SubNode[0].Contains("FAM"))
{
//grab Fam id from node early on to keep from doing it over and over
string FamID = SubNode[0].Replace("@ FAM", "");
// Multiple children can exist for each family so this section had to be a bit more dynaimic
// Look at each line of node
foreach (string Line in SubNode)
{
// If node is HUSB
if (Line.Contains("1 HUSB "))
{
FAM F = new FAM();
F.FamID = FamID;
F.type = "PAR";
F.IndiID = Line.Replace("1 HUSB ", "").Replace("@","").Trim();
Family.Add(F);
}
//If node for Wife
else if (Line.Contains("1 WIFE "))
{
FAM F = new FAM();
F.FamID = FamID;
F.type = "PAR";
F.IndiID = Line.Replace("1 WIFE ", "").Replace("@", "").Trim();
Family.Add(F);
}
//if node for multi children
else if (Line.Contains("1 CHIL "))
{
FAM F = new FAM();
F.FamID = FamID;
F.type = "CHIL";
F.IndiID = Line.Replace("1 CHIL ", "").Replace("@", "");
Family.Add(F);
}
}
}
}
}
private int FindIndexinArray(string[] Arr, string search)
{
int Val = -1;
for (int i = 0; i < Arr.Length; i++)
{
if (Arr[i].Contains(search))
{
Val = i;
}
}
return Val;
}
``` | There is a very pretty one at Codeplex: [FamilyShow](http://familyshow.codeplex.com/) (a WPF showcase). It imports/exports GEDCOM 5.5 and there is source. | Gedcom Reader for C# | [
"",
"c#",
"genealogy",
"gedcom",
""
] |
I am running Python 2.5.
This is my folder tree:
```
ptdraft/
nib.py
simulations/
life/
life.py
```
(I also have `__init__.py` in each folder, omitted here for readability)
How do I import the `nib` module from inside the `life` module? I am hoping it is possible to do without tinkering with sys.path.
Note: The main module being run is in the `ptdraft` folder. | It seems that the problem is not related to the module being in a parent directory or anything like that.
You need to add the directory that contains `ptdraft` to PYTHONPATH
You said that `import nib` worked with you, that probably means that you added `ptdraft` itself (not its parent) to PYTHONPATH. | You could use relative imports (Python >= 2.5):
```
from ... import nib
```
[(What’s New in Python 2.5) PEP 328: Absolute and Relative Imports](http://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports) | Importing modules from parent folder | [
"",
"python",
"module",
"path",
"directory",
"python-import",
""
] |
I'm changing an IFRAME's `src` in order to reload it, its working fine and firing the `onload` event when its HTML loads.
But it adds an entry to the history, which I don't want. Is there any way to reload an IFRAME and yet not affect the history? | You can use javascript [`location.replace`](https://developer.mozilla.org/en/window.location):
```
window.location.replace('...html');
```
> Replace the current document with the
> one at the provided URL. The
> difference from the assign() method is
> that after using replace() the current
> page will not be saved in session
> history, meaning the user won't be
> able to use the Back button to
> navigate to it. | Using replace() is only an option with your own domain iframes. It fails to work on remote sites (eg: a twitter button) and requires some browser-specific knowledge to reliably access the child window.
Instead, just remove the iframe element and construct a new one in the same spot. History items are only created when you modify the `src` attribute after it is in the DOM, so make sure to set it before the append.
Edit: JDandChips rightly mentions that you can remove from DOM, modifiy, and re-append. Constructing fresh is not required. | Reload an IFRAME without adding to the history | [
"",
"javascript",
"html",
"iframe",
"browser-history",
""
] |
This is a simplified version of the original problem.
I have a class called Person:
```
public class Person {
public string Name { get; set; }
public int Age { get; set; }
public int Weight { get; set; }
public DateTime FavouriteDay { get; set; }
}
```
...and lets say an instance:
```
var bob = new Person {
Name = "Bob",
Age = 30,
Weight = 213,
FavouriteDay = '1/1/2000'
}
```
I would like to write the following as a *string* in my favourite text editor....
```
(Person.Age > 3 AND Person.Weight > 50) OR Person.Age < 3
```
I would like to take this string and my object instance and evaluate a TRUE or FALSE - i.e. evaluating a Func<Person, bool> on the object instance.
Here are my current thoughts:
1. Implement a basic grammar in ANTLR to support basic Comparison and Logical Operators. I am thinking of copying the Visual Basic precedence and some of the featureset here: <http://msdn.microsoft.com/en-us/library/fw84t893(VS.80).aspx>
2. Have ANTLR create a suitable AST from a provided string.
3. Walk the AST and use the [Predicate Builder](http://www.albahari.com/nutshell/predicatebuilder.aspx) framework to dynamically create the Func<Person, bool>
4. Evaluate the predicate against an instance of Person as required
**My question is have I totally overbaked this? any alternatives?**
---
## EDIT: Chosen Solution
I decided to use the Dynamic Linq Library, specifically the Dynamic Query class provided in the LINQSamples.
Code below:
```
using System;
using System.Linq.Expressions;
using System.Linq.Dynamic;
namespace ExpressionParser
{
class Program
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public int Weight { get; set; }
public DateTime FavouriteDay { get; set; }
}
static void Main()
{
const string exp = @"(Person.Age > 3 AND Person.Weight > 50) OR Person.Age < 3";
var p = Expression.Parameter(typeof(Person), "Person");
var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p }, null, exp);
var bob = new Person
{
Name = "Bob",
Age = 30,
Weight = 213,
FavouriteDay = new DateTime(2000,1,1)
};
var result = e.Compile().DynamicInvoke(bob);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
```
Result is of type System.Boolean, and in this instance is TRUE.
Many thanks to Marc Gravell.
Include [System.Linq.Dynamic](https://www.nuget.org/packages/System.Linq.Dynamic/) nuget package, documentation [here](https://github.com/kahanu/System.Linq.Dynamic/wiki/Dynamic-Expressions) | Would the [dynamic linq library](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) help here? In particular, I'm thinking as a `Where` clause. If necessary, put it inside a list/array just to call `.Where(string)` on it! i.e.
```
var people = new List<Person> { person };
int match = people.Where(filter).Any();
```
If not, writing a parser (using `Expression` under the hood) isn't hugely taxing - I wrote one similar (although I don't think I have the source) in my train commute just before xmas... | Another such library is [Flee](http://flee.codeplex.com/)
I did a quick comparison of [Dynamic Linq Library](http://msdn2.microsoft.com/en-us/vcsharp/bb894665.aspx) and [Flee](http://flee.codeplex.com/) and Flee was 10 times faster for the expression `"(Name == \"Johan\" AND Salary > 500) OR (Name != \"Johan\" AND Salary > 300)"`
This how you can write your code using Flee.
```
static void Main(string[] args)
{
var context = new ExpressionContext();
const string exp = @"(Person.Age > 3 AND Person.Weight > 50) OR Person.Age < 3";
context.Variables.DefineVariable("Person", typeof(Person));
var e = context.CompileDynamic(exp);
var bob = new Person
{
Name = "Bob",
Age = 30,
Weight = 213,
FavouriteDay = new DateTime(2000, 1, 1)
};
context.Variables["Person"] = bob;
var result = e.Evaluate();
Console.WriteLine(result);
Console.ReadKey();
}
``` | How to convert a String to its equivalent LINQ Expression Tree? | [
"",
"c#",
"lambda",
"antlr",
"dsl",
"predicate",
""
] |
I understand how to use Dynamic Proxies in Java but what I don't understand is how the VM actually creates a dynamic proxy. Does it generate bytecode and load it? Or something else? Thanks. | At least for Sun's implementation, if you look at the source code of `java.lang.reflect.Proxy` you'll see that yes, it generates the byte code on-the-fly (using the class `sun.misc.ProxyGenerator`). | I suggest that you read [Dynamic Proxy Classes](http://docs.oracle.com/javase/8/docs/technotes/guides/reflection/proxy.html):
> The Proxy.getProxyClass method returns
> the java.lang.Class object for a proxy
> class given a class loader and an
> array of interfaces. The proxy class
> will be defined in the specified class
> loader and will implement all of the
> supplied interfaces. If a proxy class
> for the same permutation of interfaces
> has already been defined in the class
> loader, then the existing proxy class
> will be returned; ***otherwise, a proxy
> class for those interfaces will be
> generated dynamically and defined in
> the class loader.*** [emphasis mine] | How does Java's Dynamic Proxy actually work? | [
"",
"java",
"proxy",
""
] |
What are the best practices regarding the use and structure of inner classes in C#.
For instance if I have a very large base class and two large inner classes should I split them up into separate (partial class) codefiles or leave them as one very large unwieldy codefile?
Also is it bad practice to have an abstract class, with a public inherited inner class? | Typically I reserve inner-classes for one of two purposes:
1. Public classes which derive from their parent class where the parent class is an abstract base implementation with one or more abstract methods and each subclass is an implementation which serves a specific implementation. *after reading Framework Design and Guidelines I see that this is marked as "Avoid", however I use it in scenarios similar to enums--althogh that's probably giving a bad impression as well*
2. The inner classes are private and are units of business logic or otherwise tightly coupled to their parent class in a manner in which they are fundamentally broken when consumed or used by any other class.
For all other cases I try to keep them in the same namespace and the same accessibility level as their consumer/logical parent--often with names that are a little less friendly than the "main" class.
On big projects you'd be surprised how often you may find yourself initially building a strongly-coupled component just because it's first or primary purpose makes it seem logical--however unless you have a very good or technical reason to lock it down and hide it from sight then there is little harm in exposing the class so that other components can consume it.
**Edit** Keep in mind that even though we're talking about sub-classes they should be more-or-less well designed and loosely coupled components. Even if they are private and invisible to the outside world keeping a minimal "surface area" between classes will greatly ease the maintainability of your code for future expansion or alteration. | I don't have the book to hand, but the Framework Design Guidelines suggests using `public` inner classes as long as clients don't have to refer to the class name. `private` inner classes are fine: nobody's going to notice these.
**Bad:** `ListView.ListViewItemCollection collection = new ListView.ListViewItemCollection();`
**Good:** `listView.Items.Add(...);`
Regarding your large class: it's generally worthwhile splitting something like this into smaller classes, each with one specific piece of functionality. It's difficult to break it up initially, but I predict it'll make your life easier later on... | Using Inner classes in C# | [
"",
"c#",
"inner-classes",
""
] |
We are building a system that interacts with an external system over TCP/IP using the [FIX Protocol](http://en.wikipedia.org/wiki/FIX_protocol). I've used WCF to communicate from client to server, where I had control over both client and server, but never to an external TCP/IP based system. Is this possible with WCF? If so, could the community provide links for me to get started and faced in the right direction?
Unfortunately I do not have much more information that what is supplied above, as we are still in the early early planning stages. What we know is that we have an external vendor whose system will communicate with our system over TCP/IP. We would like to use this as a learning opportunity and learn WCF. | I don't think it is possible, at least it won't be easy to set it up because you don't know the communication protocol of the other end, except for it's TCP and accept FIX tags.
Why don't you within WCF application open TCP connection a SOCKET. That should do the trick in a simpler manner. | Possible? Possibly yes, but it's going to take some work.
For starters, you will need to write a custom WCF Transport Channel that handles the specifics of your TCP/IP based protocols (i.e. you'll need to write all the socket handling code and hook that into the WCF channel model). This is because the TCP channel in WCF isn't for this kind of work, but uses a relatively proprietary and undocumented wire protocol.
I'm not familiar enough with FIX to say how complex it would be, but there are some gotchas when writing WCF channels and documentation in that area isn't great.
The second part you'll need to deal with is message encoding. To WCF, all messages are XML. That is, once a message is passed on to the WCF stack, it has to look like an XML infoset at runtime. FIX doesn't use XML (afaik), so you'll need to adapt it a bit.
There are two ways you can go around it:
1. The easy way: Assume the server/client will use a specific interface and format for the data, and have your channel do all the hard work of translating the FIX messages to/from that format. The simplest example of this would be to have your WCF code use a simple service contract with one method taking a string and then just encapsulating the FIX message string into the XML format that satisfies the data contract serializer for that contract. The user code would still need to deal with decoding the FIX format later, though.
2. Do all the hard work in a custom WCF MessageEncoder. It's a bit more complex, but potentially cleaner and more reusable (and you could do more complex things like better streaming and so on).
The big question though is whether this is worth it. What is your reasoning for wanting to use WCF for this? Leveraging the programming model? I think that's an important consideration, but also keep in mind that the abstractions that WCF provides come at a price. In particular, some aspects of WCF can be problematic if you have very real-time requirements, which I understand is common in the kind of financial environment you're looking at.
If that's the case, it may very well be that you'd be better served by skipping WCF and sticking a little closer to the metal. You'll need to do the socket work anyway, so that's something to consider there.
Hope this helps :) | Is it possible to communicate with an external system over TCP/IP using WCF? | [
"",
"c#",
".net",
"wcf",
"tcp",
"fix-protocol",
""
] |
Started working on Firefox add ons, which is done with JavaScript and XUL, and I find myself sorely wanting to use Dojo or someother kind of JavaScript like library, but I can't find one that exists. So I was thinking of starting a library by porting Dojo over to a Firefox add on specific fork. Get rid off the cross browser stuff, use array comprehension and other nice stuff available in Firefox's JavaScript engine. I worry about whether or not there's enough of a userbase who'd take advantage of this, but more than that I guess I'm wondering if there's already something like this? Google finds nothing. | Mozilla Corp developed a JavaScript library for this purpose: [FUEL](https://developer.mozilla.org/en/FUEL).
it is developed by John Resig the creator of jQuery.
To know how to use jQuery inside FF extension look at this similar [question](https://stackoverflow.com/questions/491490/how-to-use-jquery-in-firefox-extension) | jQuery, at least, functions perfectly well when embedded in a Firefox addon. I can't quote you names, but I've heard that several popular addons are already using jQuery.
Here's [an article](http://digitalmihailo.blogspot.com/2008/05/jquery-and-dynamic-html-in-xul.html) discussing using jQuery within XUL and some of the hoops you may need to jump through. | Is there a dojo or a Jquery just for Firefox add on development? | [
"",
"firefox-addon",
"javascript",
""
] |
I need to read the number of lines in a file before doing some operations on that file. When I try to read the file and increment the `line_count` variable at each iteration until I reach `EOF`. It was not that fast in my case. I used both `ifstream` and `fgets`. They were both slow. Is there a hacky way to do this, which is also used by, for instance BSD, Linux kernel or berkeley db (may be by using bitwise operations).
The number of lines is in the millions in that file and it keeps getting larger, each line is about 40 or 50 characters. I'm using Linux.
**Note:**
I'm sure there will be people who might say use a DB idiot. But briefly in my case I can't use a db. | The only way to find the line count is to read the whole file and count the number of line-end characters. The fastest way to do this is probably to read the whole file into a large buffer with one read operation and then go through the buffer counting the '\n' characters.
As your current file size appears to be about 60Mb, this is not an attractive option. You can get some of the speed by not reading the whole file, but reading it in chunks, say of size 1Mb. You also say that a database is out of the question, but it really does look to be the best long-term solution.
**Edit:** I just ran a small benchmark on this and using the buffered approach (buffer size 1024K) seems to be a bit more than twice as fast as reading a line at a time with `getline()`. Here's the code - my tests were done with g++ using `-O2` optimisation level:
```
#include <iostream>
#include <fstream>
#include <vector>
#include <ctime>
using namespace std;
unsigned int FileRead( istream & is, vector <char> & buff ) {
is.read( &buff[0], buff.size() );
return is.gcount();
}
unsigned int CountLines( const vector <char> & buff, int sz ) {
int newlines = 0;
const char * p = &buff[0];
for ( int i = 0; i < sz; i++ ) {
if ( p[i] == '\n' ) {
newlines++;
}
}
return newlines;
}
int main( int argc, char * argv[] ) {
time_t now = time(0);
if ( argc == 1 ) {
cout << "lines\n";
ifstream ifs( "lines.dat" );
int n = 0;
string s;
while( getline( ifs, s ) ) {
n++;
}
cout << n << endl;
}
else {
cout << "buffer\n";
const int SZ = 1024 * 1024;
std::vector <char> buff( SZ );
ifstream ifs( "lines.dat" );
int n = 0;
while( int cc = FileRead( ifs, buff ) ) {
n += CountLines( buff, cc );
}
cout << n << endl;
}
cout << time(0) - now << endl;
}
``` | Don't use C++ stl strings and `getline` ( or C's fgets), just C style raw pointers and either block read in page-size chunks or mmap the file.
Then scan the block at the native word size of your system ( ie either `uint32_t` or `uint64_t`) using one of the [magic algorithms](http://aggregate.org/MAGIC/#SIMD%20Within%20A%20Register%20(SWAR)%20Operations) 'SIMD Within A Register (SWAR) Operations' for testing the bytes within the word. An example is [here](http://www.tincancamera.com/examples/wide-finder/src/tbray9.cpp.txt); the loop with the `0x0a0a0a0a0a0a0a0aLL` in it scans for line breaks. ( that code gets to around 5 cycles per input byte matching a regex on each line of a file )
If the file is only a few tens or a hundred or so megabytes, and it keeps growing (ie something keeps writing to it), then there's a good likelihood that linux has it cached in memory, so it won't be disk IO limited, but memory bandwidth limited.
If the file is only ever being appended to, you could also remember the number of lines
and previous length, and start from there.
---
It has been pointed out that you could use mmap with C++ stl algorithms, and create a functor to pass to std::foreach. I suggested that you shouldn't do it not because you can't do it that way, but there is no gain in writing the extra code to do so. Or you can use boost's mmapped iterator, which handles it all for you; but for the problem the code I linked to was written for this was much, much slower, and the question was about speed not style. | Fastest way to find the number of lines in a text (C++) | [
"",
"c++",
"line-count",
""
] |
I've been programming in Delphi with Midas/DataSnap for quite long time and quite happy with it. Moving to .NET I'm more than happy with the ADO.NET DataSet. For CRUD application, I'm highly uncomfortable with any kind of ORM. Generic data-structure with automatic diff/delta handling get my job done better for me, an average database application developer.
Tried to study Java years ago, and could not find similar idea implemented. The closest I could find is SDO (Service Data Object). I thought it should be widely adopted when I saw it, but I'm wrong. Even the spec is rather old now, I still hardly find many people discuss on it or use it extensively. Assuming from information I can find on the internet, SDO usage is highly passive.
Wondering if it's dying ? Any experience in SDO you want to share ? Manual DTO coding is always better ? | Ok. I see. The answer is "no"
;) | Same for me when trying SDO first time. Old specs, passive feedback... Definitely NO. | Should SDO (Service Data Object) be adopted in new project? | [
"",
"java",
"web-services",
"dto",
"sdo",
""
] |
I have a web application written in Java (Spring, Hibernate/JPA, Struts2) where users can upload images and store them in the file system. I would like to scale those images so that they are of a consistent size for display on the site. What libraries or built in functions will offer the best results? I will consider the following criteria in making my decision (in this order):
* Free/Open Source (essential)
* Easy to implement
* Quality of results
* Performance
* Size of executable | Have a look at the [Java Image I/O API](http://java.sun.com/j2se/1.4.2/docs/guide/imageio/index.html) to read/write the image. Then use [AffineTransform](http://java.sun.com/j2se/1.4.2/docs/api/java/awt/geom/AffineTransform.html) to resize.
Also, [here's](http://www.java2s.com/Code/Java/2D-Graphics-GUI/Imagescale.htm) a complete example using java.awt.Image. | I would really recommend giving imgscalr a look.
It is released under an Apache 2 license, hosted on [GitHub](https://github.com/thebuzzmedia/imgscalr), been deployed in a handful of web applications already, has a very simple, but pedantically documented API, has code that works around 2 major image bugs in the JDK for you transparently that you'll only ever notice if you suddenly start getting "black" images after a scale operation or horrible-looking results, gives you the best possible looking results available in Java, is available via Maven as well as a ZIP and is just a single class.
Basic use looks like this:
```
BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, 320);
```
This is the simplest call where the library will make a best-guess at the quality, honor your image proportions, and fit the result within a 320x320 bounding box. NOTE, the bounding box is just the maximum W/H used, since your image proportions are honored, the resulting image would still honor that, say 320x200.
If you want to override the automatic mode and force it to give you the best-looking result and even apply a very mild anti-alias filter to the result so it looks even better (especially good for thumbnails), that call would look like:
```
BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, Method.QUALITY,
150, 100, Scalr.OP_ANTIALIAS);
```
These are all just examples, the API is broad and covers everything from super-simple use cases to very specialized. You can even pass in your own BufferedImageOps to be applied to the image (and the library automatically fixes the 6-year BufferedImageOp JDK bug for you!)
There is a lot more to scaling images in Java successfully than the library does for you, for example always keeping the image in one of the best supported RGB or ARGB image types while operating on it. Under the covers the Java2D image processing pipeline falls back to an inferior software pipeline if the image type used for any image operations is poorly supported.
If all that sounded like a lot of headaches, it sort of is... that's why I wrote the library and open-sourced it, so folks could just resize their images and move on with their lives without needing to worry about it.
Hope that helps. | What is the best way to scale images in Java? | [
"",
"java",
"image",
"web-applications",
"graphics",
"image-scaling",
""
] |
I keep getting the following exception on one of our live servers (the others running the same code seem ok):
```
java.lang.RuntimeException: XPathFactory#newInstance() failed to create an XPathFactory for the default object model: http://java.sun.com/jaxp/xpath/domwith the XPathFactoryConfigurationException: javax.xml.xpath.XPathFactoryConfigurationException: No XPathFctory implementation found for the object model: http://java.sun.com/jaxp/xpath/dom
at javax.xml.xpath.XPathFactory.newInstance(XPathFactory.java:67)
```
I'm pretty sure that I have the Xalan and Saxon jars in the classpath (using IBM Java 1.5).
Do you have any Ideas what else could be wrong?
**Edit:**
That's the code that causes the Problem:
```
XPathFactory factory = XPathFactory.newInstance();
```
And it's running on a custom web server that's roughly based on the catalina engine. | Found the answer myself: The problem is the combination of using Java 5 and having an option
```
-Djava.endorsed.dirs
```
set to a directory that contained the xalan.jar.
Once removed everything works again. | You need to add the appropriate .jar in your classpath. In my case I used the Saxon-HE library.
[There exists a bug in Saxon9 you maybe run into like me.](https://saxonica.plan.io/issues/1944)
The bug has been corrected in version 9.5.1.5. So you may download the [latest Saxon 9 HE](http://saxon.sourceforge.net/). | Classpath issue using XPathFactory | [
"",
"java",
"classpath",
""
] |
I need to test whether the value of a form's `onsubmit` is a function. The format is typically `onsubmit="return valid();"`. Is there a way to tell if this is a function, and if it's callable? Using typeof just returns that it's a string, which doesn't help me much.
**EDIT**: Of course, I understand that "return valid();" is a string. I've `replace`d it down to "valid();", and even "valid()". I want to know if either of those is a function.
**EDIT**: Here's some code, which may help explain my problem:
```
$("a.button").parents("form").submit(function() {
var submit_function = $("a.button").parents("form").attr("onsubmit");
if ( submit_function && typeof( submit_function.replace(/return /,"") ) == 'function' ) {
return eval(submit_function.replace(/return /,""));
} else {
alert("onSubmit is not a function.\n\nIs the script included?"); return false;
}
} );
```
**EDIT 2**: Here's the new code. It seems that I still have to use an eval, because calling form.submit() doesn't fire existing onsubmits.
```
var formObj = $("a.button").parents("form");
formObj.submit(function() {
if ( formObj[0].onsubmit && typeof( formObj.onsubmit ) == 'function' ) {
return eval(formObj.attr("onsubmit").replace(/return /,""));
} else {
alert("onSubmit is not a function.\n\nIs the script included?");
return false;
}
} );
```
Suggestions on possibly how to do this better? | > I'm replacing a submit button with an
> anchor link. Since calling
> form.submit() does not activate
> onsubmit's, I'm finding it, and
> eval()ing it myself. But I'd like to
> check if the function exists before
> just eval()ing what's there. – gms8994
```
<script type="text/javascript">
function onsubmitHandler() {
alert('running onsubmit handler');
return true;
}
function testOnsubmitAndSubmit(f) {
if (typeof f.onsubmit === 'function') {
// onsubmit is executable, test the return value
if (f.onsubmit()) {
// onsubmit returns true, submit the form
f.submit();
}
}
}
</script>
<form name="theForm" onsubmit="return onsubmitHandler();">
<a href="#" onclick="
testOnsubmitAndSubmit(document.forms['theForm']);
return false;
"></a>
</form>
```
EDIT : missing parameter f in function testOnsubmitAndSubmit
The above should work regardless of whether you assign the `onsubmit` HTML attribute or assign it in JavaScript:
```
document.forms['theForm'].onsubmit = onsubmitHandler;
``` | Try
```
if (this.onsubmit instanceof Function) {
// do stuff;
}
``` | Testing if value is a function | [
"",
"javascript",
"typeof",
"onsubmit",
""
] |
I'm trying to move a primary key constraint to a different column in oracle. I tried this:
```
ALTER TABLE MY_TABLE
DROP CONSTRAINT c_name;
ALTER TABLE MY_TABLE
ADD CONSTRAINT c_name PRIMARY KEY
(
"COLUMN_NAME"
) ENABLE;
```
This fails on the add constraint with an error saying the the constraint already exists even though i just dropped it. Any ideas why this is happening | If the original constraint was a primary key constraint, Oracle creates an index to enforce the constraint. This index has the same name as the constraint (C\_NAME in your example). You need to drop the index separately from the constraint. So you will need to do a :
```
ALTER TABLE <table1> DROP CONSTRAINT C_NAME;
DROP INDEX C_NAME;
ALTER TABLE <table1> ADD CONSTRAINT C_NAME PRIMARY KEY
( COLUMN_2 ) ENABLE;
``` | The safest way is to first add a unique index. Try this:
```
create unique index new_pk on <tabname> (column_2);
```
Then drop the old PK:
```
alter table <tabname> drop primary key drop index;
```
(Optional) Rename the index:
```
alter index new_pk rename to c_name;
```
And then add the PK again indicating the index to be used:
```
alter table <tabname> add constraint c_name
primary key (column_2) using index c_name;
``` | Dropping then adding a constraint fails in oracle | [
"",
"sql",
"oracle",
""
] |
I am using Ajax and hash for navigation.
Is there a way to check if the `window.location.hash` changed like this?
<http://example.com/blah>**#123** to <http://example.com/blah>**#456**
It works if I check it when the document loads.
But if I have #hash based navigation it doesn't work when I press the back button on the browser (so I jump from blah#456 to blah#123).
It shows inside the address box, but I can't catch it with JavaScript. | The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.
---
Update to keep this answer fresh:
If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.
```
$(window).on('hashchange', function() {
//.. work ..
});
```
The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature [jQuery special events](http://benalman.com/news/2010/03/jquery-special-events/).
With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).
In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.
This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that [when somebody else has already](http://benalman.com/projects/jquery-hashchange-plugin/). | HTML5 [specifies a `hashchange` event](http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#history-traversal). This event is now [supported by all modern browsers](http://caniuse.com/hashchange). Support was added in the following browser versions:
* Internet Explorer 8
* Firefox 3.6
* Chrome 5
* Safari 5
* Opera 10.6 | How can I detect changes in location hash? | [
"",
"javascript",
"ajax",
"dom-events",
"fragment-identifier",
"hashchange",
""
] |
I want to write a small program that given a time (in minutes) as input, sleeps in the background for that time, and then forces a return to the "switch user screen" (equivalent to the Winkey+L combination) or logs off a user (may be another user logged in on the same machine).
What functions or libraries in Python could I use for this?
Edit:
* I prefer just a return to the "Switch User" screen rather than actually logging off
* Perhaps there's a simple Windows command to do this, which I could use
* I have Windows XP if that's relevant | There seems to be a simple way of locking a computer using no Python libraries except for ctypes:
```
import ctypes
ctypes.windll.user32.LockWorkStation ()
```
Source: [Tim Golden's Python Stuff](http://timgolden.me.uk/python/win32_how_do_i/lock_my_workstation.html) | To switch users, you can use this **Win32 API** function `WTSDisconnectSession(HANDLE hServer, DWORD SessionId, BOOL bWait)`
```
#include "WtsApi32.h"
BOOL OsofemSwitchUser()
{
//Switch User
return WTSDisconnectSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, TRUE);
}
```
Remember to link it to the `WtsApi32.lib` library.
This will return you to the Switch User screen... Hope this help... | Logout or switch user in Windows using Python | [
"",
"python",
"windows",
""
] |
I want to check if a variable exists. Now I'm doing something like this:
```
try:
myVar
except NameError:
# Do something.
```
Are there other ways without exceptions? | To check the existence of a local variable:
```
if 'myVar' in locals():
# myVar exists.
```
To check the existence of a global variable:
```
if 'myVar' in globals():
# myVar exists.
```
To check if an object has an attribute:
```
if hasattr(obj, 'attr_name'):
# obj.attr_name exists.
``` | The use of variables that have yet to been defined or set (implicitly or explicitly) is often a bad thing, since it tends to indicate that the logic of the program hasn't necessarily been thought through completely, and is likely to result in unpredictable behaviour.
If you *do* need to do it in Python, the following trick, which is similar to yours, will ensure that a variable has *some* value before use:
```
try:
myVar
except NameError:
myVar = None # or some other default value.
# Now you're free to use myVar without Python complaining.
```
The value you choose to give it will, of course, depend on what you want to do in such a case. For example, it it was a starting value for some accumulator, you would set it to zero.
---
However (and this is my opinion), it would probably be better to refactor your code so that this situation does not occur.
By way of an example, the following code was given a comment to this answer, to allow line drawing from a previous point to the current point:
```
if last:
draw(last, current);
last = current
```
In the case where `last` has not been bound to a value, that won't help in Python at all since even the *checking* of `last` will raise an exception. A better idea would be to ensure `last` *does* have a value, one that can be used to decide whether or not it is valid. That would be something like:
```
last = None
# some time passes ...
if last is not None:
draw(last, current);
last = current
```
That ensures the variable exists and that you only use it if it's valid for what you need it for.
You can still add the code to *force* this (if you have no control over the initial setting of the variable) by using the exception method given above:
```
# Variable 'last' may or may not be bound to a value at this point.
try:
last
except NameError:
last = None
# It will always now be bound to a value at this point.
if last is not None:
draw(last, current);
last = current
``` | How do I check if a variable exists? | [
"",
"python",
"exception",
"variables",
""
] |
> **Possible Duplicate:**
> [When do you use the “this” keyword?](https://stackoverflow.com/questions/23250/when-do-you-use-the-this-keyword)
Hello,
I understand that the `This` keyword is used to refer to an instance of the class, however, suppose I have a class called `Life`, which defines two fields, the person (*their name*) and their partner(*their name*):
```
class Life
{
//Fields
private string _person;
private string _partner;
//Properties
public string Person
{
get { return _person; }
set { _person = value; }
}
public string Partner
{
get { return _partner; }
set { _partner = value; }
}
//Constructor 1
public Life()
{
_person = "Dave";
_partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
//Constructor 2
public Life()
{
this._person = "Dave";
this._partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
}
```
Is there a difference between constructor 1 and constructor 2!?
Or is it just better coding practice to use the "This" keyword?
Regards | The constructors are the same. The reason I would prefer the second is that it will allow you to remove the underscores from your private variable names and retain the context (improving understandability). I make it a practice to always use `this` when referring to instance variables and properties.
I no longer use the `this` keyword in this way after moving to a different company with different standards. I've gotten used to it and now rarely use it at all when referring to instance members. I do still recommend using properties (obviously).
My version of your class:
```
class Life
{
//Fields
private string person;
private string partner;
//Properties
public string Person
{
get { return this.person; }
set { this.person = value; }
}
public string Partner
{
get { return this.partner; }
set { this.partner = value; }
}
public Life()
{
this.person = "Dave";
this.partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
}
```
or, even better, but not as clear about the use of `this` with fields.
```
class Life
{
//Properties
public string Person { get; set; }
public string Partner { get; set; }
public Life()
{
this.Person = "Dave";
this.Partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
}
``` | "this" is also used in .Net 3.5 with extension methods:
```
public static class MyExtensions
{
public static string Extend(this string text)
{
return text + " world";
}
}
```
would extend the string class
```
var text = "Hello";
text.Extend();
```
To answer your question: no, there is no difference in your two constructors. Imo, the "this" clutters the code and should only be used when necessary, e.g. when parameters and field variables have the same names.
There is also a case when the class explicitly implements an interface. If you need to call the interface methods from within your class you would have to cast this to the interface:
```
class Impl : IFace
{
public void DoStuff()
{
((IFace)this).SomeMethod();
}
void IFace.SomeMethod()
{
}
}
``` | C# When To Use "This" Keyword | [
"",
"c#",
"constructor",
"this",
""
] |
**I can't think of a good title, but my question is not as naive as it appears.**
Consider this:
```
public static void ExitApp(string message)
{
// Do stuff
throw new Exception(...);
}
```
OR
```
public static void ExitApp(string message)
{
// Do stuff
System.Environment.Exit(-1);
}
```
Neither of these methods will ever return. But when you invoke these methods elsewhere:
```
public int DoStuff()
{
// Do stuff
if (foo == 0)
{
throw new Exception(...);
}
else if (foo == 1)
{
// Do other stuff
return ...;
}
else
{
ExitApp("Something borked");
}
}
```
Try to compile that and you will get a "not all code paths return a value" in DoStuff. It seems silly to trail the call to ExitApp with an Exception just to satisfy the compiler even though I **know** that it's good. There seems to be nothing in ExitApp() that I can do to indicate it will never return.
**How can I indicate to the compiler that ExitApp never returns and, thus, that DoStuff's else block will never return either?** It seems like a rather simple bug that it's path checking fails to account for.
Even if I only use the first ExitApp (throws the exception) and that method returns an int the path checker is smart enough to realize that it will never return so it doesn't complain about the int type. This compiles file:
```
public static int ExitApp(string message)
{
// Do stuff
throw new Exception(...);
}
```
However, given that it knows this ExitApp will never return an int it does not extrapolate that to DoStuff() so I'm inclined to believe there is no solution to my question. My only choice is to throw an exception after calling ExitApp.
```
public int DoStuff()
{
...
else
{
ExitApp("Something borked");
throw new NotImplementedException("Should not reach this");
}
}
```
**Is there a reason for this behavior by the compiler?** | I have an exception defined for this purpose: UnreachableException. It might seem superfluous, but it's an easy way to say "Hey, person reading this, this line should never be executed!". I usually use it for the default case of some switch statements, but it applies here as well.
Just throw one after the ExitApp line.
```
public void int DoStuff()
{
// Do stuff
if (foo == 0)
{
throw new Exception(...);
}
else if (foo == 1)
{
// Do other stuff
return ...;
}
else
{
ExitApp("Something borked");
throw new UnreachableException();
}
}
```
The actual reason the language doesn't support declaring a method which always throws is just: **it's not worth it**. The language developers don't have unlimited time to apply every feature we can think of. They have to prioritize.
I'm betting this is the first time you've run into this situation, and look: explicitly throwing an exception deals with the issue. Why would they bother dealing with such a rare, easy to bypass case? They could be spending that time implementing optional parameters, dynamic, or a bunch of other things that will be more useful and used more often than being able to say a function always throws an exception.
That's not to say it will never be implemented. This type of method information is exactly the type of thing contracts are great at specifying. So maybe it will be included with code contracts. | The C# compiler doesn't support exception reporting, like the Java compiler does. Because of this, the compiler doesn't know (outside of the context of the method itself) that the method is guaranteed to throw an exception on every invocation. | Not all code paths return, but compiler treats it as if all paths return | [
"",
"c#",
"compilation",
""
] |
I am trying to generate a specific link and accompanying html depednant on the existance of a file. The code I am using to do so:
```
if(file_exists('../images/'. $pk . '.jpg'))
{
$imageSrc = "../images/". $pk . ".jpg";
$imagehtml = htmlentities(json_encode("<img src=\"".$imageSrc."\" >"));
$screenshotLink = "<p><a href=\"#\" onclick=\"makewindows(\"$imagehtml\"); return false;\">View Screenshot</a>";
}
else {
$screenshotLink = '';
}
```
This results in the following, useless html:
```
<a href="#" onclick="makewindows(" "<img="" src="%5C%22..%5C/images%5C/160329461329.jpg%5C%22" >"="" );="" return="" false;="">View Screenshot</a>
```
I don't understand this, because the above is essentialy the same code as:
```
$html = htmlentities(json_encode($ARTICLE_DESC));
$imagehtml = htmlentities(json_encode("<img src='".$imageSrc."' >"));
echo "<a href='#' onclick=\"makewindows(" . $imagehtml . "); return false;\">
<img src='".$imageSrc."' width='".$imageSize["width"]."' height='".$imageSize["height"]."'></a>
<p><a href='#' onclick=\"makewindows(" . $html . "); return false;\">Click for full description </a></p>";
```
which produces the following html which works fine:
```
<a href="#" onclick='makewindows("<img src=\"..\/images\/160329461329.jpg\" >"); return false;'>
<img src="../images/160329461329.jpg" width="199" height="300"></a>
```
I know it has something to do with quotes, but I am not sure what exactly. | ```
$imagehtml = htmlspecialchars(json_encode('<img src="'.$imageSrc.'" >'), ENT_QUOTES);
$screenshotLink = '<p><a href="#" onclick="makewindows($imagehtml); return false;">View Screenshot</a>';
```
Why not use ticks? | Try this:
```
$imagehtml = htmlspecialchars(json_encode("<img src=\"".$imageSrc."\" >"), ENT_QUOTES);
$screenshotLink = "<p><a href=\"#\" onclick=\"makewindows($imagehtml); return false;\">View Screenshot</a>";
``` | quotes in html in php problem | [
"",
"php",
"html",
""
] |
I am using `preg_replace` to escape special characters:
```
$tmpStr=preg_replace("/\?/", "\?", $tmpStr);
$tmpStr=preg_replace("/\#/", "\#", $tmpStr);
$tmpStr=preg_replace("/\^/", "\^", $tmpStr);
$tmpStr=preg_replace("/\&/", "\&", $tmpStr);
$tmpStr=preg_replace("/\*/", "\*", $tmpStr);
$tmpStr=preg_replace("/\(/", "\(", $tmpStr);
$tmpStr=preg_replace("/\)/", "\)", $tmpStr);
$tmpStr=preg_replace("/\//", "\/", $tmpStr);
```
But I am not able to escape `$` using the same function:
```
$tmpStr=preg_replace("/\$/", "\$", $tmpStr);
```
And also when I use the above statement all the spaces get replaced by `$` and `$` is not getting escaped.
How do I escape the dollar sign correctly? | I would strongly recommend using [preg\_quote()](http://de.php.net/manual/en/function.preg-quote.php) instead. | The correct answer is that you must escape the backslash and the dollar sign in the regex using PHP's escape characters.
```
backslash = \\
dollar sign = \$
$tmpStr=preg_replace("/\\\$/", "\\$", $tmpStr);
```
This is useful for anyone that needs to match a string that contains a dollar sign. | How to escape $ in PHP using preg_replace? | [
"",
"php",
"regex",
"preg-replace",
""
] |
The solution to this [question](https://stackoverflow.com/questions/84716/is-there-a-better-way-to-create-an-object-oriented-class-with-jquery "question") suggested the use of John Resig's class implementation. This solution covers all my needs except:
How to declare a public global variable inside this class that can be accessed from outside?
I would like to establish something like the following:
```
var MyClass = Class.extend({
EVENT_NAME : 'event-name',
init : function() {
// ...
}
});
// Now another file can directly read this value without creating the class object
console.log( MyClass.EVENT_NAME );
``` | The "only" way to do what you want to do is to use a function as the "class". This way you are declaring a "class" whose public "static" members can be accessed. Something like this:
```
function MyObject() {
// constructor stuff here
}
MyObject.EVENT_NAME = "event_name";
console.log(MyObject.EVENT_NAME); // No need to instantiate MyObject
```
However, seems to me like you are mixing concepts from statically typed languages with Javascript's more dynamic stuff. Why would you want to access a member of an object that has not been created? | Declare it in the window context or don't use the 'var' keyword:
```
window.globalVar = somevalue
globalVar = somevalue
``` | Class variable in javascript class | [
"",
"javascript",
"jquery",
""
] |
I come from the asp.net world where we'd use an objectdatasource, hooked up to data access layer, and set it's ConflictDetection property to "CompareAllValues". There is an OldValuesParameterFormatString on the ObjectDataSource that you use to identify old value parameters.
The sql procedure that does an update would then require both new params and old params and that was it... Super simple to implement; the ODS handled the old values for you.
I've moved over to Linq to SQL and WinForms. I've created a WCF service that is our business layer and I have a stored procedure that will update some table. In the data context designer I see that there is an Update Check property on my class columns. I'm not directly updating the table from the class, rather I'm calling a stored procedure to do the update. Is there some way to retain the original values, perhaps from the data context, similar to they way an objectdatasource would? | Are you using stored procedures directly (through a `SqlCommand`) or through LINQ to SQL? LINQ to SQL supports using stored procs for all its database access. You might want to look at [Updating our Database using Stored Procedures](http://weblogs.asp.net/scottgu/archive/2007/08/23/linq-to-sql-part-7-updating-our-database-using-stored-procedures.aspx), part 7 of [Scott Guthrie](http://weblogs.asp.net/scottgu/)'s blog post series about LINQ to SQL. You can setup the use of sprocs through the DBML designer or in code using a `DataContext` partial class. The idea is that you send both the new and original values (e.g. `Name` and `OriginalName`) to the sproc so it can to its concurrency checking.
If you are using the sproc directly and not through LINQ to SQL, and all you want is to get the object's original values, you can obtain them by using `Table<T>.GetOriginalEntityState()` like this:
```
Order modifiedOrder = db.Orders.First(); // using first Order as example
modifiedOrder.Name = "new name"; // modifying the Order
Order originalOrder = db.Orders.GetOriginalEntityState(modifiedOrder);
``` | Not the answer you may be looking for, but since you mentioned using WCF as a business layer along with LINQ2SQL, I felt it is my obligation to point out this article for your reference:
<http://www.sidarok.com/web/blog/content/2008/05/26/linq-to-sql-with-wcf-in-a-multi-tiered-action-part-1.html>
While the article implements ASP.NET as the main presentation layer, but considering your background, it might actually make the article easier to understand.
I personally handled the same sort of development as you are doing right now (winforms for client, WCF for business logic layer, LINQ2SQL for data access), but being complete beginner to WCF & LINQ2SQL at the time, I basically forced to drop the original values retention. This article comes closest to your needs, though to be honest I've not seen anything that works with using stored procedures. | Concurrency with Linq To Sql Stored Procedures | [
"",
"sql",
"linq",
"wcf",
"linq-to-sql",
"concurrency",
""
] |
i have a page with a series of checkboxes that authenticated users can change. I need to make this page only editable by one person at a time. So if a user goes into it and edits one of the checkboxes, noone else can go into the page and change other checkboxes.
I thought about an edit page link and a readonly page link (all controls disabled), then set a database flag if user enters under edit mode, but my concern is i wouldn't know if the user changed something, then just x'd out of the browser/app, locking everyone else out.
This is an internal app to company. Has anybody done something like this?
Any ideas or thoughts or suggestions?
Thanks | We have this functionality on an older ASP app. The user will load data with some type of primary key. We put in a DB entry to "lock" that page. If they correctly move through the site, it will unlock the resources at that time.
Other users opening this page will receive indication that the page is locked and a read-only version is rendered.
It would be fairly trivial to code a unPageUnload AJAX call to reset the lock for browser closing. We don't find this to be much of an issue and old locks are just cleared by an evening process if more than 4 hours old.
Our situation is where the pages are tied to specific regions of data. If this is a general config screen, I think a more dynamic AJAX solution that pushed the updates back and pings for changes might make sense. You would have to decide if you want to disable changes from others after the first update is received or implement collision detection for the data.
Some type of hashing of the page data would probably make this easier to detect changes. | You do what you said, but add a client side timer which will ping the server and tell you they are still there. If you don't get a ping within x mins you could let a new user go into edit mode but perhaps warn them (or not). | How do i lock an asp.net page from multi-user editing? | [
"",
"c#",
"asp.net",
""
] |
I am coding a GM script, and one thing I realised that I'm doing repeatedly is doing the same code over and over again. Specifically, the style property.
```
function createButton() {
var a = document.createElement('a');
a.href = '#';
a.innerHTML = 'Print Topic';
a.style.position = 'absolute';
a.style.right = '3em';
a.style.top = '6em';
a.style.fontFamily = 'Arial,Helvetica,sans-serif';
a.style.fontWeight = 'bold';
a.style.fontSize = '125%';
a.style.background = '#777777 none repeat scroll 0 0';
a.style.color = 'white';
a.style.padding = '6px 12px';
document.body.insertBefore(a, document.body.lastChild);
}
```
As you can see in my sample code, I repeatedly wrote a.style a lot of times. Do you have techniques that you use to avoid this mess? Just for the sake of gracefulness.
THANKS --
Guys, here's the reduced code:
```
function createButton() {
var a = document.createElement('a');
var css = document.createElement('style');
css.type = 'text/css';
css.innerHTML = '#prt { position:absolute; right:3em; top: 6em; font-family: Arial,Helvetica,sans-serif; font-weight:bold; font-size:125%; background: #777777 none repeat scroll 0 0; color: white; padding: 6px 12px;}'
a.href = '#';
a.innerHTML = 'Print Topic';
a.id = 'prt';
document.body.insertBefore(a, document.body.lastChild);
document.body.appendChild(css);
}
```
LOL, that certainly looks better | Put the style attributes into CSS classes, then just dynamically swap the classes instead of doing each style attribute explicitly. | The not-very-good-but-possibly-better-than-the-original answer:
```
s = a.style;
s.position = "absolute";
...etc...
s.color = "white";
``` | How do you organize Javascript verboseness? | [
"",
"javascript",
"greasemonkey",
""
] |
I have an extremely simple script with PHP `exec`, calling `mysql` command:
```
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'mypass';
$db = 'job';
$file ='job_create.sql';
$mySQLDir='"C:\Program Files\MySQL\MySQL Server 5.1\bin\mysql"';
if ($dbpass != '') {
$cmd = $mySQLDir.' -h '.$dbhost.' --user='.$dbuser.' --password='.$dbpass.' < "'.dirname(__FILE__).'\\'.$file.'"';
} else {
$cmd = $mySQLDir.' -h '.$dbhost.' --user='.$dbuser.' < "'.dirname(__FILE__).'\\'.$file.'"';
}
// echo $cmd;
exec($cmd,$out,$retval);
```
I would expect that the above script calls `mysql` command, pass in the user authentication information and run the `job_create.sql` on the fly.
The only thing is that it doesn't work, in the sense that the `job_create.sq`l is not run properly. . I tried to call `mysql` command directly from command line using the below script,
```
bin\mysql.exe -h localhost --user=root --password=mypass < "job_create.sql"
```
and it works.
Any idea how to fix this?
**Edit: I call this script from PHP command line. i.e., PHP.exe installdb.php** | I found the solution
The problem is that you need to explicitly enclosed the `$cmd` in "".i.e.,
```
exec('"'.$cmd.'"',$out ,$retval);
```
This is the full code that works:
```
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$db = 'job';
$file =dirname(__FILE__).'\\'.'job_create.sql';
$mySQLDir='"C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysql.exe"';
if ($dbpass != '') {
$cmd = $mySQLDir.' -h '.$dbhost.' --user='.$dbuser.' --password='.$dbpass.' < "'.$file.'"';
} else {
$cmd = $mySQLDir.' -h '.$dbhost.' --user='.$dbuser.' < "'.$file.'"';
}
echo $cmd;
exec('"'.$cmd.'"',$out ,$retval);
echo "\n";
echo ($retval);
?>
``` | The problem here is probably that
```
mysql < file.sql
```
depends on a pipe operation that is facilitated by the shell. If php executes the command directly using something like the exec\*() family of api calls rather than through a shell this won't work. I know that the shell actually is used on linux, but this might not be the case on windows. The manual doesn't specify exactly how the command is executed.
Try using the -e flag and the source command instead:
```
bin\mysql.exe -h localhost --user=root --password=mypass -e 'source job_create.sql'
```
This should work regardless of the way that the command is invoked. | Calling MySQL exe using PHP exec doesn't work | [
"",
"php",
"mysql",
""
] |
In other words I have a thread that starts and calls `waitHandle.Set()` multiple times. Then I start several threads and each is waiting on that `WaitHandle`. Will X of the them be signaled where X is the number of times the original thread called `waitHandle.Set()`?
Is there a structure that supports what I'm trying to accomplish more closely? | Maybe, but probably not.
An event can only be set or unset, if there is nothing to unset the event then repeated calls to Set will not change its state, unless it is an auto-reset event and there is at least one thread waiting on it. With a manual reset event any threads waiting (or starting to wait) will be released until something unsets the event.
I think you will actually want a semaphore, which does have a count and supports setting *n* times to release *n* threads (even if some of those threads only start waiting after some of the calls to set). | It depends on the `EventResetMode`. If it is set to `EventResetMode.AutoReset` it will only release one thread. If it is 'EventResetMode.ManualReset' however it will release all threads blocked on the event.
```
Semaphore.Release(Int)
```
Where Int is the count would be **one** way to do this. | If you call EventWaitHandle.Set() X times, will it signal X threads if X the threads haven't started yet? | [
"",
"c#",
"multithreading",
""
] |
It appears to me that C++ does not allow member template specialization in any scope other than namespace and global scope (MS VSC++ Error C3412). But to me it makes sense to specialize a base class's primary member template in the derived class because that is what derived classes do - specialize things in the base class. For instance, consider the following example:
```
struct Base
{
template <class T>
struct Kind
{
typedef T type;
};
};
struct Derived : public Base
{
/* Not Allowed */
using Base::Kind;
template <>
struct Kind <float>
{
typedef double type;
};
};
int main(void)
{
Base::Kind<float>::type f; // float type desired
Derived::Kind<float>::type i; // double type desired but does not work.
}
```
My question is why isn't it allowed? | I get what you're trying to do, but you are not doing it right. Try this :
```
struct Base{};
struct Derived{};
// Original definition of Kind
// Will yield an error if Kind is not used properly
template<typename WhatToDo, typename T>
struct Kind
{
};
// definition of Kind for Base selector
template<typename T>
struct Kind<Base, T>
{
typedef T type;
};
// Here is the inheritance you wanted
template<typename T>
struct Kind<Derived, T> : Kind<Base, T>
{
};
// ... and the specialization for float
template<>
struct Kind<Derived, float>
{
typedef double type;
};
``` | > My question is why isn't it allowed?
From my copy of the draft it appears that the following puts the above restriction:
> In
> an explicit specialization declaration for a class template, a member of a class template or a class member
> template, the name of the class that is explicitly specialized shall be a simple-template-id.
The workaround is to specialize the enclosing class. | member template specialization and its scope | [
"",
"c++",
"templates",
"scope",
"specialization",
""
] |
I have a .htaccess file which arranges that all requests go through index.php.
Now i would like to make an exception for rss.php. to go straight throuh rss.php.
How do I do this?
This is how it looks like now:
```
RewriteEngine on
RewriteBase /
RewriteRule !\.(js|ico|txt|gif|jpg|png|css)$ index.php
```
Thanks. | Put this before the last line.
```
RewriteCond %{REQUEST_URI} !^/rss\.php$
``` | You can exclude any existing file with an additional [`RewriteCond` directive](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond):
```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
``` | .htaccess file modification | [
"",
"php",
".htaccess",
""
] |
I get the error in question when I attempt to create a project. I followed the instructions found at [how to install python an django in windows vista](http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/). | Also make sure that you have permission to access all of django's files. I've seen these kinds of errors happen because of permissions issues before.
**EDIT**: I haven't tried it out, but there's a link on that page to [Instant Django](http://www.instantdjango.com/), which looks like a pretty easy to set up. | You can get around this problem by providing the full path to your django-admin.py file
```
python c:\python25\scripts\django-admin.py startproject mysite
``` | Why is django giving error: no module named django.core? | [
"",
"python",
"windows",
"django",
"django-admin",
""
] |
Instead of running an external program with its path hardcoded, I would like to get the current Project Dir. I'm calling an external program using a process in the custom task.
How would I do that? AppDomain.CurrentDomain.BaseDirectory just gives me the location of VS 2008. | You can try one of this two methods.
```
string startupPath = System.IO.Directory.GetCurrentDirectory();
string startupPath = Environment.CurrentDirectory;
```
Tell me, which one seems to you better | ```
using System;
using System.IO;
// This will get the current WORKING directory (i.e. \bin\Debug)
string workingDirectory = Environment.CurrentDirectory;
// or: Directory.GetCurrentDirectory() gives the same result
// This will get the current PROJECT bin directory (ie ../bin/)
string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;
// This will get the current PROJECT directory
string projectDirectory = Directory.GetParent(workingDirectory).Parent.Parent.FullName;
``` | How do you get the current project directory from C# code when creating a custom MSBuild task? | [
"",
"c#",
"msbuild",
""
] |
There have been a few questions on SO about the *pimpl idiom*, but I'm more curious about how often it is leveraged in practice.
I understand there are some trade-offs between performance and encapsulation, plus some debugging annoyances due to the extra redirection.
With that, is this something that should be adopted on a per-class, or an all-or-nothing basis? Is this a best-practice or personal preference?
I realize that's somewhat subjective, so let me list my top priorities:
* Code clarity
* Code maintainability
* Performance
I always assume that I will need to expose my code as a library at some point, so that's also a consideration.
**EDIT:** Any other options to accomplish the same thing would be welcome suggestions. | I'd say that whether you do it per-class or on an all-or-nothing basis depends on why you go for the pimpl idiom in the first place. My reasons, when building a library, have been one of the following:
* Wanted to hide implementation in order to avoid disclosing information (yes, it was not a FOSS project :)
* Wanted to hide implementation in order to make client code less dependent. If you build a shared library (DLL), you can change your pimpl class without even recompiling the application.
* Wanted to reduce the time it takes to compile the classes using the library.
* Wanted to fix a namespace clash (or similar).
None of these reasons prompts for the all-or-nothing approach. In the first one, you only pimplize what you want to hide, whereas in the second case it's probably enough to do so for classes which you expect to change. Also for the third and fourth reason there's only benefit from hiding non-trivial members that in turn require extra headers (e.g., of a third-party library, or even STL).
In any case, my point is that I wouldn't typically find something like this too useful:
```
class Point {
public:
Point(double x, double y);
Point(const Point& src);
~Point();
Point& operator= (const Point& rhs);
void setX(double x);
void setY(double y);
double getX() const;
double getY() const;
private:
class PointImpl;
PointImpl* pimpl;
}
```
In this kind of a case, the tradeoff starts to hit you because the pointer needs to be dereferenced, and the methods cannot be inlined. However, if you do it only for non-trivial classes then the slight overhead can typically be tolerated without any problems. | One of the biggest uses of pimpl ideom is the creation of stable C++ ABI. Almost **every** Qt class uses "D" pointer that is kind of pimpl. This allows performing much easier changes withot breaking ABI. | The Pimpl Idiom in practice | [
"",
"c++",
"pimpl-idiom",
""
] |
Does `urllib2` fetch the whole page when a `urlopen` call is made?
I'd like to just read the HTTP response header without getting the page. It looks like `urllib2` opens the HTTP connection and then subsequently gets the actual HTML page... or does it just start buffering the page with the `urlopen` call?
```
import urllib2
myurl = 'http://www.kidsidebyside.org/2009/05/come-and-draw-the-circle-of-unity-with-us/'
page = urllib2.urlopen(myurl) // open connection, get headers
html = page.readlines() // stream page
``` | Use the `response.info()` method to get the headers.
From the [urllib2 docs](https://docs.python.org/2/library/urllib2.html):
> urllib2.urlopen(url[, data][, timeout])
>
> ...
>
> This function returns a file-like object with two additional methods:
>
> * geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed
> * info() — return the meta-information of the page, such as headers, in the form of an httplib.HTTPMessage instance (see Quick Reference to HTTP Headers)
So, for your example, try stepping through the result of `response.info().headers` for what you're looking for.
Note the major caveat to using httplib.HTTPMessage is documented in [python issue 4773](http://bugs.python.org/issue4773). | What about sending a HEAD request instead of a normal GET request. The following snipped (copied from a similar [question](https://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python)) does exactly that.
```
>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
>>> print res.getheaders()
[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]
``` | Python: Get HTTP headers from urllib2.urlopen call? | [
"",
"python",
"urllib",
"forwarding",
""
] |
Is there a decent browser-based javascript self-editor?
It is obvious one can make a quick js editor with a page containing a form textarea, some buttons and callbacks. I'm wondering if someone has taken that as a beginning and ran with it.
The javascript to be edited could be defined in a global string or it could be a served .js
The ideal editor would show a pretty version inside a browser window and provide some kind of development environment for editing the script.
It is understood that user-written scripts would only exist inside the browser and could not be saved without some additional server-side functionality. The ideal package would discuss and explore this.... but I'd settle for anything that just lets the user make their own simple changes to 100-200 line scripts. | I'm not sure exactly what you're asking for, but does [jsbin](http://jsbin.com) satisfy your needs? | The hard part of what it sounds like you want to do is going to be parsing the javascript so that you can do intelligent things with it. The [CodeMirror](http://marijn.haverbeke.nl/codemirror/) library can help you develop something to put on a page.
UPDATE:
Etherpad isn't around anymore but [Ace](http://ace.ajax.org) is really nice. It's got a long history and is the engine used by the [Cloud9 IDE](https://c9.io/) | Is there a decent browser-based javascript self-editor? | [
"",
"javascript",
"ide",
"editor",
""
] |
I have a VS generated C++ Win32 DLL project. It has the following files:
stdafx.h
targetver.h
myProject.h
dllmain.cpp
myProject.cpp
stdafx.cpp
I can remove targetver.h, and merge dllmain.cpp into myProject.cpp. What more can I do to get the simplest file structure, preferably one file. I need to dynamically emit this code file and build it into a Win32 DLL. | If you want a minimalistic file structure, you could just create the files yourself. Start an empty project, or delete all the files. Heck, just make a folder, write main.cpp, and [compile it from the command line with cl](http://msdn.microsoft.com/en-us/library/ms235639.aspx).
Few IDEs really try to minimize files like you're trying to -- but when you create the project, you can cut back a little: stdafx.[h, cpp] are for precompiled headers, which you could disable when creating the project.
That said, I don't really see the value in minimizing the amount of source code in a compiled language project -- it's not going to have a meaningful impact on the number of output files/dlls and, properly used, using more files only helps your code's clarity. | In addition to what Andy said, you can merge the `myProject` header and implementation files as well with `dllmain.cpp`. But why not just keep these files and create the vsproj file at runtime? | Stripping Down VS 2008 Win32 DLL to one file | [
"",
"c++",
"visual-studio-2008",
"winapi",
""
] |
Is there a way of marking methods/classes in C++ as obsolete?
In c# you can write:
```
[Obsolete("You shouldn't use this method anymore.")]
void foo() {}
```
I use the GNU toolchain/Eclipse CDT if that matters. | The easiest way is with a `#define DEPRECATED`. On GCC, it expands to `__attribute__((deprecated))`, on Visual C++ it expands to [`__declspec(deprecated)`](http://msdn.microsoft.com/en-us/library/044swk7y.aspx), and on compilers that do not have something silimar it expands to nothing. | Only using compiler dependent pragmas: look up the [documentation](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html)
```
int old_fn () __attribute__ ((deprecated));
``` | Mark class/method obsolete or deprecated in C++ | [
"",
"c++",
"compiler-construction",
"attributes",
""
] |
I need to plot some data in various forms. Currently I'm using [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) and I'm fairly happy with the plots I'm able to produce.
This question is on how to plot the last one. The data is similar to the "distance table", like [this](http://www.southernct.edu/wellness/uploads/textWidget/wysiwyg/documents/Campus_Walking_Map__Distance_Chart.pdf) (just bigger, my table is 128x128 and still have 3 or more number per element).
Now, my data is much better "structured" than a distance table (my data doesn't varies "randomly" like in a alphabetically sorted distance table), thus a 3D [barchart](http://www.scipy.org/Cookbook/Matplotlib/BarCharts), or maybe 3 of them, would be perfect. My understanding is that such a chart is missing in Matplotlib.
I could use a (colored) Countor3d like [these](http://www.scipy.org/Cookbook/Matplotlib/mplot3D) or something in 2D like imshow, but it isn't really well representative of what the data is (the data has meaning just in my 128 points, there isn't anything between two points). And the height of bars is more readable than color, IMO.
Thus the questions:
1. is it possible to create 3D barchart in Matplotlib? It should be clear that I mean with a 2D domain, not just a 2D barchart with a "fake" 3D rendering for aesthetics purposes
2. if the answer to the previous question is no, then is there some other library able to do that? I strongly prefer something Python-based, but I'm OK with other Linux-friendly possibilities
3. if the answer to the previous question is no, then do you have any suggestions on how to show that data? E.g. create a table with the values, superimposed to the imshow or other colored way? | [MyavaVi2](http://code.enthought.com/projects/mayavi/) can make [3D barcharts](http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html#d-data) (scroll down a bit). Once you have [MayaVi](http://en.wikipedia.org/wiki/MayaVi)/[VTK](http://en.wikipedia.org/wiki/VTK)/[ETS](http://en.wikipedia.org/wiki/Enthought)/etc. installed it all works beautifully, but it can be some work getting it all installed. Ubuntu has all of it packaged, but they're the only Linux distribution I know that does. | For some time now, matplotlib had no 3D support, but it has been added back [recently](http://thread.gmane.org/gmane.comp.python.matplotlib.devel/6762/focus=6820). You will need to use the svn version, since no release has been made since, and the documentation is a little sparse (see examples/mplot3d/demo.py). I don't know if mplot3d supports real 3D bar charts, but one of the demos looks a little like it could be extended to something like that.
Edit: The source code for the demo is in [the examples](http://matplotlib.sourceforge.net/examples/mplot3d/demo.html) but for some reason the result is not. I mean the `test_polys` function, and here's how it looks like:
[example figure http://www.iki.fi/jks/tmp/poly3d.png](http://www.iki.fi/jks/tmp/poly3d.png)
The `test_bar2D` function would be even better, but it's commented out in the demo as it causes an error with the current svn version. Might be some trivial problem, or something that's harder to fix. | Barchart (o plot) 3D | [
"",
"python",
"matplotlib",
"plot",
"matplotlib-3d",
""
] |
```
class example:
def exampleMethod(self):
aVar = 'some string'
return aVar
```
In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns? | The variable is never deallocated.
The object (in this case a string, with a value of `'some string'` is reused again and again, so that object can never be deallocated.
Objects are deallocated when no variable refers to the object. Think of this.
```
a = 'hi mom'
a = 'next value'
```
In this case, the first object (a string with the value `'hi mom'`) is no longer referenced anywhere in the script when the second statement is executed. The object (`'hi mom'`) can be removed from memory. | Every time You assign an object to a variable, You increase this object's reference counter.
```
a = MyObject() # +1, so it's at 1
b = a # +1, so it's now 2
a = 'something else' # -1, so it's 1
b = 'something else' # -1, so it's 0
```
Noone can access this the MyObject object We have created at the first line anymore.
When the counter reaches zero, the garbage collector frees the memory.
There is a way to make a tricky reference that does not increase reference counter (f.e. if You don't want an object to be hold in memory just because it's in some cache dict).
More on cPython's reference counting can be found [here](http://www.python.org/doc/2.5.2/ext/refcounts.html).
Python is language, cPython is it's (quite popular) implementation. Afaik the language itself doesn't specify *how* the memory is freed. | How does garbage collection in Python work with class methods? | [
"",
"python",
"garbage-collection",
""
] |
I'm writing a PHP app that has a 'control panel' that writes a prefs file with certain variables. On every `POST`, if the file doesn't exist, it is created. If it does exist, it is `unlinked` and a new file is `touched` with the same filename and new variables. This file is then included on another page with displays content based on the variables inside it.
```
$file = "phpsettings.php";
if (!file_exists($file)) {
touch($file);
$handle = fopen ($file, 'r+');
$str = "<?php \$pref1 = \"$mypref\"; ?>";
} else {
unlink($file);
touch($file);
$handle = fopen ($file, 'r+');
$str = "<?php \$pref1 = \"$mypref\"; ?>";
}
fwrite ($handle, $str);
fclose ($handle);
```
Is this a safe way of writing preferences, provided this file will be overwritten many times per day? What is a good way of both alerting the user of this control panel if the file wasn't saved correctly, and in that case, what would be a good contingency plan to avoid breaking the page this prefs file is included on short of defining a default set of variables to fill if `!(file_exists)`? | If you store your settings in an array, you can serialize() them and write to a text file, rather than writing raw php to a php file and including it.
If you're not sanitising your input for those preferences, and say $mypref1 represents someone's name, there's nothing stopping them from filling this out in the form field:
```
\"; echo \"PWNED
```
and your resulting PHP will become
```
<?php \$pref1 = \"$mypref\"; echo \"PWNED\"; ?>
```
So firstly, storing your preferences in an array and using serialize() is much safer:
```
$prefs = array('mypref1' => 'somethingorother');
$handle = fopen ($file, 'w');
fwrite($handle, serialize($prefs));
fclose($h);
// example code demonstrating unserialization
$prefs2 = unserialize(file_get_contents($file));
var_dump($prefs == $prefs2); // should output "(bool) true"
```
In your question, you also mention that if the file does exist, it is unlinked. You can simply truncate it to zero length by passing "w" as the second argument to fopen - you don't need to manually delete it. This should set the mtime anyway, negating the need for the call to touch().
If the values being written to the file are preferences, surely each preference could have a default, unless there are hundreds? array\_merge will allow you to overwrite on a per-key basis, so if you do something like this:
```
// array of defaults
$prefs = array(
'mypref1' => 'pants',
'mypref2' => 'socks',
);
if (file_exists($file)) {
// if this fails, an E_NOTICE is raised. are you checking your server error
// logs regularly?
if ($userprefs = unserialize(file_get_contents($file))) {
$prefs = array_merge($prefs, $userprefs);
}
}
```
If the issue is that there are heaps, and you don't want to have to initialise them all, you could have a get\_preference method which just wraps an isset call to the prefs array.
```
function get_preference($name, &$prefs) {
if (isset($pref[$name]))
return $pref[$name];
return null;
}
var_dump(get_preference('mypref1', $prefs));
```
Beyond all of the questions this raises though, the reality is that with your app, in the unlikely event that something *does* go wrong with the fopen, it should be regarded as a serious failure anyway, and the handful of users you're likely to have making use of this feature are going to be contacting you pretty darn quick if something goes wrong. | Why not just use the truncation capabilities of fopen()? I believe instead of "r+", you'll need to pass "w+"... Then if the file exists, it will be truncated, if it doesn't you'll just create a new file. So the code becomes:
```
$file = "phpsettings.php";
$handle = fopen( $file, 'w+' );
$str = "<?php \$pref1 = \"$mypref\"; ?>";
fwrite ($handle, $str);
fclose ($handle);
``` | Contingency plan for fopen error in php | [
"",
"php",
"fopen",
""
] |
I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example:
```
def func( files ):
for f in files:
doSomethingWithFile( f )
func( ['file1','file2','file3'] )
func( 'file1' ) # should be treated like ['file1']
```
How can my function tell whether a string or a list has been passed in? I know there is a `type` function, but is there a "more pythonic" way? | Well, there's nothing unpythonic about checking type. Having said that, if you're willing to put a small burden on the caller:
```
def func( *files ):
for f in files:
doSomethingWithFile( f )
func( *['file1','file2','file3'] ) #Is treated like func('file1','file2','file3')
func( 'file1' )
```
I'd argue this is more pythonic in that "explicit is better than implicit". Here there is at least a recognition on the part of the caller when the input is already in list form. | ```
isinstance(your_var, basestring)
``` | How can I tell if a python variable is a string or a list? | [
"",
"python",
"list",
"duck-typing",
""
] |
Going from a lambda to an Expression is easy using a method call...
```
public void GimmeExpression(Expression<Func<T>> expression)
{
((MemberExpression)expression.Body).Member.Name; // "DoStuff"
}
public void SomewhereElse()
{
GimmeExpression(() => thing.DoStuff());
}
```
But I would like to turn the Func in to an expression, only in rare cases...
```
public void ContainTheDanger(Func<T> dangerousCall)
{
try
{
dangerousCall();
}
catch (Exception e)
{
// This next line does not work...
Expression<Func<T>> DangerousExpression = dangerousCall;
var nameOfDanger =
((MemberExpression)dangerousCall.Body).Member.Name;
throw new DangerContainer(
"Danger manifested while " + nameOfDanger, e);
}
}
public void SomewhereElse()
{
ContainTheDanger(() => thing.CrossTheStreams());
}
```
The line that does not work gives me the compile-time error `Cannot implicitly convert type 'System.Func<T>' to 'System.Linq.Expressions.Expression<System.Func<T>>'`. An explicit cast does not resolve the situation. Is there a facility to do this that I am overlooking? | Ooh, it's not easy at all. `Func<T>` represents a generic `delegate` and not an expression. If there's any way you could do so (due to optimizations and other things done by the compiler, some data might be thrown away, so it might be impossible to get the original expression back), it'd be disassembling the IL on the fly and inferring the expression (which is by no means easy). Treating lambda expressions as data (`Expression<Func<T>>`) is a magic done by the **compiler** (basically the compiler builds an expression tree in code instead of compiling it to IL).
### Related fact
This is why languages that push lambdas to the extreme (like Lisp) are often easier to implement as **interpreters**. In those languages, code and data are essentially the same thing (even at *run time*), but our chip cannot understand that form of code, so we have to emulate such a machine by building an interpreter on top of it that understands it (the choice made by Lisp like languages) or sacrificing the power (code will no longer be exactly equal to data) to some extent (the choice made by C#). In C#, the compiler gives the illusion of treating code as data by allowing lambdas to be interpreted as **code** (`Func<T>`) and **data** (`Expression<Func<T>>`) at *compile time*. | ```
private static Expression<Func<T, bool>> FuncToExpression<T>(Func<T, bool> f)
{
return x => f(x);
}
``` | converting a .net Func<T> to a .net Expression<Func<T>> | [
"",
"c#",
".net",
"lambda",
"expression",
"func",
""
] |
I've been trying to compile a Borland C++ Builder 6 project, but linker dies with exact following error:
```
[Linker Fatal Error] Fatal: Unable to open file '.OBJ'
```
Strange thing about it is that it doesn't give any file name except the extension. It looks like an internal bug, though googling for it didn't give any results. Has anyone encountered this error?
== SOLVED ==
It was actually an invalid compiler directive in one of the sourcefiles which caused linker command line to be corrupted. Thanks for help. | Check for illegal whitespace characters in your Linker command line.
If you don't find any, post your linker command line here (Off the top of my head found in Project -> Options -> Linker -> Command Line). | I've never used Borland C++ Builder, but that might sound like a broken project or a corrupted object file - I guess you have not had any compilation error.
A few steps you may want to take:
- rebuild the project
- check the exact command-line used to invoke the linker, and look for strange things in the custom project settings (in such a thing exists).
If you indeed find some strange things in the command-line, hand-editing the project file (kids, don't do this at home) to remove the offending part may be the last resort before building up a new project. | Weird linker error on Borland C++ Builder 6 | [
"",
"c++",
"linker-errors",
"c++builder",
""
] |
I have a series of checkboxes and input type="text" areas, wherein I need to have the state of the checkbox set to true when the value in the text area changes. Simple enough. I've done this successfully:
```
<input name="fixed" type="checkbox">
<input name="stuff" type="text" onchange="this.form.fixed.checked=true">
```
Which works fine. You have to edit the field then click out of it, but that is fine for my needs:
...but when I switch to this:
```
<input name="fixed[0]" type="checkbox">
<input name="stuff" type="text" onchange="this.form.fixed[0].checked=true">
<input name="fixed[1]" type="checkbox">
<input name="stuff" type="text" onchange="this.form.fixed[1].checked=true">
```
I get no change to my checkboxes when I edit:
My only javascript know-how comes from googling this sort of thing, I'm afraid. Anyone have any better info on this than the Oracle of Google on The Mountain has in store?
thanks... | Switch from dot notation to bracket notation!
```
this.form['fixed[0]'].checked
``` | It might be that you're mixing some shady practices in HTML, and when you do it in javascript, they're breaking.
So this.form.fixed[1] in javascript really says "The second item in the array this.form.fixed. So I think that's the problem. try naming your elements fixed0 and fixed1 and see if that works.
**Edit**: You could also use bracket notation, as illustrated by Peter, which should solve the problem without editing the names of the inputs. | In javascript how do I refer to this.form.checkbox[5].checked? | [
"",
"javascript",
"arrays",
"onchange",
""
] |
Heres my problem. I have a mysql table called quotes. In one of the rows, a quote contains the folloqing characters
```
‘ and ’
```
Now the row collation is **utf8\_\_unicode\_\_ci**
When using MySQL Query Browser and PHPMyAdmin to retrive the rows the quotes come out as intended. How ever when i retrive them from the database using PHP and display them on the screen they come out as boxes
```
� and �
```
My html page has UTF-8 encoding, and all the UTF-8 encoding options are set in php:
```
/* Set UTF-8 settings */
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');
mb_http_output('UTF-8');
/* Set ICONV ini settings */
ini_set('iconv.input_encoding', 'UTF-8');
ini_set('iconv.output_encoding', 'UTF-8');
ini_set('iconv.internal_encoding', 'UTF-8');
/* Set ICONV function settings */
iconv_set_encoding('input_encoding', 'UTF-8');
iconv_set_encoding('output_encoding', 'UTF-8');
iconv_set_encoding('internal_encoding', 'UTF-8');
```
It seems to me that it should work. But it doesnt :S can anyone shed some light onto this please. | You may need to set UTF-8 as the chosen charset on your MySQL connection. If you are using the mysqli PHP driver this means something like this:
```
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
$mysqli->set_charset("utf8");
``` | @Joakim, thanks so much for setting me in the right direction. I couldnt use your exact code because im using a custom database driver and it works using the old mysql commands not the mysqli class. I tried using mysql\_set\_charset() but my php version didnt support it (still php 5 tho).
this is the solution i used:
```
mysql_query("SET CHARACTER SET utf8", $this->connection);
mysql_query("SET NAMES utf8", $this->connection);
``` | PHP MySQL Encoding Bug? | [
"",
"php",
"mysql",
"encoding",
"utf-8",
""
] |
I have a view in my database that produces ordered results, but when I run a Linq query over that view, the results are no longer ordered (at least, according to the foreach I use to iterate over the results, and according to the debugger). Is this a known difficulty with Linq, or am I missing something?
**Update**: my view, from SQL Server 2008 (from design view):
```
SELECT TOP (100) PERCENT UrlId, Title, Description, Url, Parent, ResourceKey, Published, dbo.udf_SiteMap_GetRoles(UrlId) AS Roles
FROM dbo.SiteMap
ORDER BY DisplayOrder
```
The Linq query that builds the SiteMap:
```
SqlConnection connection = new SqlConnection(_connect);
DataContext dc = new DataContext(connection);
Table<NodeRoleEntity> siteMapTable = dc.GetTable<NodeRoleEntity>();
var rootQuery = from ne in siteMapTable
where ne.ParentID == null
select ne;
foreach (NodeRoleEntity rootNode in rootQuery)
{
SiteMapNode root = rootNode.AsSiteMapNode(this);
base.AddNode(root, _root);
AddChildNodes(root, siteMapTable);
}
```
This query uses the SiteMap built above to render menus in my ASP.NET application:
```
StaticSiteMapProvider _provider = SiteMap.Providers["MySiteMap"] as StaticSiteMapProvider;
string cultureToken = _GetCulture().ToLower();
SiteMapNode cultureRoot =
(from SiteMapNode cr in _provider.RootNode.ChildNodes
where cr.Description == cultureToken
select cr).First();
int menuCount = 0;
foreach (SiteMapNode node in cultureRoot.ChildNodes)
{
_RenderMenu(node, menuCount.ToString(), writer);
menuCount++;
}
```
It is the nodes in `cultureRoot.ChildNodes` that are ordered improperly (but the rows from which those nodes are derived are ordered). | When you select from a view it doesn't keep it's order. You have to put in in the LINQ:
```
SiteMapNode cultureRoot = (
from SiteMapNode cr in _provider.RootNode.ChildNodes
where cr.Description == cultureToken
orderby cr.DisplayOrder
select cr
).First();
``` | Your linq query is:
```
var rootQuery = from ne in siteMapTable
where ne.ParentID == null
select ne;
```
This will generate sql like so
```
SELECT *
FROM SiteMapTable
WHERE ParentID == @P1
```
You can take this sql to the database, run it and observe that your results are un-ordered. Here's what happens:
In the database, the text of the view will be placed as a subquery into your query.
```
SELECT *
FROM
(
SELECT top 100 percent *
FROM ...
ORDER BY ...
) as SiteMapTable
WHERE ParentID == @P1
```
The query optimizer will notice that ordering was not asked for at the outer most level, and decide that order is not needed for the results. It will strip out/ignore the ordering in the sub-query. You can view the estimated execution plan to confirm this. | Linq query loses order | [
"",
"c#",
"linq",
""
] |
I'm developing a Spring webflow, trying to use TDD so I've extended AbstractXmlFlowExecutionTests. I can't see an obvious way to assert what I would have thought would be a simple thing: that a view state has an associated view of a given name. For example, given this flow (excerpt):
```
<?xml version="1.0" encoding="UTF-8"?>
<flow ...>
...
<view-state id="foo" view="barView">
</view-state>
</flow>
```
and unit test
```
public void testAssertFooStateHasBarView() {
...
assertCurrentStateEquals("foo");
assertTrue( getFlowDefinition().getState("confirmation").isViewState());
// Surely there's an easier way...?
ViewState viewState = (ViewState)getFlowDefinition().getState("foo");
View view = viewState.getViewFactory().getView(new MockRequestContext());
// yuck!
assertTrue(view.toString().contains("barView"));
}
```
Is there a simpler way to assert that state `foo` has view `barView`? | You can use this:
```
assertResponseWrittenEquals("barView", context);
```
Where `context` is your `MockExternalContext`.
This is how I always test this anyway. | If you are actually signaling events, you can get the ViewSelection and check the name via this method:
```
assertViewNameEquals("Your View Name", applicationView(viewSelection));
``` | In Spring Webflow unit test, how do you assert that a view state has a view of a given name? | [
"",
"java",
"spring",
"unit-testing",
"spring-mvc",
"spring-webflow",
""
] |
Do you know any tool which can count all the code lines from a PHP project? | On a POSIX operating system (e.g. Linux or OS X) you can write the following into your Bash shell:
```
wc -l `find . -iname "*.php"`
```
This will count the lines in all php-files in the current directory and also subdirectories. (Note that those single 'quotes' are backticks, not actual single quotes) | I made myself a small script to do that in one of my projects. Simply use the following code on a php page in the root of your project. The script will do recursive check on sub folders.
```
<?php
/**
* A very simple stats counter for all kind of stats about a development folder
*
* @author Joel Lord
* @copyright Engrenage (www.engrenage.biz)
*
* For more information: joel@engrenage.biz
*/
$fileCounter = array();
$totalLines = countLines('.', $fileCounter);
echo $totalLines." lines in the current folder<br>";
echo $totalLines - $fileCounter['gen']['commentedLines'] - $fileCounter['gen']['blankLines'] ." actual lines of code (not a comment or blank line)<br><br>";
foreach($fileCounter['gen'] as $key=>$val) {
echo ucfirst($key).":".$val."<br>";
}
echo "<br>";
foreach($fileCounter as $key=>$val) {
if(!is_array($val)) echo strtoupper($key).":".$val." file(s)<br>";
}
function countLines($dir, &$fileCounter) {
$_allowedFileTypes = "(html|htm|phtml|php|js|css|ini)";
$lineCounter = 0;
$dirHandle = opendir($dir);
$path = realpath($dir);
$nextLineIsComment = false;
if($dirHandle) {
while(false !== ($file = readdir($dirHandle))) {
if(is_dir($path."/".$file) && ($file !== '.' && $file !== '..')) {
$lineCounter += countLines($path."/".$file, $fileCounter);
} elseif($file !== '.' && $file !== '..') {
//Check if we have a valid file
$ext = _findExtension($file);
if(preg_match("/".$_allowedFileTypes."$/i", $ext)) {
$realFile = realpath($path)."/".$file;
$fileHandle = fopen($realFile, 'r');
$fileArray = file($realFile);
//Check content of file:
for($i=0; $i<count($fileArray); $i++) {
if($nextLineIsComment) {
$fileCounter['gen']['commentedLines']++;
//Look for the end of the comment block
if(strpos($fileArray[$i], '*/')) {
$nextLineIsComment = false;
}
} else {
//Look for a function
if(strpos($fileArray[$i], 'function')) {
$fileCounter['gen']['functions']++;
}
//Look for a commented line
if(strpos($fileArray[$i], '//')) {
$fileCounter['gen']['commentedLines']++;
}
//Look for a class
if(substr(trim($fileArray[$i]), 0, 5) == 'class') {
$fileCounter['gen']['classes']++;
}
//Look for a comment block
if(strpos($fileArray[$i], '/*')) {
$nextLineIsComment = true;
$fileCounter['gen']['commentedLines']++;
$fileCounter['gen']['commentBlocks']++;
}
//Look for a blank line
if(trim($fileArray[$i]) == '') {
$fileCounter['gen']['blankLines']++;
}
}
}
$lineCounter += count($fileArray);
}
//Add to the files counter
$fileCounter['gen']['totalFiles']++;
$fileCounter[strtolower($ext)]++;
}
}
} else echo 'Could not enter folder';
return $lineCounter;
}
function _findExtension($filename) {
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
``` | count lines in a PHP project | [
"",
"php",
"count",
"line",
""
] |
I have a class that is being used by two different processes with each process using different properties of the class. Everytime a process requires a new property I simply add it to the class. Is this a bad idea? Should I just create two separate classes and update them when required?
N.B. At times the same property is being used by both the processes and each process uses a different instance of the class. | Common properties can be kept in a single class. Then you can derive two different classes from the common class and add specific properties. | > "Common properties can be kept in a
> single class. Then you can derive two
> different classes from the common
> class and add specific properties" - Kirtan Gor
```
class BaseClassWithSharedProperties
{
public Int32 SharedId { get; set; }
public String SharedName { get; get; }
}
class UniqueClassNumberOne : BaseClassWithSharedProperties
{
public UniqueClassNumberOneProperty { get; set; }
}
class UniqueClassNumberTwo : BaseClassWithSharedProperties
{
public UniqueClassNumberTwoProperty { get; set; }
}
``` | class for different uses | [
"",
"c#",
"oop",
""
] |
Let's suppose I have this object:
```
[Serializable]
public class MyClass
{
public int Age { get; set; }
public int MyClassB { get; set; }
}
[Serializable]
public class MyClassB
{
public int RandomNumber { get; set; }
}
```
The XmlSerializer will serialize the object like that:
```
<MyClass>
<Age>0</age>
<MyClassB>
<RandomNumber>4234</RandomNumber>
</MyClassB>
</MyClass>
```
How can I made the property Age nullable? IE: to not serialize the property Age when it's under 0?
I tried with the Nullable, but it serialize my object like that:
```
<MyClass>
<Age d5p1:nil="true" />
<MyClassB>
<RandomNumber>4234</RandomNumber>
</MyClassB>
</MyClass>
```
By reading the MSDN documentation I found this:
> You cannot apply the IsNullable property to a member typed as a value type because a value type cannot contain nullNothingnullptra null reference (Nothing in Visual Basic). Additionally, you cannot set this property to false for nullable value types. When such types are nullNothingnullptra null reference (Nothing in Visual Basic), they will be serialized by setting xsi:nil to true.
source: <http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.isnullable.aspx>
I understand a value type can't be set to null. A valuetype is always set to something. The serialization can't make the decision to serialize it or not based on it's current value.
I tried with the attributes, but it didn't work out. I tried creating an agecontainer object and manipulate it's serialization with attributes, but it didn't work out.
What I really want is:
```
<MyClass>
<MyClassB>
<RandomNumber>4234</RandomNumber>
</MyClassB>
</MyClass>
```
When the property Age is below 0 (zero).
---
> Looks like you'll have to implement custom serialization.
Yeah, that's what I though too, but I'd like to get away without it.
In the application, the object is much more complex, and I would like to not handle the serialization myself. | I just discovered this. `XmlSerialier` looks for a `XXXSpecified` boolean property to determine if it should be included. This should solve the problem nicely.
```
[Serializable]
public class MyClass
{
public int Age { get; set; }
[XmlIgnore]
public bool AgeSpecified { get { return Age >= 0; } }
public int MyClassB { get; set; }
}
[Serializable]
public class MyClassB
{
public int RandomNumber { get; set; }
}
```
Proof:
```
static string Serialize<T>(T obj)
{
var serializer = new XmlSerializer(typeof(T));
var builder = new StringBuilder();
using (var writer = new StringWriter(builder))
{
serializer.Serialize(writer, obj);
return builder.ToString();
}
}
static void Main(string[] args)
{
var withoutAge = new MyClass() { Age = -1 };
var withAge = new MyClass() { Age = 20 };
Serialize(withoutAge); // = <MyClass><MyClassB>0</MyClassB></MyClass>
Serialize(withAge); // = <MyClass><Age>20</Age><MyClassB>0</MyClassB></MyClass>
}
```
---
**Edit**: Yes, it is a documented feature. See the [MSDN entry for `XmlSerializer`](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx)
> Another option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. The pattern is created in the form of propertyNameSpecified. For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether to generate the XML element named "MyFirstName". | Extending Samuel's answer and Greg Beech's comment to the case of a boolean property: if the property is of type bool then you can't write a simple test in the propertySpecified property.
A solution is to use a Nullable<bool> type, then the test in the propertySpecified property is simply property.HasValue. e.g.
```
using System.Xml.Serialization;
public class Person
{
public bool? Employed { get; set; }
[XmlIgnore]
public bool EmployedSpecified { get { return Employed.HasValue; } }
}
```
An alternative to using a nullable type for a numeric property (suggested by Greg Beech) is to set the value property to an invalid default value, such as -1, as follows:
```
using System.ComponentModel;
using System.Xml.Serialization;
public class Person
{
[DefaultValue(-1)]
public int Age { get; set; }
[XmlIgnore]
public bool AgeSpecified { get { return Age >= 0; } }
}
``` | How to make a value type nullable with .NET XmlSerializer? | [
"",
"c#",
"xml-serialization",
"null",
"value-type",
""
] |
I have some unsolved issue with threads. It's my first time doing it. I know how to use one thread to write in a textBox, but I have no idea how to use two of them to do the job. Anyone have a clue what do I have to do to be able to use two threads to write to the same textBox, but not in the same time. Thank you. | Here's an example that uses two threads to write random numbers to a multi-line text box. As Brandon and Jon B noted, you need to use Invoke() to serialize the calls to the GUI thread.
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random m_random = new Random((int)DateTime.Now.Ticks);
ManualResetEvent m_stopThreadsEvent = new ManualResetEvent(false);
private void buttonStart_Click(object sender, EventArgs e)
{
Thread t1 = new Thread(new ThreadStart(ThreadOne));
Thread t2 = new Thread(new ThreadStart(ThreadTwo));
t1.Start();
t2.Start();
}
private void ThreadOne()
{
for(;;)
{
int n = m_random.Next(1000);
AppendText(String.Format("One: {0}\r\n", n));
if(m_stopThreadsEvent.WaitOne(n))
{
break;
}
}
}
private void ThreadTwo()
{
for(;;)
{
int n = m_random.Next(1000);
AppendText(String.Format("Two: {0}\r\n", n));
if(m_stopThreadsEvent.WaitOne(n))
{
break;
}
}
}
delegate void AppendTextDelegate(string text);
private void AppendText(string text)
{
if(textBoxLog.InvokeRequired)
{
textBoxLog.Invoke(new AppendTextDelegate(this.AppendText), new object[] { text });
}
else
{
textBoxLog.Text = textBoxLog.Text += text;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
m_stopThreadsEvent.Set();
}
}
``` | One option you could do, is push messages onto a Queue object and use a timer on the windows form to read messages from this queue and write to the textbox.
In order to make everything nice and threadsage you could lock the Queue object when reading and writing to it.
For example:
```
private Queue<string> messages = new Queue<string>();
/// <summary>
/// Add Message To The Queue
/// </summary>
/// <param name="text"></param>
public void NewMessage(string text)
{
lock (messages)
{
messages.Enqueue(text);
}
}
private void tmr_Tick(object sender, EventArgs e)
{
if (messages.Count == 0) return;
lock (messages)
{
this.textBox.Text += Environment.NewLine + messages;
}
}
``` | Writing to a textBox using two threads | [
"",
"c#",
".net",
"multithreading",
"textbox",
""
] |
I am migrating my Junit tests from Junit v3 to Junit v4.
I was hoping to use the search and replace structurally "srs" to add an @Test annotation before all methods starting with test.\* using my favorite IDE Intellij.
I just cant figura out how to do it... I can create a query that will find all methods without an annotation (there is an example bundled in Intellij) but when used to do a replace either my class gets replaced by only the method names OR nothing is found.
Maybe a regexp is easier :-) | It is not possible, as of now, but there are requests for class members replacements.
Here is a useful link for getting started with ssr: <https://www.jetbrains.com/idea/docs/ssr.pdf> | I tried with the following SSR but I have the same problem than you :
Search template :
```
public class $TestCase$ extends $TestCaseClazz$ {
public void $testMethod$();
}
```
Replacement template :
```
@Test public void $testMethod$();
```
And I check "This variable is target of the search" on testMethod.
The preview seems ok, but IntelliJ actually delete the whole method :( | How do I search and replace structurally in Intellij | [
"",
"java",
"intellij-idea",
"ide",
"structural-search",
""
] |
Is there a way to hide the console window when executing a console application?
I am currently using a Windows Forms application to start a console process, but I don't want the console window to be displayed while the task is running. | If you are using the `ProcessStartInfo` class you can set the window style to hidden - in the case of console (not GUI) applications, you have to set CreateNoWindow to `true`:
```
System.Diagnostics.ProcessStartInfo start =
new System.Diagnostics.ProcessStartInfo();
start.FileName = dir + @"\Myprocesstostart.exe";
start.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Hides GUI
start.CreateNoWindow = true; //Hides console
``` | If you wrote the console application you can make it hidden by default.
Create a new console app then then change the "Output Type" type to "Windows Application" (done in the project properties) | How to run a C# console application with the console hidden | [
"",
"c#",
"console-application",
""
] |
I'm looking to build myself a VMWare image for PHP+MySQL Development.
At present I'm using an ubuntu image which takes ~1 GB of my hard drive space. I'm looking to replace it with something smaller and lighter.
So, I'm curious... What do you folks use? It doesn't matter what OS / webserver as long as it's running Php 5 and MySQL. The smaller and lighter the better.
Any suggestions? | Don't forget [Slax](http://www.slax.org/). Build your own compressed distribution with only what you want. It works well in a virtual machine. | Have a look at [jeos](http://www.ubuntu.com/products/whatisubuntu/serveredition/jeos) - you can probably half the install size while sticking with Ubuntu. And I guess you should be able to create one with the standard server CD? | Looking to build myself a tiny, free VMWare image for PHP+MySQL Development | [
"",
"php",
"mysql",
"vmware",
""
] |
I saw some JSF projects developed by my collegues and these projects seemed to me very slow. Does anybody have the same opinion?
I'm currently using jsp+jstl and jQuery for "rich" client.
I wonder what advantages and disadvantages have modern frameworks (jsf, wicket, tapestry..) over old plain jsp.
It would be great if people who used all these technologies had answered.
It's also interesting for me which most exciting features made you to leave jsp and use "massive" framework (I mean, for example AOP in Spring or something else whatever you can notice).
Thanks for all comments. | I've used CGI, PHP, JSP, Struts, Spring MVC (1.2), Bea workshop, JSF, JBoss Seam, Spring MVC (2.5) and [Wicket](http://wicket.apache.org) (in that order). I've noticed a jump in both productivity and quality for each new technology I've worked on. It just works better, It **feels** better. I prefer Wicket (with a twist of spring, quartz, etc.) over all of the others. I can honestly say I saw the light, and I don't want to go back to a darker -- or lighter ;) -- side.
There is a lot to say about Wicket.
* Conversational support (or tab-enabling) comes by default, you do not worry about "open in a new tab" and "back" button problems ever again.
* It is component-based, so you can re-use code ala swing.
* Leverages a lot of the standard Java, like the type safety wonders.
* Supports advanced security features like url encryption.
* Clusterizable applications by default.
* And, most important, it is **fun** to use.
There is a lot to improve for JSP and JSF.
* The one thing that bothers me the most is the "EL" nonsense, for I believe it breaks the nice java type safety and strength.
* Both need tooling support for high productivity.
* You need another framework on top of both of them to really solve the problems (as seen with seam framework, which makes JSF usable).
* The error handling is very tricky and the exceptions are not straitforward helpful.
* It is difficult to make reusable components on both frameworks and doesn't support a proper model for separation of concerns.
* ... and, most important, a long etc of minor pains, like [this](http://techieexchange.wordpress.com/2008/02/21/jsf-session-expired-timeout-solution/), or [this](http://mail-archives.apache.org/mod_mbox/myfaces-users/200508.mbox/%3Cc206dbe9050805070956b59d8f@mail.gmail.com%3E). | I totally like to use JSP 2.0 as templating technology -- that is I use Spring MVC to access my domain objects and prepare all data I need for a certain view and leave it to JSP to render it. JSP 2.0 because I like to use tag files for template composition which allows me to use simple JSP 2.0 where I would need other compositing frameworks else.
I intentionally avoid everything in JSP that basically is programming. No data acess, no SQL, no scriptlets, no methods, no nothing. just plain presentation of pre-existing, controller-provided data with maybe some simple cases and iteration of collections. | JSF and Spring performance vs poor JSP performance | [
"",
"java",
"performance",
"jsp",
"jsf",
"comparison",
""
] |
in C#
```
float ratio = 185 / srcRect.Width;
```
where `srcRect.Width = 400`
returns `0` where it should return `0.45`...
min value for float is `-3.40282347E+38` so how is this possible? | You are performing an integer division and hence `185/srcRect.Width` will return 0. You will need to change the expression to
```
float ratio = 185.0f / srcRect.Width;
``` | 185 is an integer literal, and so the division performed is integer division.
To perform a float division, use 185.0 or 185.0f instead (the former is a double, the latter is float) | Float calculation errors | [
"",
"c#",
""
] |
I'm trying to write an `__init__` function for one of my models so that I can create an object by doing:
```
p = User('name','email')
```
When I write the model, I have:
```
def __init__(self, name, email, house_id, password):
models.Model.__init__(self)
self.name = name
self.email = email
```
This works and I can save the object to the database, but when I do `User.objects.all()`, it doesn't pull anything up unless I take out my `__init__` function. Any ideas? | Relying on Django's built-in functionality and passing named parameters would be the simplest way to go.
```
p = User(name="Fred", email="fred@example.com")
```
But if you're set on saving some keystrokes, I'd suggest adding a static convenience method to the class instead of messing with the initializer.
```
# In User class declaration
@classmethod
def create(cls, name, email):
return cls(name=name, email=email)
# Use it
p = User.create("Fred", "fred@example.com")
``` | Django expects the signature of a model's constructor to be `(self, *args, **kwargs)`, or some reasonable facsimile. Your changing the signature to something completely incompatible has broken it. | Writing a __init__ function to be used in django model | [
"",
"python",
"django",
"django-models",
""
] |
I'd like to use [JSLint](http://www.jslint.com/), but I am wary of tools that have access to my unfiltered source code. Is there an offline version or is there another similar tool that does "`lint` error checking" for JavaScript offline?
**Edit:** One with a GUI and that shows you a styled list of errors, instead of a command line interface? | If you like the [JSLint web interface](http://www.jslint.com/), you can do `File` > `Save Page As...` and `Save as type:` `Web Page, complete` (in Firefox, doing it in Internet Explorer may be slightly different) to a local folder.
I change the name to `jslint.htm` to get it under 8.3 with no spaces.
It seems to work when saved locally.
Three things:
1. This may violate his license, although I leave the Copyright intact and don't modify any of his code, and technically my web browser already created a copy of his site on my local HD, so I'm not sure whether I'm in violation or not and I'm not a lawyer so I'll keep doing this until I get a letter telling me to stop.
2. The page may somehow still be able to send your code to the Internet, although the chance of it being possible is very remote. That said, the WSH or Rhino versions could probably send the code you submit to the Internet easier than a version in a locally saved web page could (if you're paranoid).
3. You'll get behind on any bug fixes or updates Douglas does. But the same thing applies to the WSH or Rhino versions if you don't update them regularly. | JSLint can be run offline with either WSH or Rhino:
<http://www.jslint.com/lint.html#try>
**Edit**: In the two years since this question was asked, JSLint has dropped support for Rhino and WSH. I encourage anyone interested in linting their code to also check out [JSHint](https://github.com/jshint/jshint). It's a fork of JSLint which aims to be more flexible than the original, but also happens to support Node, Rhino, and WSH (in addition to browsers, of course). | Is JSLint available for offline use? | [
"",
"javascript",
"compiler-errors",
"jslint",
"lint",
""
] |
I have a table (`product_shoppingcart`) with 4 columns :
```
id, product_id, shoppingcart_id, product_quantity.
```
I'm using Kohana's ORM.
I want to write a search query which returns all the rows where the `shoppingcart_id` column contains 1 (for example).
I already tried:
```
$arr = ORM::factory('product_shoppingcart')->where('shoppingcart_id',$shoppingcartID)->find_all();
```
but that doesn't work.
Can anyone please help me out? | Your example code should work, but perhaps the problem is that you're not iterating over your result set?
```
$results = ORM::factory('product_shoppingcart')
->where('shoppingcart_id', $shoppingcartID)
->find_all();
foreach ($results as $product_shoppingcart) {
print Kohana::debug($product_shoppingcart->as_array());
}
```
If you have more than one row with that id, this should give you a result iterator in $results, which you then walk with the foreach loop. I have lots of examples of similar working code, if you're still not able to get it working. | Here is what it would look like:
```
$arr = ORM::factory('product_shoppingcart')->where(
'shoppingcart_id',"=",$shoppingcartID)->find_all();
``` | How do I write a search query using Kohana PHP? | [
"",
"php",
"kohana",
""
] |
Why is the following algorithm not halting for me?
In the code below, `str` is the string I am searching in, and `findStr` is the string occurrences of which I'm trying to find.
```
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1)
count++;
lastIndex += findStr.length();
}
System.out.println(count);
``` | The last line was creating a problem. `lastIndex` would never be at -1, so there would be an infinite loop. This can be fixed by moving the last line of code into the if block.
```
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
System.out.println(count);
``` | How about using [StringUtils.countMatches](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#countMatches(java.lang.CharSequence,%20java.lang.CharSequence)) from Apache Commons Lang?
```
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(StringUtils.countMatches(str, findStr));
```
That outputs:
```
3
``` | Find the Number of Occurrences of a Substring in a String | [
"",
"java",
"string",
"string-matching",
""
] |
We're using Exchange 2007 WS to process mail folders and are hitting various problems if we try and forward a message we've already received. Our process is:
* Windows Service monitors mailbox folder, on finding a new mail we process the information and move the item to a 'Processed folder' and store the Exchange Message Id.
* Users may opt to forward the mail externally. We use the Exchange API to find the item using the Message Id we stored earlier, and then again use the API to forward.
Except finding the mail again is proving rather flaky. We regularly get the following error:
> The specified object was not found in the store.
Is there a better/more reliable way we can achieve the same? The documentation for Exchange WS is rather sparse. | This is a bug in microsoft exchange manage API. here is a link for more information
<http://maheshde.blogspot.com/2010/09/exchange-web-service-specified-object.html> | Are you saving the Message ID of the newly found message or the message once it has been moved to the 'Processed' folder? The id will change when it moves to a new folder.
The method recommended in the book [Inside Microsoft Exchange Server 2007 Web Services](http://www.microsoft.com/learning/en/us/books/10724.aspx) is to grab the PR\_SEARCH\_KEY (0x300B, Binary) of the newly discovered item, then move it to the 'Processed' folder. You can then search for it in the new folder based on the PR\_SEARCH\_KEY and get it's new Message id to forward it. | Exchange WS 'The specified object was not found in the store.' error | [
"",
"c#",
"exchange-server",
"exchangewebservices",
""
] |
What is the best way to store XML data used in a program ? Use RESX file or store it as a .xml file and load and unload the files as per requirement | A third option would be to put the XML file as embedded resource in the assembly. In that case, use Assembly.GetManifestResourceStream() to load the XML.
As Cerebrus wrote, when localization is necessary, RESX would be the way to go. | .resx files ***are*** XML files albeit conforming to a particular schema (Microsoft ResX Schema v2.0). This schema was designed with the explicit aim of being easily human readable and editable manually.
I see no problem with storing your data as XML files. Basically it depends on the function of the data - If it is localizable resources that you are trying to store, go with the established .resx files. If not, you are free to use your XML with custom schema. | RESX files and xml data | [
"",
"c#",
"xml",
""
] |
When I try and compile the following code...
```
#include <vector>
template <class T> void DoNothing()
{
std::vector<T>::iterator it;
}
int main(int argc, char**argv)
{
return 0;
}
```
g++ says:
> test.cpp:5: error: expected `;' before
> ‘it’
And I don't understand why this is a problem. If I replace it with `std::vector<int>::iterator`, say, it works fine as expected.
As you can see i'm not instantiating the function, so g++ must have a problem with the template definition itself, but I can't see how its invalid.
Thanks for any advice about whats going on.
NB I'm actually trying to write a templated class and having issues with a map rather than a vector, but this is the simplest test case for my problem. | You need to use the `typename` keyword because the `std::vector<T>::iterator` type is dependent on the template parameter:
```
template <class T> void DoNothing()
{
typename std::vector<T>::iterator it;
}
```
It can actually be confusing when you need to use `typename` and when you don't need it (or are even not permitted to use it). This article has a decent overview:
* <http://pages.cs.wisc.edu/~driscoll/typename.html> | I agree it is confusing. Without the `typename` keyword, the name would be considered a static member. The book *C++ Templates* by Vandevoorde and Josuttis explains this in detail. | Failing to use stl containers in templated functions/classes | [
"",
"c++",
"stl",
"templates",
""
] |
I'd like to produce sounds that would resemble audio from real instruments. The problem is that I have very little clue how to get that.
What I know this far from real instruments is that sounds they output are rarely clean. But how to produce such unclean sounds?
This far I've gotten to do this, it produces quite plain sound from which I'm not sure it's even using the alsa correctly.
```
import numpy
from numpy.fft import fft, ifft
from numpy.random import random_sample
from alsaaudio import PCM, PCM_NONBLOCK, PCM_FORMAT_FLOAT_LE
pcm = PCM()#mode=PCM_NONBLOCK)
pcm.setrate(44100)
pcm.setformat(PCM_FORMAT_FLOAT_LE)
pcm.setchannels(1)
pcm.setperiodsize(4096)
def sine_wave(x, freq=100):
sample = numpy.arange(x*4096, (x+1)*4096, dtype=numpy.float32)
sample *= numpy.pi * 2 / 44100
sample *= freq
return numpy.sin(sample)
for x in xrange(1000):
sample = sine_wave(x, 100)
pcm.write(sample.tostring())
``` | Cheery, if you want to generate (from scratch) something that really sounds "organic", i.e. like a physical object, you're probably best off to learn a bit about how these sounds are generated. For a solid introduction, you could have a look at a book such as Fletcher and Rossings [The Physics of Musical Instruments](https://rads.stackoverflow.com/amzn/click/com/0387983740). There's lots of stuff on the web too, you might want to have a look at a the primer James Clark has [here](http://www.cim.mcgill.ca/~clark/emusic.html)
Having at least a skim over this sort of stuff will give you an idea of what you are up against. Modeling physical instruments accurately is very difficult!
If what you want to do is have something that sounds physical, rather something that sounds like instrument X, your job is a bit easier. You can build up frequencies quite easily and stack them together, add a little noise, and you'll get something that at least doesn't sound anything like a pure tone.
Reading a bit about Fourier analysis in general will help, as will Frequency Modulation (FM) techniques.
Have fun! | Sound synthesis is a complex topic which requires many years of study to master.
It is also not an entirely solved problem, although relatively recent developments (such as physical modelling synthesis) have made progress in imitating real-world instruments.
There are a number of options open to you. If you are sure that you want to explore synthesis further, then I suggest you start by learning about FM synthesis. It is relatively easy to learn and implement in software, at least in basic forms, and produces a wide range of interesting sounds. Also, check out the book "The Computer Music Tutorial" by Curtis Roads. It's a bible for all things computer music, and although it's a few years old it is the book of choice for learning the fundamentals.
If you want a quicker way to produce life-like sound, consider using sampling techniques: that is, record the instruments you want to reproduce (or use a pre-existing sample bank), and just play back the samples. It's a much more straightforward (and often more effective) approach. | How to synthesize sounds? | [
"",
"python",
"numpy",
"alsa",
""
] |
I have another MySQL problem. Again, with the complex queries I'm in over my head.
On my website I *currently* display the last 5 reviewed games on the main page. Now, it's been ticking over a while and I've decided to add news items as well to the same page.
But, I want to *change* the system that I have into one that displays news entries as well as reviews - showing the last entry that was posted in either category. Both tables are completely unrelated (news, review).
The following columns are what I want to be returned:
```
news.newsTitle
news.newsBody
news.postedOn (timestamp)
review.postedOn (timestamp)
review.reviewSummary
review.ourScore
game.gameName
game.gameImage
```
The **game** table is connected to the **review** table with gameID, but neither of these tables are associated with the **news** table.
The current query is this:
```
SELECT news.newsTitle, news.newsBody, DATE_FORMAT( review.postedOn, '%M %d, %Y' ) AS reviewPosted, DATE_FORMAT( news.postedOn, '%M %d, %Y' ) AS newsPosted, game.gameID, gameName, gameImage, review.reviewSummary, review.ourScore
FROM game
LEFT JOIN news ON news.newsID = news.newsID
LEFT JOIN review ON game.gameID = review.gameID
WHERE game.isPublished = 'y'
ORDER BY game.gameID DESC
LIMIT 0 , 5
```
But all this does is display the news item 5 times along with the game information.
Any assistance would be much appreciated. | You need to investigate UNION - create two queries that output the same number of (and equivalent) columns, join the results using UNION then order by date and limit results to the top 5.
Using the above, you could return the newest top 5, regardless of their mix between news / reviews - is that what you mean?
The following should return the desired data:
```
(SELECT news.newsTitle AS title, news.newsBody AS body,
DATE_FORMAT( news.postedOn, '%M %d, %Y' ) AS posted,
news.postedOn, null AS image, null AS score
FROM news)
UNION ALL
(SELECT game.gameName as title, review.reviewSummary AS body,
DATE_FORMAT( review.postedOn, '%M %d, %Y' ) AS posted,
review.postedOn, game.gameImage AS image, review.ourScore AS score
FROM game LEFT JOIN review ON game.gameID = review.gameID
WHERE game.isPublished = 'y')
ORDER BY postedOn DESC
LIMIT 0,5
``` | Why do you want to pull two completely unrelated pieces of data with the same query?
You could do some acrobatics by generating a rowid for each result from reviews and from news, then joining the results on the rowids; or by selecting like columns from both and using UNION as BrynJ suggested. But all of this seems totally unnecessary when you can just issue two queries.
Do these things belong together?
If you were writing this using objects in memory, not a database -- would you have some Collection that included both, or two separate collections that contained them separately?
**Update**
I got the answers to my questions in the comments; now I understand what you are trying to do. There are two ways I've seen this type of thing done: one is to select the most recent data from all sources (comments, reviews, news, uploaded photos, etc), sort them by date, and get the top X of those on the client. This has the drawback of the number of queries increasing in proportion with the number of your data sources, but it has the benefit of being very flexible in terms of the presentation layer -- you can select different columns from different objects, format them as you desire, and do whatever you need to on the client side (client in this case being your software, not the web client).
The other is to enforce a consistent set of columns you need to represent any object, which can possibly be null -- usually stuff like "type, title, body, date, img\_id" or something of the sort -- and use a union, as suggested by the other poster. This has the benefit of allowing you to use a single query, making your software less complicated; it has the drawbacks of giving you less flexibility when it comes to other types of things you might want to stick in the feed, and of possibly overloading the database (that part depends on how big a bottleneck the DB is in your case). | How do I return data from multiple MySQL tables in date order? | [
"",
"sql",
"mysql",
""
] |
I need to write a small program for the university. The problem is, it has to be in C/C++ under linux, and I've never used linux, I anticipate having a lot of problems with the IDE, compilation, and all that.
Is it possible to code it under windows and then "copy/paste" the code and compile it under linux? What are limitations I should know about if it's at all possible?
It will be a small program, typical client/server communication using sockets. | I think you should go ahead and do it under Linux (gcc?). This will teach you some stuff about 'old school' programming. Forget about using an IDE, use vim (if you already get it) or nedit (more like notepad).
Compile on the command line. Link it yourself. Write a make file to do this.
This is the basics. You need to understand it before using an IDE. *Do this while you are still at university, because it's a pain and you will (and should) want to use an IDE for real work!*
Also, a basic understanding of Unix is not hard to achieve (I have found my way around Solaris, Ubuntu and OS X, coming from a Windows background) - a few simple tutorials should get you up and running. For writing small school projects, there is not much you need to know: `cd`, `ls`, `mkdir`, `make`, `gcc` (be sure to use `g++` for C++ projects - that has bitten me on my Mac before...). Stay close to your home directory (`~`).
Doing your project on the target system will help you get certain stuff right: When doing these simple sockets and pthreads examples, I found compiling and linking them to be non-platform portable. On certain systems, linking in the libraries needs to be done this way, on others that way.
**BTW**: If you really *do* want to do this under Windows, your best bet is to have a POSIX environment under Windows. POSIX sockets are different to the Windows networking model if I remember correctly.
Try either MinGW or Cygwin. Both should give you the \*nix development environment under Windows. You can use your favorite text editor (a Windows port of vim?) and cmd.exe instead of bash for starting the compiler :)
**EDIT**: Sorry, if the tone is confrontational (according to comment). I will try to soften it a bit. It's just... I have seen quite a few people trying to learn C/C++ (or Java for that matter) with IDEs and have come to believe that they get in the way for starting off. Sure, you will need better tools for real life programs, but the overhead of project files etc. for school sample projects adds clutter. It also makes it harder to email your homework to your teacher - a zip with a bunch of .c and .h files and a makefile is really as simple as it gets... | If you need to do the coding in Windows, I would recommend using [mingw/msys](http://sourceforge.net/projects/mingw/) as a development environment. Msys implements a unix-like shell on windows, and mingw is a port of the [gnu compiler collection (gcc)](http://gcc.gnu.org/) and other gnu build tools to the windows platform. It is an open-source project, and well-suited to the task.
The install procedure can be a little bit tricky, but I found that the best place to start is [here](http://www.mingw.org/wiki/msys). | Cross platform programming | [
"",
"c++",
"c",
"windows",
"linux",
"cross-platform",
""
] |
What is the correct way to implement and architect a command line tool as a C# console application?
Concerns to address include proper parsing of command line variables, and the proper way to output text. While Console.WriteLine() is the most obvious choice for output, what are the circumstances in which one should instead opt to write to the standard error stream, .Error, .SetErrorStream, etc?
What is the proper way for the application to exit while returning a proper return code to the calling command?
How should the the CancelKeyPress event be implemented to interrupt the program? Is it only for use when an asynchronous operation is occurring on a separate thread?
Is there a concise guide to command line tool programming in C#, or even better an open source project or template which I could use to properly implement a relatively simple tool? | Error messages should be written to stderr aka Console.Error, and normal output to stdout aka Console.Out. This is particularly important for "filter" type console apps whose output (stdout) can be piped to another process, e.g. in a batch file.
Generally if you encounter an error, write an error message to Console.Error and return a non-zero result. Or if it's an exception, just don't bother handling it.
To return a result code, you can either pass it as an argument to Environment.Exit, set the Environment.ExitCode property, or return a non-zero value from main.
For simple console apps I would:
* have a helper class to parse the command line.
* have a facade class that provides a testable API for the functionality implemented by your command line tool. Like most .NET APIs, this would normally throw an exception if an error occurs.
* the main program simply uses the helper to parse the command line and calls the API passing the arguments passed from the command line. It optionally catches exceptions thrown from the API, logs them, writes a user-oriented error message to Console.Error and sets a non-zero return code.
But I wouln't consider this to be the one true way: there isn't really such a thing which is why you're unlikely to find the book you're looking for. | As to how to implement command parsing, I've succesfully used reflection and delegates before. They way it works is to decorate command methods with a special attribute you make yourself that states the method should be user-invokable, either through the method's name or a string specified in the attribute, i.e.:
```
[Command("quit")]
public void QuitApp()
{
...
}
```
On program startup you can scan a class for such methods, and store delegates that target them in a dictionary where the keys are the commands. This makes it easy to parse commands based on looking up the first word in a dictionary (amortized O(1) ) and easily extensible and maintanable for the future, as new commands are added simply adding separate methods. | Correct way to implement C# console application? | [
"",
"c#",
"command-line",
"console",
"arguments",
""
] |
Is there a call I can make to `new` to have it zero out memory like `calloc`? | Contrary what some are saying in their answers, it *is* possible.
```
char * c = new char[N]();
```
Will zero initialize all the characters (in reality, it's called value-initialization. But value-initialization is going to be zero-initialization for all its members of an array of scalar type). If that's what you are after.
Worth to note that it does also work for (arrays of) class-types without user declared constructor in which case any member of them is value initialized:
```
struct T { int a; };
T *t = new T[1]();
assert(t[0].a == 0);
delete[] t;
```
It's not some extension or something. It worked and behaved the same way in C++98 too. Just there it was called default initialization instead of value initialization. Zero initialization, however, is done in both cases for scalars or arrays of scalar or POD types. | No but it's fairly easy to create a new version that acts like calloc. It can be done in much the same way that the no-throw version of new is implemented.
SomeFile.h
```
struct zeromemory_t{};
extern const zeromemory_t zeromemory;
void* __cdcel operator new(size_t cbSize, const zeromemory_t&);
```
SomeFile.cpp
```
const zeromemory_t zeromemory;
void* _cdecl operator new(size_t cbSize, const zeromemory_t&)
{
void *mem = ::operator new(cbSize);
memset(mem,0,cbSize);
return mem;
}
```
Now you can do the following to get new with zero'd memory
```
MyType* pMyType = new (zeromemory) MyType();
```
Additionally you'd need to do other fun things like define new[] which is fairly straight forward as well. | C++: new call that behaves like calloc? | [
"",
"c++",
"new-operator",
"calloc",
""
] |
I have searched for this, but still can't seem to get this to work for me. I have an array of Id's associated with a user (their Organization Id). These are placed in an int[] as follows:
```
int[] OrgIds = (from oh in this.Database.OrganizationsHierarchies
join o in this.Database.Organizations on oh.OrganizationsId equals o.Id
where (oh.Hierarchy.Contains(@OrgId))
|| (oh.OrganizationsId == Id)
select o.Id).ToArray();
```
The code there isn't very important, but it shows that I am getting an integer array from a Linq query.
From this, though, I want to run another Linq query that gets a list of Personnel, that code is as follows:
```
List<Personnel> query = (from p in this.Database.Personnels
where (search the array)
select p).ToList();
```
I want to add in the where clause a way to select only the users with the OrganizationId's in the array. So, in SQL where I would do something like "where OrganizationId = '12' or OrganizationId = '13' or OrganizatonId = '17'."
Can I do this fairly easily in Linq / .NET? | While this is probably better suited to a join, you can use this:
```
List<Personnel> query =
(from p in this.Database.Personnels
where OrgIds.Contains(p.OrgID) select p).ToList();
```
This will translate into SQL something like..
```
where OrgID in (1,2,...,n)
``` | A check using the `Contains` method should do the job here.
```
var query = (from p in this.Database.Personnels
where OrgIds.Contains(p.OrganisationId)
select p).ToList();
``` | Linq query with Array in where clause? | [
"",
".net",
"sql",
"linq",
""
] |
I'm profiling in Python using `cProfile`. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?
**EDIT:**
I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it? | That may not answer your question directly, but will definitely help. If use the profiler with option --sort cumulative it will sort the functions by cumulative time. Which is helpful to detect not only heavy functions but the functions that call them.
```
python -m cProfile --sort cumulative myScript.py
```
There is a workaround to get the caller function:
```
import inspect
print inspect.getframeinfo(inspect.currentframe().f_back)[2]
```
You can add as many f\_back as you want in case you want the caller caller etc
If you want to calculate frequent calls you can do this:
```
record = {}
caller = inspect.getframeinfo(inspect.currentframe().f_back)[2]
record[caller] = record.get(caller, 0) + 1
```
Then print them by order of frequency:
```
print sorted(record.items(), key=lambda a: a[1])
``` | I almost always view the output of the cProfile module using [Gprof2dot](https://github.com/jrfonseca/gprof2dot), basically it converts the output into a graphvis graph (a `.dot` file), for example:
[](https://raw.githubusercontent.com/jrfonseca/gprof2dot/733b59379592c39d9f595de7323260d397b8d3b9/sample.png)
It makes it very easy to determine which function is slowest, and which function[s] called it.
Usage is:
```
python -m cProfile -o output.pstats path/to/your/script arg1 arg2
gprof2dot.py -f pstats output.pstats | dot -Tpng -o output.png
``` | Profiling in Python: Who called the function? | [
"",
"python",
"profiling",
""
] |
I have several navigation related functions which I would like to have no depth limits. These generate CSS menus, breadcrumb trails and the like.
I am stumped as to how I would make the functions follow each path to depth or to root without explicit looping.
The following is a typical example where I want the topmost parent of a page. The topmost will have a value of zero in its `parent` field.
Here is the explicitly looped version:
```
function topPg() {
$p = $this->retrieve("id = '$this->parent'");
if ($p->parent != 0) {
$gp = $this->retrieve("id = '$p->parent'");
if ($gp->parent != 0) {
$ggp = $this->retrieve("id = '$gp->parent'");
if ($ggp->parent != 0) {
$gggp = $this->retrieve("id = '$ggp->parent'");
// ad naseum
} else {
return $ggp;
}
} else {
return $gp;
}
} else {
return $p;
}
} // func
```
Anyone have advice or similar code or a tute link to help point the way? | It's easily expressable as a while loop:
```
$node = $this;
while ($node->parent != 0) {
$node = $this->retrieve("id = '$node->parent'");
}
```
`$node` now contains the topmost element. | [Welbog's](https://stackoverflow.com/users/52443/welbog) [answer](https://stackoverflow.com/questions/836494/recursing-properly/836543#836543) is the nicest, but for completeness I'll add another recursive solution:
```
function topPg() {
function foo($p) {
$gp = $this->retrieve("id = '$p->parent'");
return ($gp->parent == 0) ? $p : foo($gp);
}
return foo($this);
}
``` | Recursing Properly | [
"",
"php",
"recursion",
""
] |
I'd like my software to display a tutorial window when it first starts up and to have this window appear 'locked' to the right hand side of the main window such that, whenever I move the main window, the child will follow. How can I accomplish this? | As mentioned by [John Gietzen](https://stackoverflow.com/questions/843689/how-to-lock-a-window-to-another-winforms/843695#843695), you'll need to trap the movement of your main window and reposition the child window.
However, this will break down if the user moves the child window directly.
If you want to enforce that the two stay together always, you'd be much better trying to put these into a single window. Having two windows and trying to override the normal Windows behavior is probably not a clean approach - it will be more confusing than just trying to make a single "normal" window. | Generally, you will need to trap the OnMove event for the parent window and relocate the child window.
I do not believe that there is a WinAPI way to do this, so it will be a bit of manual coding. | How to lock a window to another? [winforms] | [
"",
"c#",
"winforms",
""
] |
I use Python 2.6 more than I use Leopard's default python installation, so I have it set as my main Python installation. But I'd rather use the default Python for a PyObjC program I'm working on. Is there any way to specify to only use it instead of Python 2.6? | Finally figured this one out myself. The key to this is to make the final executable link with /System/Library/Frameworks/Python.framework instead of /Library/Frameworks/Python.framework. | Try specifying the full path to the Python interpreter in the command line, something like:
```
/foo/bar/python2.6 script.py
/baz/python objcscript.py
```
You can also add a shebang to the beginning of your script (first line):
```
#! /foo/bar/python2.6 script.py
```
If you have the environment variable `PYTHONPATH` set, you might have to unset it or change it. | How do I choose which Python installation to run in a PyObjC program? | [
"",
"python",
"objective-c",
"macos",
"pyobjc",
""
] |
I've noticed that the native C++ application I'm working on has quite a large memory footprint (20MB) even before it enters any of my code.
(I'm referring to the "private bytes" measure in Windows, which as I understand it is the most useful metric).
I've placed a break point on the first line of the "main()" function and sure enough, the footprint is at 20MB when it reaches that.
The size of the EXE is only a couple of meg so that doesn't account for it.
I also deliberately removed all of the DLLs just to prove they weren't the cause. As expected it gets a "Dll not found" message, but the footprint is still 20MB!
So then I wondered that maybe it was the statically initialised objects which were the cause.
So, I added breakpoints to both "new" and "malloc". At the first hit to those (for the first static initialiser), the memory is already 20MB.
Anyone got any ideas about how I can diagnose what's eating up this memory?
Because it seems to be memory outside of the usual new/malloc paradigm, I'm struggling to understand how to debug.
Cheers,
John | It might be that you're pulling a lot of libraries with your app. Most of them get initialized before execution is handed over to your main(). Check for any non-standard libraries you're linking against.
EDIT: A very straightforward solution would be to create a new project and just link the libraries you're using one by one, checking memory usage each time. Even though it's an ugly approach, you should find the culprit this way.
There's probably a more elegant solution out there, so you might want to spare some time googling for (free) memory profiling solutions. | You might compile your app without debug information and see if this changes something, debugging ability eats quiet some memory. | Large initial memory footprint for native app | [
"",
"c++",
"windows",
"debugging",
"memory",
"native",
""
] |
I have a GridView that is bound with a dataset. I have my footer, whichis separated by the column lines. I want to merge 2 columns; how do I do that?
```
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
...
</ItemTemplate>
<FooterTemplate >
Grand Total:
</div>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age" SortExpression="Age">
<ItemTemplate>
...
</ItemTemplate>
<FooterTemplate >
<%# GetTotal() %>
</div>
</FooterTemplate>
</asp:TemplateField>
``` | untested code
1st footer template should include <%# GetTotal() %>
2nd footer template should be empty
```
Protected Sub Page_SaveStateComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.SaveStateComplete
Dim DG As GridView = GridView1
Dim Tbl As Table = DG.Controls(0)
Dim tr As GridViewRow
Dim i As Integer
Dim j As Integer
tr = Tbl.Rows(Tbl.Rows.Count - 1) 'this line assume last row is footer row
tr.Cells(0).ColumnSpan = 2 'if you have 3 columns then colspan = 3 instead
For j = 1 To 1 'if you have 3 columns then j = 1 To 2 instead
tr.Cells(j).Visible = False
Next
End Sub
``` | ```
protected void GridView1_OnRowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells.RemoveAt(1);
e.Row.Cells[0].ColumnSpan = 2;
}
}
``` | Can I Merge Footer in GridView? | [
"",
"c#",
".net",
"asp.net",
"html",
""
] |
I'm trying to pass data from one page to another.
> www.mints.com?name=something
How to read `name` using JavaScript? | Please see [this, more current solution](https://stackoverflow.com/a/55576345/18771) before using a custom parsing function like below, or a 3rd party library.
The a code below works and is still useful in situations where [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) is not available, but it was written in a time when there was no native solution available in JavaScript. In modern browsers or Node.js, prefer to use the built-in functionality.
---
```
function parseURLParams(url) {
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1),
pairs = query.replace(/\+/g, " ").split("&"),
parms = {}, i, n, v, nv;
if (query === url || query === "") return;
for (i = 0; i < pairs.length; i++) {
nv = pairs[i].split("=", 2);
n = decodeURIComponent(nv[0]);
v = decodeURIComponent(nv[1]);
if (!parms.hasOwnProperty(n)) parms[n] = [];
parms[n].push(nv.length === 2 ? v : null);
}
return parms;
}
```
Use as follows:
```
var urlString = "http://www.example.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
urlParams = parseURLParams(urlString);
```
which returns a an object like this:
```
{
"a" : ["a a"], /* param values are always returned as arrays */
"b b": ["b"], /* param names can have special chars as well */
"c" : ["1", "2"] /* an URL param can occur multiple times! */
"d" : [null] /* parameters without values are set to null */
}
```
So
```
parseURLParams("www.mints.com?name=something")
```
gives
```
{name: ["something"]}
```
---
**EDIT**: The [original version of this answer](https://stackoverflow.com/revisions/814628/3) used a regex-based approach to URL-parsing. It used a shorter function, but the approach was flawed and I replaced it with a proper parser. | It’s 2019 and there is no need for any hand-written solution or third-party library. If you want to parse the URL of current page in browser:
```
# running on https://www.example.com?name=n1&name=n2
let params = new URLSearchParams(location.search);
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]
```
If you want to parse a random URL, either in browser or in Node.js:
```
let url = 'https://www.example.com?name=n1&name=n2';
let params = (new URL(url)).searchParams;
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]
```
It’s making use of the [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) interface that comes with modern browsers. | How to read GET data from a URL using JavaScript? | [
"",
"javascript",
"parsing",
"url",
""
] |
I'd like to create a slice object from a string; right now the only way seems through a cumbersome hacky eval statement
```
class getslice:
def __getitem__(self, idx): return idx[0]
eval("getslice()[%s, 1]" %(":-1"))
```
thanks in advance.
**Edit**: Sorry if the original prompt was not clear, the input in this case was ":-1". The point was to parse the string. Ignacio Vazquez-Abrams's response at least solved the problem (and seems to work with reverse indexing as well), but I think my solution above is still more clear if not conceptually clean (and will work correctly if Python ever changes slicing syntax). | ```
slice(*[{True: lambda n: None, False: int}[x == ''](x) for x in (mystring.split(':') + ['', '', ''])[:3]])
``` | `slice(*map(lambda x: int(x.strip()) if x.strip() else None, mystring.split(':')))`
for single arg slices `'-1'` or `'1'` so when `mystring.split(':')==1` you just call `int(x)`
On request, took it out of comment section. | python create slice object from string | [
"",
"python",
"indexing",
"slice",
""
] |
For every stl container there is a MFC container available in visual c++.Which is better than the other one in what sense and what do you use?
I always use STL container is that wrong? | MFC collection classes do have some advantages *if* you are working within confines of MFC land. E.g. you get things like serialization (if your container elements inherit from CObject or similar) and some debugging support for "free". MSDN has a breakdown of how to choose between different MFC collection types [here](<http://msdn.microsoft.com/en-us/library/y1z022s1(VS.80).aspx)>.
As a default though, I would lean towards the STL classes. | I would always prefer the STL containers because of the portability.
MFC containers will nearly never be available on Linux.
Even if you don't plan to use you're code on Linux...you never know what the future brings. | Which one to use c++ stl container or the MFC container? | [
"",
"c++",
"visual-c++",
"mfc",
"stl",
"containers",
""
] |
I would like to get some of your ideas about
* **resource name / categorizing**
* **place of resources**
Let me just give you the scope of the application:
* 3 or more supported languages
* 3 MVC websites [with a lot of shared resources, and also some unique resources]
* 1 shared MVC extensions library
* 1 core business library, which has shared functionality, and business objects [also contains resources]
* 3 business libraries that have specific business logic for the three websites [also with resources]
* 1 SQL 2008 database shared among all websites, sends sometimes localized emails.
I would like for it to be easily maintainable (so also easily exported/imported for translation), not to be duplicate (since we have common resources), and understandable for everybody that comes in contact with the code
**Place of the resources:**
* should I create one assembly containing all the translations? And create a reference to that assembly in my projects (even if possible adding it to SQL server)?
* or should I use source control to keep all the resource files in sync?
* some other ideas?
**resource name / categorizing:**
So we have localized emails, text on buttons (command like texts), labels, error messages, information messages etc etc.
How do you categorize these items into resources files, do you just dump them all in one file? Or do you categorize them into a *strings* , and an *emails* resource files, which categorization do you use? | We have a similar system setup; What we use is a database just for the text. Then we have a common assembly that provides methods to get localized strings along with a custom expression provider so we can use standard <%$ Resources:zzzz %> syntax inside aspx/ascx files.
Our database is set up so we can provide a default text for a token, along with a localized version and an application (eg, simplified our "Translation" table has the following columns: (Token, Locale, Application, NativeText) ). This way we can provide overrides for specific applications if we need to.
This has the advantage that we can also provide a Translation Editor (we don't currently, but it is a possible future option), and also exporting/importing translations isn't too bad (not claiming that it is without fault - I think translation is going to be a hard topic no matter what).
We do still use standard resource files, but only for strings that are truly application specific and also unlikely to change; I'd advise against this. It just means we can't create the list of strings to translate as easily. | As Groo mentioned, one mega-assembly would be a bad a idea since it would cause a coupling issue. For example, if you wanted to change the button text in web site 1, you'd have to update that assembly, which then causes an update to web sites 2 and 3, even though 2 and 3 didn't need any changes at all. Just like with anything else, you want to isolate your changes where possible so that if something breaks, it breaks as little as possible.
I would define your assemblies so that you can share some as needed, but have others that contain resources needed only for individual projects. From the description you've given, here is how I would structure your resources:
* 1 UI-related resource file shared across web sites
* 3 site-specific UI-related resource files
* 1 business logic-related resource file in the core library
* 3 site-specific business logic-related resource files, stored in their respective business logic projects
In some cases above I may have mixed up where you just need a resource file and where you need a full standalone assembly, but the division of resources is essentially the same. And of course, you'll need one copy of each of the above files per language.
I would absolutely recommend storing these files in source control. They're a part of the source of your app, just like the code, and source control will give you the same benefits.
Regarding SQL Server, when you say that it sends localized e-mails, do you mean that it does that through a stored procedure, or that some other code uses data from the database to send e-mails? Either way, I don't have much of an answer. I don't know how SQL Server itself handles localization, and if it's an app that's sending the e-mails, it depends a lot on where the localized text needs to come from.
Finally, regarding your question on categorizing the resources, it really just depends on what seems the most natural to you and (I assume) your team. From what you've described, it sounds like you might want to split your resources out into text that will be shown on web pages, and text that will be included in emails, but it's hard to say. This is a very personal choice, and it has no effect on the code other than making it easier for everyone to find the resource they're looking for, so just go with what makes the most sense to you. | n-Tiered .NET application localization guidelines | [
"",
".net",
"sql",
"localization",
"naming-conventions",
""
] |
How can I create F# dll and call it in C#?
Thank you | To create a DLL in F#, you should set the output type to class library in project properties. Use Add Reference dialog as mentioned before to add the reference in your C# project. | If you are using the latest version, all you should need to do is set the project type to 'F# Library' when you create the project. | call F# dll in C# | [
"",
"c#",
"dll",
"f#",
"reference",
""
] |
Basically I need to do String.IndexOf() and I need to get array of indexes from the source string.
Is there easy way to get array of indexes?
Before asking this question I have Googled a lot, but have not found easy solution to solve this simple problem. | ```
var indexs = "Prashant".MultipleIndex('a');
//Extension Method's Class
public static class Extensions
{
static int i = 0;
public static int[] MultipleIndex(this string StringValue, char chChar)
{
var indexs = from rgChar in StringValue
where rgChar == chChar && i != StringValue.IndexOf(rgChar, i + 1)
select new { Index = StringValue.IndexOf(rgChar, i + 1), Increament = (i = i + StringValue.IndexOf(rgChar)) };
i = 0;
return indexs.Select(p => p.Index).ToArray<int>();
}
}
``` | How about this extension method:
```
public static IEnumerable<int> IndexesOf(this string haystack, string needle)
{
int lastIndex = 0;
while (true)
{
int index = haystack.IndexOf(needle, lastIndex);
if (index == -1)
{
yield break;
}
yield return index;
lastIndex = index + needle.Length;
}
}
```
Note that when looking for "AA" in "XAAAY" this code will now only yield 1.
If you really need an array, call `ToArray()` on the result. (This is assuming .NET 3.5 and hence LINQ support.) | Finding multiple indexes from source string | [
"",
"c#",
".net",
"algorithm",
"string",
""
] |
I am a latecomer to XML - have to parse an XML file. Our company is using xerces already so I managed to cobble together a sample app (SAX) that displays all the data in a file. However, after parsing is complete I was expecting to be able to call the parser or some other entity that had an internal representation of the file and iterate through the fields/data.
Basically I want to be able to hand it some key or other string(s) and get back strings or collections of key/value pairs. I do not see that. It seems pretty obvious to me that that is a good thing to do. Am I missing something?
Is the DOM parsing what I want, or does that fall short too? | Xerces provides both SAX and DOM processing. SAX parsing doesn't construct a model, so once parsing is finished there is nothing to examine or iterate through. DOM processing produces a tree-structured model which gives you what you want. | Check out the beginner's sample in this page
[YoLinux Tutorial on Parsing XML](http://www.yolinux.com/TUTORIALS/XML-Xerces-C.html) | getting XML data from Xerces (c++) | [
"",
"c++",
"xml",
"xerces",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.