Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm using ASP.NET 2.0 with a Master Page, and I was wondering if anyone knew of a way to detect when the fields within a certain `<div>` or `fieldset` have been changed (e.g., marked '`IsDirty`')?
You could bind the Change event for all inputs and flag a variable as true. Like this. ``` var somethingChanged = false; $(document).ready(function() { $('input').change(function() { somethingChanged = true; }); }); ``` But, keep in mind that if the user changes something, then changes back to the original values, it will still be flagged as changed. **UPDATE:** For a specific div or fieldset. Just use the id for the given fieldset or div. Example: ``` var somethingChanged = false; $(document).ready(function() { $('#myDiv input').change(function() { somethingChanged = true; }); }); ```
## Quick (but very dirty) solution This is quick, but it won't take care of `ctrl+z` or `cmd+z` and it will give you a false positive when pressing `shift`, `ctrl` or the `tab` key: ``` $('#my-form').on('change keyup paste', ':input', function(e) { // The form has been changed. Your code here. }); ``` [Test it with this fiddle.](https://jsfiddle.net/a2otmLxk/) --- ## Quick (less dirty) solution This will prevent false positives for `shift`, `ctrl` or the `tab` key, but it won't handle `ctrl+z` or `cmd+z`: ``` $('#my-form').on('change keyup paste', ':input', function(e) { var keycode = e.which; if (e.type === 'paste' || e.type === 'change' || ( (keycode === 46 || keycode === 8) || // delete & backspace (keycode > 47 && keycode < 58) || // number keys keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns) (keycode > 64 && keycode < 91) || // letter keys (keycode > 95 && keycode < 112) || // numpad keys (keycode > 185 && keycode < 193) || // ;=,-./` (in order) (keycode > 218 && keycode < 223))) { // [\]' (in order)) // The form has been changed. Your code here. } }); ``` [Test it with this fiddle.](https://jsfiddle.net/h5k60vL7/22/) --- ## A complete solution If you want to handle **all** the cases, you should use: ``` // init the form when the document is ready or when the form is populated after an ajax call $(document).ready(function() { $('#my-form').find(':input').each(function(index, value) { $(this).data('val', $(this).val()); }); }) $('#my-form').on('change paste', ':input', function(e) { $(this).data('val', $(this).val()); // The form has been changed. Your code here. }); $('#my-form').on('keyup', ':input', function(e) { if ($(this).val() != $(this).data('val')) { $(this).data('val', $(this).val()); // The form has been changed. Your code here. } }); ``` [Test it with this fiddle.](https://jsfiddle.net/h5k60vL7/25/)
Detecting data changes in forms using jQuery
[ "", "javascript", "jquery", "" ]
* I have installed the new `asp:chart` control on my machine and have built an app that uses it. * All is working well so far. Now I want to deploy my app in a hosted environment. * If my hosting provider doesn't have the `asp:chart` control installed can I get my app to work by putting the `.dll` in the bin folder? (I guess I am asking if it has to be found in the Gac)
Apart from deploying the assembly to the bin folder, you also need to configure a folder with write permission to temporarily store the chart images. In web.config under ``` <appSettings> <add key="ChartImageHandler" value="storage=file;timeout=20;dir=D:\TEMPDUMP\;"/> ... ```
It does not have to be in the GAC. Applications will look in the GAC if it can't find it in the bin folder.
Does the new asp:chart control need to be installed on the server or can it be used from the bin folder
[ "", "c#", "asp.net", "hosting", "charts", "" ]
I write a lot of little scripts that process files on a line-by-line basis. In Perl, I use ``` while (<>) { do stuff; } ``` This is handy because it doesn't care where the input comes from (a file or stdin). In Python I use this ``` if len(sys.argv) == 2: # there's a command line argument sys.stdin = file(sys.argv[1]) for line in sys.stdin.readlines(): do stuff ``` which doesn't seem very elegant. Is there a Python idiom that easily handles file/stdin input?
The fileinput module in the standard library is just what you want: ``` import fileinput for line in fileinput.input(): ... ```
``` import fileinput for line in fileinput.input(): process(line) ``` This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty.
Python equivalent of Perl's while (<>) {...}?
[ "", "python", "stdin", "" ]
I have the following method inside `class DBConnection`. I call the method like this: `SQLiteConnection conn = DBConnection.OpenDB();` when I want to open an connection, so that I can execute my queries. I can call a similar method when I want to close the connection. The method: ``` public static SQLiteConnection OpenDB() { try { //Gets connectionstring from app.config string myConnectString = ConfigurationManager.ConnectionStrings[ "LegMedSQLLite.Properties.Settings.LegMedSQLLiteDBConnectionString"].ConnectionString; var conn = new SQLiteConnection(myConnectString); conn.Open(); return conn; } catch (SQLiteException e) { MessageBox.Show(e.ToString(), "TEST"); return null; } } ``` This all works fine and dandy. The problem is the try-catch though. Let us imagine the following scenario: * The database file has been moved/delete. The exception will never be thrown. Actually, the first catch I stumble upon is when I execute my first query - where it figures that there is no such table(s) and it throws its own exception. I was stunned by this weird phenomenon, but I soon found out that SQLite creates a new **empty** database. By empty is mean **no tables**, nothing, just an SQLite database file with the same name as the old database which was supposed to be there. This is an issue, I want the application to know if there is something wrong (database not found, corrupted, being used by another process etc.) as soon as I try to call `SQLiteConnection conn = DBConnection.OpenDB();`. Naturally, I could try call a File.Exists in my method, but that doesn't seem like a proper solution. Any help?
If you're using System.Data.SQLite, you can add "**`FailIfMissing=True`**" to your connection string. `SQLiteConnection.Open()` will throw a `SQLiteException` if the database file does not exist. ``` string ConnectString = "Data Source=file.sdb; FailIfMissing=True"; DbConnection db = new SQLiteConnection(ConnectString); db.Open(); // Fails if file.sdb does not exist ``` See [SQLite Connection String Samples](http://www.connectionstrings.com/sqlite) for another example, look for "Disable create database behaviour". If you're using Microsoft.Data.Sqlite, you can specify an [open mode](https://github.com/dotnet/efcore/blob/916b8d48a4f38553cd3f6c33dd4c841f56454fe6/src/Microsoft.Data.Sqlite.Core/SqliteOpenMode.cs) with `Mode=ReadWrite` instead of `Mode=ReadWriteCreate`.
If you want to detect database corruption issues on start up , you can execute the command pragma integrity\_check; or pragma quick\_check; ( which is faster, but less thorough ) This returns a single row with the value "ok". Otherwise it will report errors that it encounters.
Make SQLite connection fail if database is missing? (deleted/moved)
[ "", "c#", "sqlite", "" ]
I can't seem to figure out how to make a resize drag handle in Java Swing. If you're not sure what I mean, open up the "Ask Question" page on this website and look at the bottom of the text area. It has a bar which you can drag in order to change the size of the area. I'm looking for a way to do this in Java Swing. I don't even know where to look at this point. Any help would be appreciated.
In my opinion, the drag handle that's used on the Stack Overflow posting form most closely resembles that of a vertical [JSplitPane](http://java.sun.com/javase/6/docs/api/javax/swing/JSplitPane.html), both in appearance and functionality.
I haven't done it either, but since you're just looking for a start, I'll give it a shot. I would put a `JComponent` of some sort (possibly a custom subclass) at the spot where you want the handle to appear (I'm assuming you can manipulate layout managers well enough to do that part). Then, I would add a `MouseListener` and a `MouseMotionListener` -- probably the same class, a subclass of `MouseAdapter` -- to the component. When a click and drag is detected, I would resize the component that the handle is attached to. Does that help any?
Dragging handle in Java Swing
[ "", "java", "swing", "" ]
I am getting more and more spam emails recently. I already validate my email using regular expression, all the emails must be something like this: xxx@xxxx.xxx But the problem i have now is, there are alot spammers, type hsdjsdhgf@gmail.com, iluvhahahahah@yahoo.com, these emails are not existed, because i tried to send email to them. How to avoid those email?
You're barking up the wrong tree. The better way to stop spam is by filtering them out in other ways from the form. If you are not a fan of CAPTCHAs like [reCAPTCHA](http://recaptcha.net/), you should look into what is known as ["Honeypots"](http://www.rustylime.com/show_article.php?id=676). Essentially, add an extra field to your form with a common name like "email" and hide it with CSS. Mark it as "leave blank" for anyone browsing with styles disabled. If the field has a value in it, it is most likely a bot, so throw the submission out. Voila. They work really well for your average mid-size website that spammers don't really care to specifically set out to beat. Check out [this related question](https://stackoverflow.com/questions/111576/when-the-bots-attack). All things considered, I like the honeypots because it is usually enough to deter 99% of your spamming while not making your average user have to do anything. This is important. To quickly answer your original question: the only way to verify the email is valid is to actually send out an email to that address and see if it bounces. It is generally not worth the hassle, however.
If they are signing up for a newsletter or something that you will email them more than once I like to send a confirmation email to them which they must click a link to verify that it is a real email. If they dont confirm after a few days then you know you can delete it. If they do confirm then you know that it is a real person. You will still get bounce backs when you first email them but it will eliminate reoccurring bounce backs. I also like CAPTCHAs or if you want something simpler ask them to enter the first letter of the title of your website (or some other word that will always remain the same on the page), it works for smaller to mid sized sites but is mostly effective.
Is there a way to check if the email is EXISTED using php?
[ "", "php", "email", "spam", "" ]
I have a txt file and each line has a set of random strings, I need to select only the lines that contains only the characters: 1234567890qwertyuiopasdfghjklzxcvbnm-.\_~ I'm reading line by line and verifying char by char, I don't think it's the best way to do that, and I think a RegEx would be perfect. So can anybody help with with a pattern for this? thanks!
``` /^[-0-9a-z._~]*$/ ^ :: matches the start of a string/start of a line [ :: start of a character class, means match any one of the contained characters - :: dash has a special meaning in character classes, so to avoid having it interpreted for its special meaning, list it first 0-9 :: shorthand for 0123456789 in a character class a-z :: shorthand for abcdefghijklmnopqrstuvwxyz in a character class ._~ :: means exactly these characters in a character class ] :: end of the character class * :: match zero or more of the previous atom (in this case, the character class) $ :: matches the end of a string/end of a line ```
If I understand you well, you could go with this: ``` /^([-0-9a-zA-Z._~]\n)+$/ ``` It is case-insensitive, check for end of line and doesn't match an empty line.
Help with regex pattern
[ "", "c#", "regex", "" ]
So I got into a friendly argument with a co-worker over a piece of code: ``` public sealed class NewObject { private string _stuff = string.Empty; public string Stuff { get { return GetAllStuff(); } } private string GetAllStuff() { //Heavy string manipulation of _stuff } public NewObject(string stuffToStartWith) { _stuff = stuffToStartWith; } public static NewObject operator +(NewObject obj1, NewObject obj2) { if (obj1 == null) throw new ArgumentNullException(); if (obj2 == null) throw new ArgumentNullException(); NewObject result = new NewObject(string.Empty); result._stuff = String.Concat(obj1._stuff, obj2._stuff); return result; } } ``` The argument was over the operator override. My co-worker feels that it's not best programming practice to set values of private fields anywhere but the constructor. The solution proposed by my co-worker was to refactor the name of the `Stuff` property to `AllStuff` and add a property, `Stuff`, that has a `get` AND `set` accessor and use the new `Stuff` property in the operator override. Making it look like this: ``` public static NewObject operator +(NewObject obj1, NewObject obj2) { if (obj1 == null) throw new ArgumentNullException(); if (obj2 == null) throw new ArgumentNullException(); NewObject result = new NewObject(string.Empty); result.Stuff = String.Concat(obj1.Stuff, obj2.Stuff); return result; } ``` I disagree. I feel the first way is better since it keeps the property read-only outside the class. My question is, which way is the best practice for object-oriented design?
You could give yourself a `private set` on the property (which would retain visibility or lack thereof while allowing you to use property syntax), but that doesn't really address the point. Within the class, I say that variables are fair game. Anywhere outside, including inherited classes, should `get` and `set` the property, but within the declaring class I say it's OK to assign the private member.
The general issue has to do with a contract policy. The notion of a (public set) property is that when it is called, other actions may be taken in addition to the semantic notion of changing state. For example, calling a setter may fire events, trigger a peripheral device and so on. Your coworker is saying that by not using the property, you're side-stepping the contract and no events will be fired. So here's you should do from your coworker's point of view: ``` this.Prop = CalculateSomeValue(); if (this.Prop < kPropMin) { this.Prop = kPropMin; } else if (this.Prop > kPropMax * 2) { this.Prop = kPropMax * 2; } this.Prop = this.Prop / 2; ``` Now, this is a contrived case, but I've just hit a possible heavyweight property up to three times in the get and up to three times in the set, and one of those might be illegal (setting to kHighLimit / 2). I can work around this by using a local and calling the set precisely once at the end. I'd rather just mess with the field, though. I think a better approach is to take it pragmatically: use the property inside your class if and only if you want to invoke all the side-effects of a set or a get, otherwise obey the spirit of the property instead. -- clarification -- By obey the spirit of the property, let's say that my set property looks like this: ``` bool PropValueOutOfRange(int val) { return val < kPropMin || val > kPropMax; } public int Prop { set { if (PropValueOutOfRange(value)) throw new ArgumentOutOfRangeException("value"); if (PropValueConflictsWithInternalState(value)) throw new ArgumentException("value"); _prop = value; NotifyPeriperalOfPropChange(_prop); FirePropChangedEvent(/* whatever args might be needed */); } } ``` In this I've factored out a lot of the grungy details, but that lets me reuse them. So now I feel confident in touching the private field \_prop because I have the same infrastructure for making sure that I keep it in range and to notify the peripheral and fire the event. This lets me write this code: ``` _prop = CalculateSomeValue(); if (_prop < kPropMin) _prop = kPropMin; else if (_prop > kPropMax * 2) _prop = kPropMax; _prop /= 2; NotifyPeripheralOfPropChange(); FirePropChangedEvent(); ``` I'm using the same tools as those used to build the property so I'm working within the spirit of the property. I maintain correct range (but don't throw - I know better, I'm the implementer), hit the peripheral and fire events, and I do it thoughtfully, readably, and efficiently - not indiscriminately.
Should I use a Field or Property within the class to set values
[ "", "c#", "" ]
Is it preferred to use "Id" as the column name for a primary key or "[TableName]Id" as a naming convention? > Table: Account > Primary Key: Id -- versus -- > Table: Account > Primary Key: AccountId It seems to be split about 50% / 50% in the implementations that I've seen. What are the advantages and disadvantages in each approach? **Follow-up:** Does it make sense to use one convention in my database, and another on my entities in code? Or should I keep them consistent? How would does this work best in most ORMs?
TableNameID for clarity 1. Improve JOIN readability 2. Clarity, say, when multiple FK "ID" columns (PK matches FK) 3. ID is a reserved keyword
I use ID. How would you set up User table with an Account ID as a foreign key? Would you name that column AccountAccountID or AccountID? But the most important part is to be consistent in my opinion, whichever way you choose. **Edit**: I think in reading my comment the logic of my argument is off, since obviously you wouldn't ever call a field AccountAccountID. But at first glance using [TableName]ID as the primary key and [TableName]ID as the foreign key as well *feels* weird to me. It seems like you're using two different rules for two things that should follow the same set of standards. Also I think that Account.ID and User.AccountID is more readable and semantically correct.
Id or [TableName]Id as primary key / entity identifier
[ "", "sql", "sql-server", "database-design", "orm", "naming-conventions", "" ]
Is there a free package for reading, manipulating and writing ASN.1 in Java? It must be: 1. Free 2. Lightweight 3. Self-contained (without external dependencies on, e.g. Apache commons) 4. Java 5 (not Java 6), and Java 4 is preferred.
The following project looks promising: <http://www.chaosinmotion.com/wiki/index.php?title=ASN.1_Library> It is provided under a liberal BSD-style licence. It is small, 41 classes compiling to 55KiB. It compiled clean with no dependencies to Java 3.
The free [BouncyCastle](http://www.bouncycastle.org/docs/docs1.4/org/bouncycastle/asn1/package-summary.html) library provides low-level ASN.1 parsing. You don't need to install BC as a provider to use the ASN.1 capabilities. It has different versions for 1.4 and up. It has no external dependencies. As the default bundle contains all of the BC provider classes, you may want to repackage it if you want something more compact.
Is there a free package for reading, manipulating and writing ASN.1 in Java?
[ "", "java", "package", "asn.1", "" ]
I have a web service that is working fine in one environment but not in another. The web service gets document meta data from SharePoint, it running on a server where I cant debug but with logging I confirmed that the method enters and exits successfully. What could be the reason for the errors? The error message is, ``` The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://CompanyName.com.au/ProjectName:GetDocumentMetaDataResponse. The InnerException message was 'Error in line 1 position 388. 'Element' 'CustomFields' from namespace 'http://CompanyName.com.au/ProjectName' is not expected. Expecting element 'Id'.'. Please see InnerException for more details. ``` The InnerException was System.ServiceModel.Dispatcher.NetDispatcherFaultException was caught Message="The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter <http://CompanyName.com.au/ProjectName:GetDocumentMetaDataResponse>. The InnerException message was ``` 'Error in line 1 position 388. 'Element' 'CustomFields' from namespace 'http://CompanyName.com.au/ProjectName' is not expected. Expecting element 'Id'.'. Please see InnerException for more details." Source="mscorlib" Action="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher/fault" StackTrace: Server stack trace: at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest) at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameter(XmlDictionaryReader reader, PartInfo part, Boolean isRequest) at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameters(XmlDictionaryReader reader, PartInfo[] parts, Object[] parameters, Boolean isRequest) at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest) at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest) at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeReply(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.ProxyOperationRuntime.AfterReply(ProxyRpc& rpc) at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoap.GetDocumentMetaData(GetDocumentMetaDataRequest request) at CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoapClient.CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoap.GetDocumentMetaData(GetDocumentMetaDataRequest request) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\External\CompanyName.ProjectName.External.Sharepoint.WebServiceProxies\Service References\SharepointProjectNameSiteService\Reference.cs:line 2141 at CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoapClient.GetDocumentMetaData(ListSummaryDto listSummary, FileCriteriaDto criteria, List`1 customFields) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\External\CompanyName.ProjectName.External.Sharepoint.WebServiceProxies\Service References\SharepointProjectNameSiteService\Reference.cs:line 2150 at CompanyName.ProjectName.Services.Shared.SharepointAdapter.GetDocumentMetaData(ListSummaryDto listSummary, FileCriteriaDto criteria, List`1 customFields) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\Services\CompanyName.ProjectName.Services\Shared\SharepointAdapter.cs:line 260 at CompanyName.ProjectName.Services.Project.ProjectDocumentService.SetSharepointDocumentData(List`1 sourceDocuments) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\Services\CompanyName.ProjectName.Services\Project\ProjectDocumentService.cs:line 1963 at CompanyName.ProjectName.Services.Project.ProjectDocumentService.GetProjectConversionDocumentsImplementation(Int32 projectId) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\Services\CompanyName.ProjectName.Services\Project\ProjectDocumentService.cs:line 3212 InnerException: System.Runtime.Serialization.SerializationException Message="Error in line 1 position 388. 'Element' 'CustomFields' from namespace 'http://CompanyName.com.au/ProjectName' is not expected. Expecting element 'Id'." Source="System.Runtime.Serialization" StackTrace: at System.Runtime.Serialization.XmlObjectSerializerReadContext.ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, Int32 memberIndex, Int32 requiredIndex, XmlDictionaryString[] memberNames) at System.Runtime.Serialization.XmlObjectSerializerReadContext.GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, Int32 memberIndex, Int32 requiredIndex, ExtensionDataObject extensionData) at ReadFileMetaDataDtoFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] ) at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns) at ReadArrayOfFileMetaDataDtoFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString , XmlDictionaryString , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns) at ReadMetaDataSearchResultsDtoFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] ) at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns) at ReadGetDocumentMetaDataResponseBodyFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] ) at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract) at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns) at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName) at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName) at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName) at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest) InnerException: ```
I have a solution for this but not sure on the reason why this would be different from one environment to the other - although one big difference between the two environments is WSS svc pack 1 was installed on the environment where the error was occurring. To fix this issue I got a good clue from this link - <https://web.archive.org/web/20090506064853/http://silverlight.net/forums/t/22787.aspx> ie to "please check the Xml Schema of your service" and "the sequence in the schema is sorted alphabetically" Looking at the wsdl generated I noticed that for the serialized class that was causing the error, the properties of this class were not visible in the wsdl. The Definition of the class had private setters for most of the properties, but not for CustomFields property ie.. ``` [Serializable] public class FileMetaDataDto { . . a constructor... etc and several other properties edited for brevity . public int Id { get; private set; } public string Version { get; private set; } public List<MetaDataValueDto> CustomFields { get; set; } } ``` On removing private from the setter and redeploying the service then looking at the wsdl again, these properties were now visible, and the original error was fixed. So the wsdl before update was ``` - <s:complexType name="ArrayOfFileMetaDataDto"> - <s:sequence> <s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" /> </s:sequence> </s:complexType> - <s:complexType name="FileMetaDataDto"> - <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" /> </s:sequence> </s:complexType> ``` The wsdl after update was ``` - <s:complexType name="ArrayOfFileMetaDataDto"> - <s:sequence> <s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" /> </s:sequence> </s:complexType> - <s:complexType name="FileMetaDataDto"> - <s:sequence> <s:element minOccurs="1" maxOccurs="1" name="Id" type="s:int" /> <s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="Title" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="ContentType" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="Icon" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="ModifiedBy" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="ModifiedDateTime" type="s:dateTime" /> <s:element minOccurs="1" maxOccurs="1" name="FileSizeBytes" type="s:int" /> <s:element minOccurs="0" maxOccurs="1" name="Url" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="RelativeFolderPath" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="DisplayVersion" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="Version" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" /> <s:element minOccurs="0" maxOccurs="1" name="CheckoutBy" type="s:string" /> </s:sequence> </s:complexType> ```
Are you sure your web service is deployed correctly to the enviornment that is NOT working. Looks like the type is out of date.
How do I solve this error, "error while trying to deserialize parameter"
[ "", "c#", "web-services", "sharepoint", "" ]
``` typeof(string).IsPrimitive == false typeof(int).IsPrimitive == true typeof(MyClass).IsClass == true typeof(string).IsClass == true typeof(string).IsByRef == false typeof(MyClass).IsByRef == true // correction: should be false (see comments below) ``` I have a method that instantiates a new instance of T and, if it's a "complex" class, fills its properties from a set of source data values. (a) If T is a simple type (e.g. a string or an int or anything else similar), a quick conversion from the source data to T is to be performed. (b) If T is a class (but not something simple like string), then I'll use Activator.CreateInstance and do a bit of reflection to populate the fields. Is there a quick and simple way to tell if I should use method (a) or method (b)? This logic will be used inside a generic method with T as the type argument.
String is probably a special case. I think I would do..... ``` bool IsSimple(Type type) { return type.IsPrimitive || type.Equals(typeof(string)); } ``` --- **Edit:** Sometimes you need to cover some more cases, like enums and decimals. Enums are a special kind of type in C#. Decimals are structs like any other. The problem with the structs is that they may be complex, they may be user defined types, they may be just a number. So you don't have any other chance than knowing them to differentiate. ``` bool IsSimple(Type type) { return type.IsPrimitive || type.IsEnum || type.Equals(typeof(string)) || type.Equals(typeof(decimal)); } ``` Handling nullable counterparts are also a bit tricky. The nullable itself is a struct. ``` bool IsSimple(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { // nullable type, check if the nested type is simple. return IsSimple(type.GetGenericArguments()[0]); } return type.IsPrimitive || type.IsEnum || type.Equals(typeof(string)) || type.Equals(typeof(decimal)); } ``` Test: ``` Assert.IsTrue(IsSimple(typeof(string))); Assert.IsTrue(IsSimple(typeof(int))); Assert.IsTrue(IsSimple(typeof(decimal))); Assert.IsTrue(IsSimple(typeof(float))); Assert.IsTrue(IsSimple(typeof(StringComparison))); // enum Assert.IsTrue(IsSimple(typeof(int?))); Assert.IsTrue(IsSimple(typeof(decimal?))); Assert.IsTrue(IsSimple(typeof(StringComparison?))); Assert.IsFalse(IsSimple(typeof(object))); Assert.IsFalse(IsSimple(typeof(Point))); // struct in System.Drawing Assert.IsFalse(IsSimple(typeof(Point?))); Assert.IsFalse(IsSimple(typeof(StringBuilder))); // reference type ``` **Note to .NET Core** As DucoJ points out in [his answer](https://stackoverflow.com/questions/863881/how-do-i-tell-if-a-type-is-a-simple-type-i-e-holds-a-single-value/38998370#38998370), some of the used methods are not available on the class `Type` in .NET core anymore. Fixed code (I hope it works, I couldn't try myself. Otherwise please comment): ``` bool IsSimple(Type type) { var typeInfo = type.GetTypeInfo(); if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>)) { // nullable type, check if the nested type is simple. return IsSimple(typeInfo.GetGenericArguments()[0]); } return typeInfo.IsPrimitive || typeInfo.IsEnum || type.Equals(typeof(string)) || type.Equals(typeof(decimal)); } ```
Using a solution based on `TypeConverter` is also a nice and simple way to model this. Say you have this implementation for instance: ``` public static bool IsSimple(this Type type) => TypeDescriptor.GetConverter(type).CanConvertFrom(typeof(string)); ``` This returns `true` for: * All primitive types * All enums * `string`s * `decimal`s * `DateTime` * `DateTimeOffset` * `TimeSpan` * `Uri` * `Guid` * `Nullable<>` of any of the types above * numerous other types that have native `TypeConverter`s implemented (see [here](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.typeconverter?view=net-5.0) on the `Derived` section) This approach works well since most frameworks support `TypeConverter`s natively, like XML and Json serialization libraries, and you can then use the same converter to parse the values while reading.
How do I tell if a type is a "simple" type? i.e. holds a single value
[ "", "c#", ".net", "generics", "" ]
I need to byte-shift a text file. I know absolutely nothing about perl, but I found a perfectly working piece of code in perl called [moz-byteshift.pl](http://www.alain.knaff.lu/howto/MozillaCustomization/moz-byteshift.pl) ([documentation](http://www.alain.knaff.lu/howto/MozillaCustomization/locked.html)). This does exactly what I want to do, but I need to do it in C#. Here's the source code of the perl file: ``` #!/usr/bin/perl # To perform a byteshift of 7 # To decode: moz-byteshift.pl -s -7 <infile >outfile # To encode: moz-byteshift.pl -s 7 <infile >outfile # To perform a byteshift of 13 # To decode: moz-byteshift.pl -s -13 <infile >outfile # To encode: moz-byteshift.pl -s 13 <infile >outfile use encoding 'latin1'; use strict; use Getopt::Std; use vars qw/$opt_s/; getopts("s:"); if(!defined $opt_s) { die "Missing shift\n"; } my $buffer; while(1) { binmode(STDIN, ":raw"); my $n=sysread STDIN, $buffer, 1; if($n == 0) { last; } my $byte = unpack("c", $buffer); $byte += 512 + $opt_s; $buffer = pack("c", $byte); binmode(STDOUT, ":raw"); syswrite STDOUT, $buffer, 1; } ``` If someone could at least explain how the perl script works, that would be great. Sample code of the equivalent in C# would be better. =) Thanks for the help.
What the code does is this: Read each byte from standard input one by one (after switching it into raw mode so no translation occurs). The unpack gets the byte value of the character just read so that a '0' read turns into 0x30. The latin1 encoding is selected so that this conversion is consistent (e.g. see <http://www.cs.tut.fi/~jkorpela/latin9.html>). Then the value specified on the command line with the -s option is added to this byte along with 512 to simulate a modulus operation. This way, -s 0, -s 256 etc are equivalent. I am not sure why this is needed because I would have assumed the following pack took care of that but I think they must have had good reason to put it in there. Then, write the raw byte out to standard input. Here is what happens when you run it on a file containing the characters 012345 (I put the data in the **DATA** section): ``` E:\Test> byteshift.pl -s 1 | xxd 0000000: 3132 3334 3536 0b 123456. ``` Each byte value is incremented by one. ``` E:\Test> byteshift.pl -s 257 | xxd 0000000: 3132 3334 3536 0b 123456. ``` Remember 257 % 256 = 1. That is: ``` $byte += $opt_s; $byte %= 256; ``` is equivalent to the single step used in the code. Much later: OK, I do not know C# but here is what I was able to piece together using online documentation. Someone who knows C# should fix this: ``` using System; using System.IO; class BinaryRW { static void Main(string[] args) { BinaryWriter binWriter = new BinaryWriter( Console.OpenStandardOutput() ); BinaryReader binReader = new BinaryReader( Console.OpenStandardInput() ); int delta; if ( args.Length < 1 || ! int.TryParse( args[0], out delta ) ) { Console.WriteLine( "Provide a non-negative delta on the command line" ); } else { try { while ( true ) { int bin = binReader.ReadByte(); byte bout = (byte) ( ( bin + delta ) % 256 ); binWriter.Write( bout ); } } catch(EndOfStreamException) { } catch(ObjectDisposedException) { } catch(IOException e) { Console.WriteLine( e ); } finally { binWriter.Close(); binReader.Close(); } } } } E:\Test> xxd bin 0000000: 3031 3233 3435 0d0a 0d0a 012345.... E:\Test> b 0 < bin | xxd 0000000: 3031 3233 3435 0d0a 0d0a 012345.... E:\Test> b 32 < bin | xxd 0000000: 5051 5253 5455 2d2a 2d2a PQRSTU-*-* E:\Test> b 257 < bin | xxd 0000000: 3132 3334 3536 0e0b 0e0b 123456.... ```
There's not much to tell. It reads a file one byte at a time, adjusts the value of each byte by an arbitrary value (specified via the -s flag), and writes out the adjusted bytes. It's the binary equivalent of ROT-13 encryption of a text file. The rest of the details are specific to how Perl does those things. getopts() is a function (from the Getopt::Std module) that processes command-line switches. binmode() puts the filehandles in raw mode to bypass any of the magic that Perl normally does during I/O. The sysread() and syswrite() functions are used for low-level stream access. The pack() and unpack() functions are used to read and write binary data; Perl doesn't do native types. This would be trivial to re-implement in C. I'd recommend doing that (and binding to it from C# if need be) rather than porting to C# directly.
Help with byte shifting
[ "", "c#", "perl", "byte-shifting", "" ]
If I have class B : A {} I say that "Class B *inherited* class A" or "class B derives from class A". However, if I instead have: ``` class B : ISomeInterface {} ``` it's wrong to say "B inherits ISomeInterface" -- the proper term is to say "B *implements* ISomeInterface". But, say I have ``` interface ISomeInterface : ISomeOtherInterface {} ``` Now, it's still wrong to say "inherits", but it's now just as wrong to say "implements" since ISomeInterface doesn't implement anything. So, what do you call that relationship?
I personally say "extends" and I *thought* the C# spec uses that word as well somewhere (I can't find it now, unfortunately) - but I remember Eric Lippert saying he wasn't keen on it, and wanted to change it for 4.0. I think it's good, because it shows that you're extending the contract specified by the original interface. EDIT: Having looked at the 3.0 spec... The spec sort of side-steps the issue in section 13.2. It talks about the members being inherited from the base interfaces. It talks about one *class* extending another, but not interfaces EDIT: In the C# 5 spec, section 13.1.4, it uses inherits: > An interface can inherit from zero or more interface types So that's probably the best term to use.
I call it "extends".
What do you call it when one interface "inherits" from another?
[ "", "c#", "oop", "interface", "" ]
I am implementing a thread pooling mechanism in which I'd like to execute tasks of varying priorities. I'd like to have a nice mechanism whereby I can submit a high priority task to the service and have it be scheduled before other tasks. The priority of the task is an intrinsic property of the task itself (whether I express that task as a `Callable` or a `Runnable` is not important to me). Now, superficially it looks like I could use a `PriorityBlockingQueue` as the task queue in my `ThreadPoolExecutor`, but that queue contains `Runnable` objects, which may or may not be the `Runnable` tasks I've submitted to it. Moreover, if I've submitted `Callable` tasks, it's not clear how this would ever map. Is there a way to do this? I'd really rather not roll my own for this, since I'm far more likely to get it wrong that way. (An aside; yes, I'm aware of the possibility of starvation for lower-priority jobs in something like this. Extra points (?!) for solutions that have a reasonable guarantee of fairness)
At first blush it would seem you could define an interface for your tasks that extends `Runnable` or `Callable<T>` and `Comparable`. Then wrap a `ThreadPoolExecutor` with a `PriorityBlockingQueue` as the queue, and only accept tasks that implement your interface. Taking your comment into account, it looks like one option is to extend `ThreadPoolExecutor`, and override the `submit()` methods. Refer to `AbstractExecutorService` to see what the default ones look like; all they do is wrap the `Runnable` or `Callable` in a `FutureTask` and `execute()` it. I'd probably do this by writing a wrapper class that implements `ExecutorService` and delegates to an anonymous inner `ThreadPoolExecutor`. Wrap them in something that has your priority, so that your `Comparator` can get at it.
I have solved this problem in a reasonable fashion, and I'll describe it below for future reference to myself and anyone else who runs into this problem with the Java Concurrent libraries. Using a `PriorityBlockingQueue` as the means for holding onto tasks for later execution is indeed a movement in the correct direction. The problem is that the `PriorityBlockingQueue` must be generically instantiated to contain `Runnable` instances, and it is impossible to call `compareTo` (or similiar) on a `Runnable` interface. Onto solving the problem. When creating the Executor, it must be given a `PriorityBlockingQueue`. The queue should further be given a custom Comparator to do proper in place sorting: ``` new PriorityBlockingQueue<Runnable>(size, new CustomTaskComparator()); ``` Now, a peek at `CustomTaskComparator`: ``` public class CustomTaskComparator implements Comparator<MyType> { @Override public int compare(MyType first, MyType second) { return comparison; } } ``` Everything looking pretty straight forward up to this point. It gets a bit sticky here. Our next problem is to deal with the creation of FutureTasks from the Executor. In the Executor, we must override `newTaskFor` as so: ``` @Override protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) { //Override the default FutureTask creation and retrofit it with //a custom task. This is done so that prioritization can be accomplished. return new CustomFutureTask(c); } ``` Where `c` is the `Callable` task that we're trying to execute. Now, let's have a peek at `CustomFutureTask`: ``` public class CustomFutureTask extends FutureTask { private CustomTask task; public CustomFutureTask(Callable callable) { super(callable); this.task = (CustomTask) callable; } public CustomTask getTask() { return task; } } ``` Notice the `getTask` method. We're gonna use that later to grab the original task out of this `CustomFutureTask` that we've created. And finally, let's modify the original task that we were trying to execute: ``` public class CustomTask implements Callable<MyType>, Comparable<CustomTask> { private final MyType myType; public CustomTask(MyType myType) { this.myType = myType; } @Override public MyType call() { //Do some things, return something for FutureTask implementation of `call`. return myType; } @Override public int compareTo(MyType task2) { return new CustomTaskComparator().compare(this.myType, task2.myType); } } ``` You can see that we implement `Comparable` in the task to delegate to the actual `Comparator` for `MyType`. And there you have it, customized prioritization for an Executor using the Java libraries! It takes some bit of bending, but it's the cleanest that I've been able to come up with. I hope this is helpful to someone!
How do I implement task prioritization using an ExecutorService in Java 5?
[ "", "java", "multithreading", "concurrency", "" ]
We are developing a rather large project in C++, where many components require configuration parameters. We would like to use a central place to configure everything (like a registry), preferably with a nice and simple GUI (e.g. like Firefox's `about:config`) and a simple API. I am pretty sure this that many applications have this kind of problem, but could not find any libraries available that can be readily used for this. Does anyone know of a good (preferably free) library to use for this? This should work cross platform in Windows and Linux.
[boost::program\_options](http://www.boost.org/doc/libs/1_38_0/doc/html/program_options.html) provides unified (and cross platform) support for configuration from command line, environment variables and [configuration files](http://www.boost.org/doc/libs/1_38_0/doc/html/program_options/overview.html#id3763008). It seems like it ought to scale to multiple bits of a large software system registering an interest in various parameters (e.g [option groups](http://www.boost.org/doc/libs/1_38_0/doc/html/program_options/howto.html#id3763728)). Not much help with the GUI or persistence side of things though (but then what's wrong with editing a config file with a text editor ?).
I've used libconfig before, works well easy and LGPL. <http://www.hyperrealm.com/libconfig/>
Good, simple configuration library for large c++ project?
[ "", "c++", "user-interface", "configuration", "" ]
I happened to be making some changes to a WordPress blog and noticed that they use `parse_str` (<http://php.net/parse_str>) for parsing and setting their optional parameters to a function. I'm wondering if there is an advantage to this over sending an array? Examples: With array: ``` $blahOptions = array( 'option_1' => true, ); BlahArray($blahOptions); function BlahArray($options = array()) { $defaults = array( 'option_1' => false, 'option_2' => 'blah', ); // this would probably be in a function to be used everywhere foreach ($defaults as $defaultOption => $defaultValue) { if (!isset($options[$defaultOption])) $options[$defaultOption] = $defaultValue; } } ``` With `parse_str`: ``` $blahOptions = 'option_1=1'; BlahString($blahOptions); function BlahString($options = '') { $defaults = array( 'option_1' => false, 'option_2' => 'blah', ); parse_str($options, $defaults); $options = $defaults; } ```
No. That seems like a ridiculous way to pass functional parameter arguments. I could understand it if you needed to recreate $\_GET or $\_POST variables or something along those lines, but for parameters to a function? That's code smell right there. They should be using an array, and then utilizing [extract()](http://www.php.net/extract) instead. I've worked with Wordpress before, and my advice is to keep the code at arm's length. It is not an example of model programming.
No. There are more disadvantages than advantages. When you’re using a single string, you just can pass string values. With an array you can use every PHP data type and every element’s value type is independently of each other.
Is there an advantage to using parse_str for optional function parameters vs an array?
[ "", "php", "optional-parameters", "function-parameter", "" ]
First, the background: I'm working in Tapestry 4, so the HTML for any given page is stitched together from various bits and pieces of HTML scattered throughout the application. For the component I'm working on I don't have the `<body>` tag so I can't give it an `onload` attribute. The component has an input element that needs focus when the page loads. Does anyone know a way to set the focus to a file input (or any other text-type input) on page load without access to the body tag? I've tried inserting script into the body like `document.body.setAttribute('onload', 'setFocus()')` (where setFocus is a function setting the focus to the file input element), but that didn't work. I can't say I was surprised by that though. **EDIT:** As has been stated, I do indeed need to do this with a page component. I ended up adding file-type inputs to the script we use for giving focus to the first editable and visible input on a page. In researching this problem I haven't found any security issues with doing this.
This has worked well for me: ``` <script> function getLastFormElem(){ var fID = document.forms.length -1; var f = document.forms[fID]; var eID = f.elements.length -1; return f.elements[eID]; } </script> <input name="whatever" id="maybesetmaybenot" type="text"/> <!-- any other code except more form tags --> <script>getLastFormElem().focus();</script> ```
``` <script> window.onload = function() { document.getElementById('search_query').select(); //document.getElementById('search_query').value = ''; // where 'search_query' will be the id of the input element }; </script> ``` must be useful i think !!!
How can you set focus to an HTML input element without having all of the HTML?
[ "", "javascript", "html", "dom", "tapestry", "" ]
i'm new with python.. Actually, i'm trying to send featured email with python: html body, text alternative body, and attachment. So, i've found this [tutorial](http://code.activestate.com/recipes/67083/ "tutorial 1") and adapted it with the gmail authentication (tutorial found [here](http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html "tutorial 2")) The code i have atm, is that: ``` def createhtmlmail (html, text, subject): """Create a mime-message that will render HTML in popular MUAs, text in better ones""" import MimeWriter import mimetools import cStringIO from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os out = cStringIO.StringIO() # output buffer for our message htmlin = cStringIO.StringIO(html) txtin = cStringIO.StringIO(text) writer = MimeWriter.MimeWriter(out) # # set up some basic headers... we put subject here # because smtplib.sendmail expects it to be in the # message body # writer.addheader("Subject", subject) writer.addheader("MIME-Version", "1.0") # # start the multipart section of the message # multipart/alternative seems to work better # on some MUAs than multipart/mixed # writer.startmultipartbody("alternative") writer.flushheaders() # # the plain text section # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) mimetools.encode(txtin, pout, 'quoted-printable') txtin.close() # # start the html subpart of the message # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") # # returns us a file-ish object we can write to # pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) mimetools.encode(htmlin, pout, 'quoted-printable') htmlin.close() # # Now that we're done, close our writer and # return the message body # writer.lastpart() msg = out.getvalue() out.close() return msg import smtplib f = open("/path/to/html/version.html", 'r') html = f.read() f.close() f = open("/path/to/txt/version.txt", 'r') text = f.read() subject = "Prova email html da python, con allegato!" message = createhtmlmail(html, text, subject) gmail_user = "thegmailaccount@gmail.com" gmail_pwd = "thegmailpassword" server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(gmail_user, gmail_pwd) server.sendmail(gmail_user, "example@example.com", message) server.close() ``` and that works.. now only miss the attachment.. And i am not able to add the attachment (from [this](http://snippets.dzone.com/posts/show/757 "attachments") post) So, why there is not a python class like phpMailer for php? Is it because, for a medium-able python programmer sending a html email with attachment and alt text body is so easy that a class is not needed? Or is because i just didn't find it? If i'll be able to wrote a class like that, when i'll be enough good with python, would that be useful for someone?
If you can excuse some blatant self promotion, I wrote a [mailer module](http://pypi.python.org/pypi/mailer/0.3) that makes sending email with Python fairly simple. No dependencies other than the Python smtplib and email libraries. Here's a simple example for sending an email with an attachment: ``` from mailer import Mailer from mailer import Message message = Message(From="me@example.com", To=["you@example.com", "him@example.com"]) message.Subject = "Kitty with dynamite" message.Body = """Kitty go boom!""" message.attach("kitty.jpg") sender = Mailer('smtp.example.com') sender.login("username", "password") sender.send(message) ``` **Edit**: Here's an example of sending an HTML email with alternate text. :) ``` from mailer import Mailer from mailer import Message message = Message(From="me@example.com", To="you@example.com", charset="utf-8") message.Subject = "An HTML Email" message.Html = """This email uses <strong>HTML</strong>!""" message.Body = """This is alternate text.""" sender = Mailer('smtp.example.com') sender.send(message) ``` **Edit 2**: Thanks to one of the comments, I've added a new version of mailer to pypi that lets you specify the port in the Mailer class.
Django includes the class you need in core, [docs here](http://docs.djangoproject.com/en/dev/topics/email/#sending-alternative-content-types) ``` from django.core.mail import EmailMultiAlternatives subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.attach_file('/path/to/file.jpg') msg.send() ``` In my settings I have: ``` #GMAIL STUFF EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'name@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 ```
Where is the phpMailer php class equivalent for Python?
[ "", "python", "email", "phpmailer", "" ]
Anyone out there using YAML as a data DSL in .NET? I'd like to use YAML because it's more lightweight than XML. I intend to use this DSL as a "power user" configuration tool for one of my existing applications. My concerns: * How is the support for YAML using one of the .NET community libraries? * Does YAML have staying power? Will it still be around 4 years from now? Or will we be talking about some other format? I know JSON and XML are going to be around for a while, but my users aren't going to want to write or maintain JSON or XML documents.
If it's a user-facing document, don't worry about the 'staying power' of YAML. Worry about making the users happy with some DSL. That being said, I would choose YAML over XML. Outside of the user-facing portion, I wouldn't use YAML for much. XML has so much more going for it \*that I can imagine\*, that it would be in your best interest to use something richer and more widely used (esp. by .NET). Even if you had to create your own language to satisfy your users, it would probably be worth it to not force them to look at XML.
Have you considered instead using IronPython scripts? That way, you can not only interpret simple key-value type things, you can also add dynamic execution and calculation to your power-user configuration. It's worth checking out, as hosting IronPython is *dead simple*, and the syntax is very clean and easy-to-read for users, even if they don't know Python.
YAML as a Data DSL in .NET (C#)
[ "", "c#", ".net", "serialization", "dsl", "yaml", "" ]
In Java5, is there a way to get the full name of the user that is running the application using only JDK APIs? (I know about JAAS and third-party libraries, but they might not be installed on the target system). I know about System.getProperty("user.name") but that returns the user *ID* not user *NAME*.
The concept of a user's "full" name is OS dependent so there is not a way to get it using standard Java APIs.
``` import java.util.Scanner; ... System.out.println("Please enter your full name: "); Scanner sc = new Scanner(System.in); String name = sc.nextLine(); ``` ;)
In Java5, how do I get the full name of the user running the application?
[ "", "java", "operating-system", "jaas", "" ]
I am trying to achieve reading variables from a Java applet out of process from my C# program. Apart from reading memory addresses, is there any way I can obtain values of variables from a java applet? This java applet will be running inside a browser. If it is not possible to do this from C#, would it be possible to do it from a different java applet? Thanks.
If you can change the code of the applet, you can have it host an RMI server, which is the subject of [this excercise](http://java.sun.com/developer/onlineTraining/rmi/exercises/RMICallback/index.html). I'm not an expert of the subject though - I assume it may be subject to various security restrictions. If you *can't* change the applet, but you *can* change the HTML page showing the applet, there are two ways to access information from the applet. The first way is scripting the applet with Javascript like @Margus suggests (all public methods of the applet object are exposed via the applet's DOM object). The other way is putting an applet of your own in the page, and use [`getAppletContext()`](http://java.sun.com/javase/6/docs/api/java/applet/Applet.html#getAppletContext()) to obtain a reference to the other applet. The main benefit of doing it this way is that you can access non-public information from the third-party applet via reflection, and publish it with an RMI server (as above).
Yes, it can be done. C# form can have can host webbrowser component, and it can fire JScript, and it can call Java applet public methods. While ago, i made a simple webpage, that hosts an applet that draws 'hot'-colored map. Input is injected with JScript, and COULD be retrieved with AJAX or any other application that can fire JScript on HTML DOM. Source of HTML is: ``` <HTML><HEAD></HEAD><BODY> <SCRIPT> function call() { var inputData = "-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2" + ";-2,-2,-2,-2,-2,-2,-2,-2,-2,0,1647,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2" + ";-2,-2,-2,-2,-2,-2,-2,-2,-2,89,0,-1,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2" + ";-2,-2,-2,-2,-2,-2,-2,0,0,615,366,0,1198,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2" + ";-2,-2,-2,-2,-2,-2,0,2179,1262,764,200,0,0,609,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2" + ";-2,-2,-2,-2,-2,0,0,3401,1940,0,210,0,-1,-1,162,0,0,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2" + ";-2,-2,-2,-2,-2,-2,0,-1,966,0,86,0,0,0,0,-1,-1,0,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2" + ";-2,-2,-2,-2,-2,-2,-2,0,0,0,0,0,0,0,-1,250,53,-1,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2" + ";-2,-2,-2,-2,-1,1977,1413,128,0,0,0,0,0,0,-1,1413,2447,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2" + ";-2,-2,-2,0,-1,0,0,0,0,0,0,0,-1,317,0,-1,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2" + ";-2,-2,-2,0,0,0,0,0,0,0,0,0,0,3246,2190,0,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2" + ";-2,51,0,-1,0,0,0,-1,0,-1,0,-1,-1,1523,-2,-2,-2,-1,0,0,-2,-2,0,0,-2,-2,-2,-2,-2" + ";-2,0,0,0,0,0,0,0,0,0,0,1692,2028,2850,-2,0,-1,0,0,0,0,0,0,0,-1,-2,-2,-2,-2" + ";-2,0,0,0,0,0,-1,0,0,0,-1,1292,-2,-2,-2,0,0,-1,-1,0,0,0,0,0,-1,0,-2,-2,-2" + ";-2,0,-1,0,0,-1,0,0,-1,0,1028,1247,7675,9244,7940,0,-1,0,0,-1,0,0,0,0,0,0,0,-2,-2" + ";-2,-1,0,0,0,0,0,0,0,0,844,1114,2860,6631,4249,0,0,-1,-1,0,0,0,0,0,0,0,0,-2,-2" + ";-2,-2,0,0,0,-1,0,-1,0,0,0,-1,1958,2379,-1,0,0,0,0,0,0,0,0,-1,0,0,0,-2,-2" + ";-2,-2,-2,0,470,0,-2,-2,-2,0,0,0,-1,0,0,0,0,0,-1,0,-1,0,0,3574,2706,2195,-1,-2,-2" + ";-2,-2,-2,-2,-2,-2,-2,-2,-2,0,0,0,-1,-1,0,0,0,0,0,0,0,0,165,-1,-1,1282,867,0,-2" + ";-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,0,0,0,0,0,0,-1,0,0,0,0,34,504,3098,2708,2324,-1,0,-2" + ";-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,0,0,-1,0,0,0,0,0,0,0,0,0,721,-1,3854,2783,-1,0,-2" + ";-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,0,0,0,0,0,-1,0,0,0,-1,0,34,191,2455,4126,0,0,-2" + ";-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,0,0,0,0,0,0,0,0,3982,2656,0,0,-1,0,0,-2,-2" + ";-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,0,-1,0,0,2194,0,0,0,0,-2,-2,-2,-2" + ";-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,0,0,-1,0,0,-2,-2,-2,-2,-2,-2,-2" + ";-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2"; document.Necrodrip.update(inputData); } </SCRIPT> <FORM> <APPLET CODE="kuningriik.pdApplet.class" NAME="Necrodrip" width="1200" height="600"> </APPLET><br/> <INPUT type="button" value="Loo kaart" onClick = "call()"> </FORM> </BODY></HTML> ``` You can view page here: [link](http://www.hot.ee/ocjel/K/aaa.html)
Read Java Variables
[ "", "java", "memory", "applet", "" ]
Say I make a program that keeps track of the days I worked and the hours I worked, would I use a dictionary? And how would I differentiate from a Monday on week 1 from a Monday on week 2? How do I get it to store this information after I close the program? (Python Language)
A dictionary is a good way to store the data while your program is running. There are a number of ways to add some data permanence (so it's around after you close the program). The Python modules pickle and [shelve](http://docs.python.org/library/shelve.html) are useful and easy to use. One issue with these is that you can't easily inspect the data outside of a Python program. There are also modules to read and write text files in the [JSON](http://docs.python.org/library/json.html) and XML formats, and JSON is particularly easy to read in a text editor. If you aren't already proficient, the databases like MySQL are way more than you need for a personal program like you mention and unless you want to invest some time into learning how to use them, you should go with a simpler solution. As for the Monday on week 1 vs week 2, you have many options. You could use the actual date (this seems like a good idea to me), or you could key the dictionary with tuples, like ("Monday", 1). The main rule is that dictionary keys must be immutable (ints, strings, tuples -- that contain only immutable objects, etc), but not (dictionaries, lists, etc).
I would probably create a timesheet object for each week, or pay period. Each timesheet object might have a collection of days, with hours worked or times clocked in and out. For persistent storage for a web site, I'd use a database like mysql. For an application running on a single machine I'd maybe use pickle, or a flat file system maybe.
Timesheet Program to Track Days/Hours worked?
[ "", "python", "" ]
What are the access-specifiers available in c#? What is the default one?
The possible access modifiers are : * private * protected * internal * protected internal * public The default modifier that is used, depends on the element. * For classes, the default specifier is 'internal' * For class-members, the default specifier is private * For nested types (inner classes), the default is private You can also find it on [MSDN](http://msdn.microsoft.com/en-us/library/wxh6fsc7(VS.71).aspx) You might find it also interesting to have a look at [this](http://msdn.microsoft.com/en-us/library/ba0a1yw2(VS.71).aspx)
A copy of the C# Language Specification is included when you install Visual Studio (in 2008 at least), at `VSRoot\VC#\Specifications\1033\CSharp Language Specification.doc`. This is, of course, the definitive place to look.
What are the access-specifiers available in c#? What is the default one?
[ "", "c#", "" ]
This is the code I use to setup my TCP server ``` internal void Initialize(int port,string IP) { IPEndPoint _Point = new IPEndPoint(IPAddress.Parse(IP), port); Socket _Accpt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { _Accpt.Bind(_Point); } catch (SocketException exc) { System.Windows.Forms.MessageBox.Show(exc.Message); } finally { _Accpt.Listen(2); //Second exception is here after the code continues after the catch block _Accpt.BeginAccept(null, 0, new AsyncCallback(Accept), _Accpt); } } ``` If you call Bind on the same destination you'll get an exception,because the port is already in use,so do I get that exception when I call that function two times. Problem - After Catch{} statement the code continues to follow the Finally{} even though I caught the exception,why that happens? I want it to exit the function after the messagebox.I tried with "return",but it still continues to follow the finally{} block.
The finally block always executes, regardless if an exception was thrown or the method was exiting from within the try/catch block.
The Finally block is where you put code that MUST run regardless of whether the try block succeeds or fails. It's where you'd put "clean up" code that might dispose objects etc. So, it's by-design that this code runs regardless of what happened. Perhaps you need to move that code into the Try block if you only want it running when the Bind is good. Check out this page... <http://msdn.microsoft.com/en-us/library/6dekhbbc(VS.80).aspx> ... for details on how this works. A sample try/catch/finally follows (taken from Jeffery Richter's CLR via C# which should be on your required reading)... ``` FileStream fs = null; try { fs = new FileStream(...) // process the data } catch (IOException) { // inside this catch block is where you put code that recovers // from an IOException } finally { // make sure the file gets closed if (fs != null) fs.Close(); } ```
problem in try statement
[ "", "c#", "exception", "try-catch", "finally", "" ]
In Python, I'm getting the following error: ``` UnboundLocalError: local variable 'total' referenced before assignment ``` At the start of the file (before the function where the error comes from), I declare `total` using the `global` keyword. Then, in the body of the program, before the function that uses `total` is called, I assign it to 0. I've tried setting it to 0 in various places (including the top of the file, just after it is declared), but I can't get it to work. Does anyone see what I'm doing wrong?
I think you are using 'global' incorrectly. See [Python reference](http://docs.python.org/reference/simple_stmts.html#the-global-statement). You should declare variable without global and then inside the function when you want to access global variable you declare it `global yourvar`. ``` #!/usr/bin/python total def checkTotal(): global total total = 0 ``` See this example: ``` #!/usr/bin/env python total = 0 def doA(): # not accessing global total total = 10 def doB(): global total total = total + 1 def checkTotal(): # global total - not required as global is required # only for assignment - thanks for comment Greg print total def main(): doA() doB() checkTotal() if __name__ == '__main__': main() ``` Because `doA()` does not modify the *global total* the output is 1 not 11.
My Scenario ``` def example(): cl = [0, 1] def inner(): #cl = [1, 2] # access this way will throw `reference before assignment` cl[0] = 1 cl[1] = 2 # these won't inner() ```
Why do I get a "referenced before assignment" error when assigning to a global variable in a function?
[ "", "python", "global-variables", "" ]
We have an application that can create e-books. This application has an export module that creates an AIR file but this can take a while (some books have 2500 pages). If we export we get the following error: ``` Thread was being aborted. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Threading.ThreadAbortException: Thread was being aborted. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [ThreadAbortException: Thread was being aborted.] System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +501 System.Web.ApplicationStepManager.ResumeSteps(Exception error) +564 System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +141 System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +436 ``` I've changed my runtime executiontimeout to 3600 secs but it keeps crashing arround 3 minutes. so it is time related ... everytime we approach the 3 minutes it crashes, I hope someone can help me out.
I think Paul is right about the cause of the exception. Both IIS and ASP.NET have settings that limit the maximum amount of time a request can take. For ASP.NET it's in the Machine.Config file (look for the httpRuntime element, executionTimeout attribute). It's set to 90 seconds on my development machine. I would however not advise you to change that setting as it's there to make sure your application doesn't hang on a bad request. Long running tasks should use asynchronous execution. With async execution, the actual work is handled on a separate thread. This frees the thread that handles the request to handle other requests which is good for the overall performance of your application. There are some good articles on this available. For example : <http://msdn.microsoft.com/en-us/magazine/cc163725.aspx>
Quite often, this error actually occurs from an OutOfMemory exception. Is there an InnerException available?
Thread being aborded error
[ "", "c#", "asp.net", "multithreading", "abort", "" ]
I'm trying to create an accordion widget in jquery similar to [jquery's accordion plugin](http://jqueryui.com/demos/accordion/), with the difference that I want the handles to appear below their respective content instead of above. My accordion works by decreasing the height of the open content section while at the same time increasing the height of the clicked content section. I've posted an example [here](http://cobradragon.com/~adam/accordion/). My problem is that the animations aren't started at exactly the same time, and there is a noticeable "jump" due to the slight delay before the second animation is started. Scriptaculous has a function called [Effect.Parallel](http://wiki.github.com/madrobby/scriptaculous/effect-parallel) that allows you to create an array of animation effects and execute them in parallel. Unfortunately, I can't seem to find something similar with jquery. Is there a way I can run precise parallel animations on separate divs in jquery? Edit: I'm as much interested in alternative methods of coding this accordion widget. So if there is any other method people think would work I'm open to that.
One more answer, hopefully my last one... Unfortunately, John Resig's syncAnimate method is not quite up to snuff for the accordion-type animation I want to do. While it works great on Firefox, I couldn't get it working smoothly on IE or Safari. With that said, I decided to bite the bullet and write my own animation engine that does simple parallel animations. The class-code uses jquery functions but is not a jquery plugin. Also, I've only set it up to do size/position animations, which is all I need. ``` ParallelAnimations = function(animations, opts){ this.init(animations, opts); }; $.extend(ParallelAnimations.prototype, { options: { duration: 250 }, rules: {}, init: function(animations, opts){ // Overwrite the default options $.extend(this.options, opts); // Create a set of rules to follow in our animation for(var i in animations){ this.rules[i] = { element: animations[i].element, changes: new Array() }; for(var style in animations[i].styles){ // Calculate the start and end point values for the given style change var from = this.parse_style_value(animations[i].element, style, ""); var to = this.parse_style_value(animations[i].element, style, animations[i].styles[style]); this.rules[i].changes.push({ from: from, to: to, style: style }); } } this.start() }, /* * Does some parsing of the given and real style values * Allows for pixel and percentage-based animations */ parse_style_value: function(element, style, given_value){ var real_value = element.css(style); if(given_value.indexOf("px") != -1){ return { amount: given_value.substring(0, (given_value.length - 2)), unit: "px" }; } if(real_value == "auto"){ return { amount: 0, unit: "px" }; } if(given_value.indexOf("%") != -1){ var fraction = given_value.substring(0, given_value.length - 1) / 100; return { amount: (real_value.substring(0, real_value.length - 2) * fraction), unit: "px" }; } if(!given_value){ return { amount: real_value.substring(0, real_value.length - 2), unit: "px" }; } }, /* * Start the animation */ start: function(){ var self = this; var start_time = new Date().getTime(); var freq = (1 / this.options.duration); var interval = setInterval(function(){ var elapsed_time = new Date().getTime() - start_time; if(elapsed_time < self.options.duration){ var f = elapsed_time * freq; for(var i in self.rules){ for(var j in self.rules[i].changes){ self.step(self.rules[i].element, self.rules[i].changes[j], f); } } } else{ clearInterval(interval); for(var i in self.rules){ for(var j in self.rules[i].changes) self.step(self.rules[i].element, self.rules[i].changes[j], 1); } } }, 10); }, /* * Perform an animation step * Only works with position-based animations */ step: function(element, change, fraction){ var new_value; switch(change.style){ case 'height': case 'width': case 'top': case 'bottom': case 'left': case 'right': case 'marginTop': case 'marginBottom': case 'marginLeft': case 'marginRight': new_value = Math.round(change.from.amount - (fraction * (change.from.amount - change.to.amount))) + change.to.unit; break; } if(new_value) element.css(change.style, new_value); } }); ``` Then the original Accordion class only needs to be modified in the animate method to make use of the new call. ``` Accordion = function(container_id, options){ this.init(container_id, options); } $.extend(Accordion.prototype, { container_id: '', options: {}, active_tab: 0, animating: false, button_position: 'below', duration: 250, height: 100, handle_class: ".handle", section_class: ".section", init: function(container_id, options){ var self = this; this.container_id = container_id; this.button_position = this.get_button_position(); // The height of each section, use the height specified in the stylesheet if possible this.height = $(this.container_id + " " + this.section_class).css("height"); if(options && options.duration) this.duration = options.duration; if(options && options.active_tab) this.active_tab = options.active_tab; // Set the first section to have a height and be "open" // All the rest of the sections should have 0px height $(this.container_id).children(this.section_class).eq(this.active_tab) .addClass("open") .css("height", this.height) .siblings(this.section_class) .css("height", "0px"); // figure out the state of the handles this.do_handle_logic($(this.container_id).children(this.handle_class).eq(this.active_tab)); // Set up an event handler to animate each section $(this.container_id + " " + this.handle_class).mouseover(function(){ if(self.animating) return; self.animate($(this)); }); }, /* * Determines whether handles are above or below their associated section */ get_button_position: function(){ return ($(this.container_id).children(":first").hasClass(this.handle_class) ? 'above' : 'below'); }, /* * Animate the accordion from one node to another */ animate: function(handle){ var active_section = (this.button_position == 'below' ? handle.prev() : handle.next()); var open_section = handle.siblings().andSelf().filter(".open"); if(active_section.hasClass("open")) return; this.animating = true; // figure out the state of the handles this.do_handle_logic(handle); // Close the open section var arr = new Array(); arr.push({ element: open_section, styles: { "height": "0px" } }); arr.push({ element: active_section, styles: { "height": this.height } }); new ParallelAnimations(arr, {duration: this.duration}); var self = this; window.setTimeout(function(){ open_section.removeClass("open"); active_section.addClass("open"); self.animating = false; }, this.duration); }, /* * Update the current class or "state" of each handle */ do_handle_logic: function(handle){ var all_handles = handle.siblings(".handle").andSelf(); var above_handles = handle.prevAll(this.handle_class); var below_handles = handle.nextAll(this.handle_class); // Remove all obsolete handles all_handles .removeClass("handle_on_above") .removeClass("handle_on_below") .removeClass("handle_off_below") .removeClass("handle_off_above"); // Apply the "on" state to the current handle if(this.button_position == 'below'){ handle .addClass("handle_on_below"); } else{ handle .addClass("handle_on_above"); } // Apply the off above/below state to the rest of the handles above_handles .addClass("handle_off_above"); below_handles .addClass("handle_off_below"); } }); ``` The HTML is still called the same way: ``` <html> <head> <title>Parallel Accordion Animation</title> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="ui.js"></script> <script type="text/javascript"> $(document).ready(function(){ new Accordion("#accordion"); }); </script> <style type="text/css"> #accordion{ position: relative; } #accordion .handle{ width: 260px; height: 30px; background-color: orange; } #accordion .section{ width: 260px; height: 445px; background-color: #a9a9a9; overflow: hidden; position: relative; } </style> </head> <body> <div id="accordion"> <div class="section"><!-- --></div> <div class="handle">handle 1</div> <div class="section"><!-- --></div> <div class="handle">handle 2</div> <div class="section"><!-- --></div> <div class="handle">handle 3</div> <div class="section"><!-- --></div> <div class="handle">handle 4</div> <div class="section"><!-- --></div> <div class="handle">handle 5</div> </div> </body> </html> ``` There are a few things I may add in the future: - Queued Animations - Animations for other types of styles (colors,etc)
John Resig posted a [synchronized animation sample](http://ejohn.org/files/sync/) (no instructions, click a colored box). It might take some work to figure out how to apply it to your control, but it could be a good place to start.
How can I get jquery to execute animations in exact parallel?
[ "", "javascript", "jquery", "jquery-ui", "" ]
I would like to get the last modified date of a remote file by means of curl. Does anyone know how to do that?
From [php's article](http://ar.php.net/filemtime): ``` <?php // outputs e.g. somefile.txt was last modified: December 29 2002 22:16:23. $filename = 'somefile.txt'; if (file_exists($filename)) { echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename)); } ?> ``` filemtime() is the key here. But I'm not sure if you can get the last modified date of a **remote** file, since the server should send it to you... Maybe in the HTTP headers?
You could probably do something like this using [`curl_getinfo()`](http://php.net/manual/en/function.curl-getinfo.php): ``` <?php $curl = curl_init('http://www.example.com/filename.txt'); //don't fetch the actual page, you only want headers curl_setopt($curl, CURLOPT_NOBODY, true); //stop it from outputting stuff to stdout curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // attempt to retrieve the modification date curl_setopt($curl, CURLOPT_FILETIME, true); $result = curl_exec($curl); if ($result === false) { die (curl_error($curl)); } $timestamp = curl_getinfo($curl, CURLINFO_FILETIME); if ($timestamp != -1) { //otherwise unknown echo date("Y-m-d H:i:s", $timestamp); //etc } ```
Get the last modified date of a remote file
[ "", "php", "jquery", "curl", "" ]
Primarily I've done basic (novice level) software development on a Windows machine, but I've always had MS Visual Studio to help me step through the process of debugging. Now, however, it looks like I will be on Linux, so in order to get ready for the jump I want to make sure I have a tool/tools lined up to help me step through the code and debug. Unfortunately when I've verbally asked folks how they go about debugging on Linux, I typically get the following answer, "Oh, I just put a bunch of print statements." OMG! No way you say, but yes that is their answer. Since it is on Linux, and will be working with C++ code on the CentOS 32-bit OS, I am hoping here is a preferred OpenSource solution. So, I guess I asking for the preferred OpenSource IDE for C++ code on CentOS Linux. Thanks for any insight and suggestions.
I would suggest using [Eclipse](http://www.eclipse.org/cdt/) Eclipse is a mature IDE with plenty of support available. There is also [Code::Blocks](http://www.codeblocks.org/) if you want to try something different
> Good question, of course, but its been > done before: > > * <https://stackoverflow.com/questions/408418/what-editor-ide-do-you-use-for-c-programming-on-linux-and-why-closed> > * <https://stackoverflow.com/questions/86676/is-there-a-good-and-free-ide-for-c-c-in-linux> > * <https://stackoverflow.com/questions/149321/what-ide-would-be-good-for-linux-kernel-driver-development> > * [Lightweight IDE for Linux](https://stackoverflow.com/questions/2756/lightweight-ide-for-linux) > * [Simple GUI IDE?](https://stackoverflow.com/questions/524404/simple-gui-ide) (from: <https://stackoverflow.com/questions/579219/best-unix-linux-c-debuger-ide-closed>)
Debugging on Linux for Windows Developer
[ "", "c++", "linux", "debugging", "" ]
I've got a class somewhat like this: ``` public class Test { private final List<ISomeType> things = new LinkedList<ISomeType>(); public <T extends ISomeType> Test(Class<T> clazz, int order) { for (int i = 0; i < order; i++) { try { this.things.add(clazz.newInstance()); } catch (Exception e) { // stackoverflowers use your imagination } } } } ``` Where I expect and hope the Class clazz has an accessible no-argument constructor. Is there any way I can enforce presence of it at compile time?
There is no way to enforce constructor requirements at compile time. At runtime you can check class.getConstructors() and ensure there is one that has no args (or just catch the exception like you are in the sample code). Usually the no-arg constructor requirement is just listed in the Javadoc of the base class or interface.
There are some tools for code style validation that can be extended to check for this type of requirement. For eclipse (and others), [PMD](http://pmd.sourceforge.net/howtowritearule.html) may help you. By looking at the tutorial I think you should be able to write an specific rule to check for constructors without any parameters.
Enforce presence of no-argument constructor at compile time (Java)
[ "", "java", "" ]
Compiler Error Keyword 'this' is not available in the current context ``` delegate void CallBack(int i); class A { public A(CallBack cb) { } } class B : A { public B() : base(new CallBack(this.f)){} private void f(int i) { } } ``` Why is this error ? As a solution I thought of providing a parameterless protected ctor in A() and have ``` class B : A { public B() : base() // inherit the new A() ctor { base.cb = new CallBack(this.f); //this is allowed here } //... } ```
It's because "this" hasn't been created until the base class constructor has run. In your 2nd example the base constructor has finished, and now "this" has meaning.
In the first example the B instance is not initialized yet. In the second, it is.
Constructor initializer does not allow me to use 'this'
[ "", "c#", "inheritance", "constructor", "" ]
I have a C++ app and looking for a library that would make it a HTTP Server that's able to serve static files as well as perform very simple tasks. The only constraint is that it must be Cross-platform. What are my options. Clarify: I need a web interface for my application. This application is a background program that does other tasks. I want to provide a way so you can access <http://localhost:9999/performtask> or <http://localhost:9999/viewstatus> clarification2: something like this <http://www.gnu.org/software/libmicrohttpd/>
In [a question which has since been deleted](https://stackoverflow.com/questions/175507/c-c-web-server-library), I asked: > I'm looking for a well-written, flexible library written in C or C++ (I'm writing my apps in C++) that can be used to embed an relatively simple HTTP server into my applications. Ultimately I will use this for application monitoring and control. > > There are a number of great client-side libraries (e.g. libwww, neon, curl) but I'm struggling to find a good solution for the server-side. I'm sure other folks have done this before, so I'd love to hear what folks have done and what has worked and what hasn't. I ended up choosing [Mongoose](http://code.google.com/p/mongoose/).
The [Wt library](http://www.webtoolkit.eu/wt) does exactly this. Recommended, especially if your user interface gets more complex.
Giving C++ Application a HTTP Web Server Functionality
[ "", "c++", "web-services", "http", "" ]
It seems like a no brainer to me. I've heard countless stories about people forgetting the WHERE clause in an UPDATE or DELETE and trashing an entire table. I know that careless people shouldn't be issuing queries directly and all that... and that there are legitimate cases where you want to affect all rows, but wouldn't it make sense to have an option on by default that requires such queries to be written like: ``` UPDATE MyTable SET MyColumn = 0 WHERE * ``` Or without changing the language, ``` UPDATE MyTable SET MyColumn = 0 WHERE 1 = 1 -- tacky, I know ```
Isn't it possible to set auto commit to false in your client session as a default? You have to issue a "commit" to see your changes that way, in an almost "are you sure you want to do this?" fashion. I believe that was the default for all Oracle TOAD clients at a former employer.
Because the [spec](http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt) doesn't require it, and you shouldn't be running ad hoc sql directly against production data anyway.
Why hasn't SQL Server made a WHERE clause mandatory by default?
[ "", "sql", "sql-server", "t-sql", "" ]
I'm attempting to make a very simple 2-person chatroom for my Django site. I'm learning AJAX to do this. I need parts of the web page to update without user interaction: * When User 1 sends a message, it should appear on User 2's screen * When User 1 logs off, his status should change to "offline" on User 2's screen What is the simplest way to implement this? Is it just to use JavaScript to poll the server at regular intervals? If so, what is the best practice for doing this? I found a few solutions about using setInterval or setTimeout, but wasn't sure if this was the best way. (I've read about reverse AJAX, but from what I've read this is more complex to implement. I don't need my solution to be fast or scalable; I just need it to work.)
Since you said you don't care for [Comet](http://en.wikipedia.org/wiki/Comet_(programming)), which is admittedly not very easy to get going, setInterval will do the trick. You want to be smart about it, though. You should probably start with an interval of 30 seconds. If the user starts chatting, your interval should drop down to 5. As you notice less and less action, your timer should decay down to 30 seconds again, and so on. It's not going to win any awards at a scalability convention, but it will get it done for your average mid-size website. For more on this technique, [check out this related question](https://stackoverflow.com/questions/676098/server-polling-intervals-for-a-javascript-chat-client).
Take advantage of [Orbited](http://www.orbited.org/). At first glance it's easy for your eyes to glaze over, start mumbling about being too complicated, but once you get passed it you'll understand what the "best practice" is, and why it is both fast and scalable. You'll also find yourself realizing that this is an outstanding technique, and can be used for *lots* of dynamic web page behavior.
What is the simplest way to implement "server push"-like behavior for a web page?
[ "", "javascript", "ajax", "comet", "reverse-ajax", "" ]
I've read about 10 different questions on when and how to override `GetHashCode` but there's still something I don't quite get. Most implementations of `GetHashCode` are based on the hash codes of the fields of the object, but it's been cited that the value of `GetHashCode` should never change over the lifetime of the object. How does that work if the fields that it's based on are mutable? Also what if I do want dictionary lookups etc to be based on reference equality not my overridden `Equals`? I'm primarily overriding `Equals` for the ease of unit testing my serialization code which I assume serializing and deserializing (to XML in my case) kills the reference equality so I want to make sure at least it's correct by value equality. Is this bad practice to override `Equals` in this case? Basically in most of the executing code I want reference equality and I always use `==` and I'm not overriding that. Should I just create a new method `ValueEquals` or something instead of overriding `Equals`? I used to assume that the framework always uses `==` and not `Equals` to compare things and so I thought it was safe to override `Equals` since it seemed to me like its purpose was for if you want to have a 2nd definition of equality that's different from the `==` operator. From reading several other questions though it seems that's not the case. **EDIT:** It seems my intentions were unclear, what I mean is that 99% of the time I want plain old reference equality, default behavior, no surprises. For very rare cases I want to have value equality, and I want to explicitly request value equality by using `.Equals` instead of `==`. When I do this the compiler recommends I override `GetHashCode` as well, and that's how this question came up. It seemed like there's contradicting goals for `GetHashCode` when applied to mutable objects, those being: 1. If `a.Equals(b)` then `a.GetHashCode()` should `== b.GetHashCode()`. 2. The value of `a.GetHashCode()` should never change for the lifetime of `a`. These seem naturally contradicting when a mutable object, because if the state of the object changes, we expect the value of `.Equals()` to change, which means that `GetHashCode` should change to match the change in `.Equals()`, but `GetHashCode` should not change. Why does there seem to be this contradiction? Are these recommendations not meant to apply to mutable objects? Probably assumed, but might be worth mentioning I'm referring to classes not structs. **Resolution:** I'm marking JaredPar as accepted, but mainly for the comments interaction. To sum up what I've learned from this is that the only way to achieve all goals and to avoid possible quirky behavior in edge cases is to only override `Equals` and `GetHashCode` based on immutable fields, or implement `IEquatable`. This kind of seems to diminish the usefulness of overriding `Equals` for reference types, as from what I've seen most reference types usually have no immutable fields unless they're stored in a relational database to identify them with their primary keys.
## How does that work if the fields that it's based on are mutable? It doesn't in the sense that the hash code will change as the object changes. That is a problem for all of the reasons listed in the articles you read. Unfortunately this is the type of problem that typically only show up in corner cases. So developers tend to get away with the bad behavior. ## Also what if I do want dictionary lookups etc to be based on reference equality not my overridden Equals? As long as you implement an interface like `IEquatable<T>` this shouldn't be a problem. Most dictionary implementations will choose an equality comparer in a way that will use `IEquatable<T>` over Object.ReferenceEquals. Even without `IEquatable<T>`, most will default to calling Object.Equals() which will then go into your implementation. ## Basically in most of the executing code I want reference equality and I always use == and I'm not overriding that. If you expect your objects to behave with value equality you should override == and != to enforce value equality for all comparisons. Users can still use Object.ReferenceEquals if they actually want reference equality. ## I used to assume that the framework always uses == and not Equals to compare things What the BCL uses has changed a bit over time. Now most cases which use equality will take an `IEqualityComparer<T>` instance and use it for equality. In the cases where one is not specified they will use `EqualityComparer<T>.Default` to find one. At worst case this will default to calling Object.Equals
If you have a mutable object, there isn't much point in overriding the GetHashCode method, as you can't really use it. It's used for example by the `Dictionary` and `HashSet` collections to place each item in a bucket. If you change the object while it's used as a key in the collection, the hash code no longer matches the bucket that the object is in, so the collection doesn't work properly and you may never find the object again. If you want the lookup not to use the `GetHashCode` or `Equals` method of the class, you can always provide your own `IEqualityComparer` implementation to use instead when you create the `Dictionary`. The `Equals` method is intended for value equality, so it's not wrong to implement it that way.
Overriding GetHashCode for mutable objects?
[ "", "c#", ".net", "overriding", "equals", "gethashcode", "" ]
If I have a function `foo()` that windows has implemented in kernel32.dll and it always returns true, can I have my program: "bar.exe" hook/detour that Windows function and make it return false for all processes instead? So, if my svchost, for example, calls `foo()`, it will return false instead of true. The same action should be expected for all other processes currently running. If so, how? I guess I'm looking for a system-wide hook or something.
Take a look at [Detours](http://research.microsoft.com/en-us/projects/detours/ "Detours"), it's perfect for this sort of stuff. --- For system-wide hooking, read [this article](http://web.archive.org/web/20091228193034/http://msdn.microsoft.com/en-us/library/ms997537.aspx "MSDN") from MSDN. --- First, create a DLL which handles hooking the functions. This example below hooks the socket send and receive functions. ``` #include <windows.h> #include <detours.h> #pragma comment( lib, "Ws2_32.lib" ) #pragma comment( lib, "detours.lib" ) #pragma comment( lib, "detoured.lib" ) int ( WINAPI *Real_Send )( SOCKET s, const char *buf, int len, int flags ) = send; int ( WINAPI *Real_Recv )( SOCKET s, char *buf, int len, int flags ) = recv; int WINAPI Mine_Send( SOCKET s, const char* buf, int len, int flags ); int WINAPI Mine_Recv( SOCKET s, char *buf, int len, int flags ); int WINAPI Mine_Send( SOCKET s, const char *buf, int len, int flags ) { // .. do stuff .. return Real_Send( s, buf, len, flags ); } int WINAPI Mine_Recv( SOCKET s, char *buf, int len, int flags ) { // .. do stuff .. return Real_Recv( s, buf, len, flags ); } BOOL WINAPI DllMain( HINSTANCE, DWORD dwReason, LPVOID ) { switch ( dwReason ) { case DLL_PROCESS_ATTACH: DetourTransactionBegin(); DetourUpdateThread( GetCurrentThread() ); DetourAttach( &(PVOID &)Real_Send, Mine_Send ); DetourAttach( &(PVOID &)Real_Recv, Mine_Recv ); DetourTransactionCommit(); break; case DLL_PROCESS_DETACH: DetourTransactionBegin(); DetourUpdateThread( GetCurrentThread() ); DetourDetach( &(PVOID &)Real_Send, Mine_Send ); DetourDetach( &(PVOID &)Real_Recv, Mine_Recv ); DetourTransactionCommit(); break; } return TRUE; } ``` Then, create a program to inject the DLL into the target application. ``` #include <cstdio> #include <windows.h> #include <tlhelp32.h> void EnableDebugPriv() { HANDLE hToken; LUID luid; TOKEN_PRIVILEGES tkp; OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ); LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &luid ); tkp.PrivilegeCount = 1; tkp.Privileges[0].Luid = luid; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken, false, &tkp, sizeof( tkp ), NULL, NULL ); CloseHandle( hToken ); } int main( int, char *[] ) { PROCESSENTRY32 entry; entry.dwSize = sizeof( PROCESSENTRY32 ); HANDLE snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, NULL ); if ( Process32First( snapshot, &entry ) == TRUE ) { while ( Process32Next( snapshot, &entry ) == TRUE ) { if ( stricmp( entry.szExeFile, "target.exe" ) == 0 ) { EnableDebugPriv(); char dirPath[MAX_PATH]; char fullPath[MAX_PATH]; GetCurrentDirectory( MAX_PATH, dirPath ); sprintf_s( fullPath, MAX_PATH, "%s\\DllToInject.dll", dirPath ); HANDLE hProcess = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, FALSE, entry.th32ProcessID ); LPVOID libAddr = (LPVOID)GetProcAddress( GetModuleHandle( "kernel32.dll" ), "LoadLibraryA" ); LPVOID llParam = (LPVOID)VirtualAllocEx( hProcess, NULL, strlen( fullPath ), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE ); WriteProcessMemory( hProcess, llParam, fullPath, strlen( fullPath ), NULL ); CreateRemoteThread( hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)libAddr, llParam, NULL, NULL ); CloseHandle( hProcess ); } } } CloseHandle( snapshot ); return 0; } ``` This should be more than enough to get you started!
[EASYHOOK](https://github.com/EasyHook/EasyHook) <https://github.com/EasyHook/EasyHook> Dominate's all aformentioned techniques in simpleicty, flexability and functionality. It was not discussed previously on [Hook processes](https://stackoverflow.com/questions/299261/hook-processes) either. I've read all leaf's of this thread and with absolute certanty, [EASYHOOK](https://github.com/EasyHook/EasyHook) is vastly superiour. No matter if your using C, C++, CLR, whatever. I'll paste a bit from the codeplex homepage, to ensure sufficient omage being paid. ## The following is an incomplete list of features: 1. A so called "Thread Deadlock Barrier" will get rid of many core problems when hooking unknown APIs; this technology is unique to EasyHook 2. You can write managed hook handlers for unmanaged APIs 3. You can use all the convenience managed code provides, like NET Remoting, WPF and WCF for example 4. A documented, pure unmanaged hooking API 5. Support for 32- and 64-bit kernel mode hooking (also check out my PatchGuard 3 bypass driver which can be found in the release list) 6. No resource or memory leaks are left in the target 7. Experimental stealth injection mechanism that won't raise the attention of any current AV Software 8. EasyHook32.dll and EasyHook64.dll are pure unmanaged modules and can be used without any NET framework installed! 9. All hooks are installed and automatically removed in a stable manner 10. Support for Windows Vista SP1 x64 and Windows Server 2008 SP1 x64 by utilizing totally undocumented APIs, to still allow hooking into any terminal session. 11. Managed/Unmanaged module stack trace inside a hook handler 12. Get calling managed/unmanaged module inside a hook handler 13. Create custom stack traces inside a hook handler 14. You will be able to write injection libraries and host processes compiled for AnyCPU, which will allow you to inject your code into 32- and 64-Bit processes from 64- and 32-Bit processes by using the very same assembly in all cases. 15. EasyHook supports RIP-relative addressing relocation for 64-Bit targets. 16. No unpacking/installation is necessary. 17. The Visual Studio Redistributable is not required. I'm happy that my hooker's still know a few tricks in comparison that makes me keep them around. But to be sure, when you need a HOOK, 99 times of 100, EASYHOOK'r will get you there faster. And it's quite actively maintained.
How can I hook Windows functions in C/C++?
[ "", "c++", "c", "windows", "hook", "" ]
Please consider this code: ``` template<typename T> char (&f(T[1]))[1]; template<typename T> char (&f(...))[2]; int main() { char c[sizeof(f<void()>(0)) == 2]; } ``` I expected it doing SFINAE and chosing the second overload, since substitution of `T` into `T[1]` yields ``` void [1]() ``` Which is an invalid type, of course. Adjustment of parameter types (array->pointer) is done after substituting template parameters into function parameters and checking for valid resulting types like 14.8.2 [temp.deduct] describes. But both comeau and GCC fail to compile the above. Both with different diagnostics. Comeau says: > "ComeauTest.c", line 2: error: array of functions is not allowed `char (&f(T[1]))[1];` GCC says (version `4.3.3`): > error: ISO C++ forbids zero-size array `c` Meaning, GCC does not fail to substitute, but it chooses the first overload of `f`, returning a `sizeof` of 1, instead of failing to substitute it up front like Comeau. What compiler is right and is my code valid at all? Please refer to or quote the proper Standard section in your answer. Thanks! --- **Update**: The Standard itself contains such an example in the list at `14.8.2/2`. I don't know, why I overlooked it first: ``` template <class T> int f(T[5]); int I = f<int>(0); int j = f<void>(0); // invalid array ``` While the example is only informative, it shows the intention of all those mysterious paragraphs and seems to show the code above should work and reject the first overload.
A small note, although very rare, I have found some occasions where I believe that the Comeau compiler has it wrong - although, these occasions are so rare that its always worth double and triple checking your assumptions! I may have a reason for the behaviour of g++. I'm not sure its specified exactly when parameter types are adjusted: Consider the following: ``` template<typename T> struct A { void bar (T[10]); }; template<typename T> void A<T>::bar (T*) { } ``` The definition of 'bar' is legal, as "T[10]" decays to "T\*". I do not see anything in the standard that prohibits the compiler from performing the adjustments of 8.3.5 against the template declaration, and it also improves performance when it comes to overload matching. Applying this to your example, g++ might be treating it as: ``` template<typename T> char (&f( T* ))[1]; template<typename T> char (&f(...))[2]; int main() { char c[sizeof(f<void()>(0)) == 2]; } ``` In the above, the substituted parameter is a legal pointer to function, rather than an array of functions. So, the question for me is - is if there is something that prohibts the adjustments for the function parameters (8.3.5) twice? Personally, I think it makes sense to allow the adjustments to happen twice since otherwise it complicates the matching of function template overloads In conclusion, I think its valid for g++ to select the first overload based on how it treates decaying array parameters, and Comeau is wrong not to have a deduction failure for the array of functions. Of course this now means that (if Comeau was fixed) then each compiler would choose a different overload and would still be standards compliant! :( **EDIT:** Just to illustrate my point, consider the following code: ``` template <typename T> void foo ( T * ); template <typename T> void foo ( T * const ); template <typename T> void foo ( T [] ); template <typename T> void foo ( T [10] ); template <typename T> void foo ( T [100] ); void bar () { foo < void() > ( 0 ); } ``` Here, foo has been declared and redeclared several times. Which declaration, and so which parameter type, should the compiler apply the rules listed in 14.8.2? My point is that the standard doesn't say anything about the above. I would also go as far as to say that any wording on this would have to leave it as either "undefined" or "implementation defined" behaviour.
Suprisingly enough - this does work in VS2008. I don't think that's necessarily evidence for it being correct behaviour or not though... Visual Studio is interpretting ``` char (&f(T[1]))[1]; ``` as a function that takes an array of size 1 of T, and returns a reference to an array of chars of size 1.
SFINAE with invalid function-type or array-type parameters?
[ "", "c++", "arrays", "templates", "sfinae", "" ]
I'm currently trying to draw shapes with 2D Arrays. In my class there is a global array defined with `public char canvas[][];` Up until now, I have only declared arrays with `char canvas[][] = new char[height][width];` If this Array has already been declared, and I'm not supposed to amend the code I've been given, how do I call an instance of that array so that I can use it? thanks. (edit) ``` class DrawingSystem { public char canvas[][]; public static void makeNewCanvas(int tmpWidth, int tmpHeight) { canvas[][] = new char[tmpHeight][tmpWidth]; for (int row=0; row<tmpHeight; row++) { for (int col=0; col<tmpWidth; col++) { canvas[row][col] = ' '; } } } ```
You have an incompatibility between static methods and instance variables. Think about it this way: an instance variable is associated with a specific *instance* of a class; a static variable is associated with the *class* itself. You call static methods via the class: ``` ClassI.callStaticMethod(); ``` Whereas you call an instance method via an instance of the class: ``` public ClassI classObj = new ClassI(); classObj.callInstanceMethod(); ``` In the code you posted, there's an instance variable ("canvas") being set in a static method (`main` is associated with the Class, not an instance). Therefore, you'll need to create instance methods to modify/update your "canvas", and create an instance of the class within the static function. This object (an "instance") can be used to update the instance variable. Here's an example: ``` public class Foo { public char canvas[][]; public static void main(String[] args) { Foo fooObj = new Foo(); //creates an instance of this class fooObj.createCanvas(2, 2); fooObj.modifyCanvas(0, 0, 'c'); } public void createCanvas(int x, int y) { canvas = new char[x][y]; } public void modifyCanvas(int x, int y, char c) { canvas[x][y] = c; } } ``` This obviously isn't a one-to-one correlation to your assignment, but I'm sure you'll be able to adapt it to what you're doing :-)
Your problem is that `makeNewCanvas(int tmpWidth, int tmpHeight)` is static or `public char canvas[][]` is not static. In Java static class members can only work with other static class members. Static members belong to the class and non static members belong to instances. The class is a template that is used to create objects, these objects are called instances of the class. When you declare something static it is shared by all instances of the class. In the case of methods this means that static methods must behave exactly the same on all instances. ``` DrawingSystem a = new DrawingSystem(); DrawingSystem b = new DrawingSystem(); ``` `a` and `b` are instance of the class `DrawingSystem` that means they each have their own `canvas` array. Now since `makeNewCanvas` is static and must behave the same for all instances it cannot use `a.canvas` or `b.canvas` because they are unique to `a` and `b` and can have different contents.
Calling a global Array
[ "", "java", "arrays", "global-variables", "" ]
I have an image that is generated automatically inside an Ajax UpdatePanel. This image is a graph that is generated from server-side code. Searching in Google, I realised it was a bug of FF. Does anybody have any solution? Here is the source (it contains also unneeded tags, I just copied-paste) ``` <div> <asp:UpdatePanel ID="UpdatePanelGraph" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Panel ID="pnlGraph" runat="server" CssClass="container"> <div id="chart"> <Web:ChartControl ID="chartExchange" runat="server" Width="300px" Height="200px" BorderStyle="None" GridLines="both" DefaultImageUrl="../images/noData.png" ShowTitlesOnBackground="False" BorderWidth="1px" Padding="1" HasChartLegend="False" BottomChartPadding="20" TopChartPadding="5" RightChartPadding="5" LeftChartPadding="20"> <Border Color="211, 224, 242"></Border> <YAxisFont ForeColor="115, 138, 156" Font="Tahoma, 7pt" StringFormat="Far,Center,Character,LineLimit"></YAxisFont> <XTitle ForeColor="115, 138, 156" StringFormat="Center,Near,Character,LineLimit"> </XTitle> <XAxisFont ForeColor="115, 138, 156" StringFormat="Near,Near,Character,NoClip"></XAxisFont> <Background Type="LinearGradient" Color="#C9DEFD" ForeColor="Transparent" EndPoint="500, 500"> </Background> <ChartTitle ForeColor="51, 51, 51" Font="Verdana, 9pt, style=Bold" StringFormat="Near,Near,Character,LineLimit"> </ChartTitle> <Charts> <Web:SmoothLineChart Name="buy" Legend="Blen"> <Line Color="ActiveCaption"></Line> <DataLabels> <Border Color="Transparent"></Border> <Background Color="Transparent"></Background> </DataLabels> </Web:SmoothLineChart> <Web:ColumnChart Name="avgChart"> </Web:ColumnChart> </Charts> <YTitle ForeColor="115, 138, 156" StringFormat="Center,Near,Word,LineLimit"></YTitle> </Web:ChartControl> </div> </asp:Panel> </ContentTemplate> </asp:UpdatePanel> </div> ```
Also it is not a good solution, setting the cacheability to nocache resolved my problem. I worte this on my pageload ``` Response.Cache.SetCacheability(HttpCacheability.NoCache); ``` It also works by setting this code ``` <script type="text/javascript"> var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_pageLoaded(pageLoaded); var c = 0; function pageLoaded(sender, args) { var img = document.getElementById("ctl00_ctl00_MainContent_MainContent_chartExchange"); c++; img.src = img.src + "?" + c; } </script> ```
What version of .NET are you using? The 3.5 framework has a new graphing control. I spent a few days playing around with it, and was surprised at how powerful it is. And I also used it in UpdatePanels without any problems whatsoever.
Image inside UpdatePanel not working in Firefox
[ "", "c#", "asp.net", "ajax", "updatepanel", "webchartcontrol", "" ]
I am in need of a component or control that can read a DVD and play it back either on the current window, on another window, or in an arbitrary position on-screen (to be indicated programmatically). There do not need to be any user-visible controls on it; the app will handle that separately. Where do I need to turn? FYI, I'm using .Net 3.5 in a winforms application. I feel like I'm probably missing something simple, but it is escaping me. ;-) -- afward
You can use a Windows Media Player control. The example is in VB.NET, but you should be able to translate very easily. <http://msdn.microsoft.com/en-us/library/dd562852(VS.85).aspx>
Embed the windows media control to your window. Here is the c# code : <http://msdn.microsoft.com/en-us/library/dd562851(v=vs.85).aspx>
DVD Playback in C#?
[ "", "c#", "playback", "dvd", "" ]
I have several classes that conceptually belong to one tier. They have no common properties which is why they have no need to inherit from some base class. I also have a few methods that deal with these classes. Some of them are templates of the following style: ``` public SomeClass { public void SomeMethod<T> (T argument) where T : BaseClass { /* Do something */ } } ``` So I'm using this WHERE keyword just to secure the code (from myself I suppose), so that I don't by mistake feed to this method something else. Naturally I made those other classes derive from BaseClass which is empty and has no other purpose (at least for now) than to group other classes. This is probably not that good approach but anyway I'm using it. Is there a better way to do this? EDIT: After consideration I decided not to go with that approach and just removed that base class. Good enough without it. I cannot make the code absolutely perfect anyway, and the less unneeded thing there are the better.
Use a marker (empty) interface instead of a base class: ``` public void SomeMethod<T> (T argument) where T : ISomeInterface ```
+1 on Jeff's answer. Tagging ("marker") interfaces are common in both C# and Java frameworks. They let you assign a common type to "class A" so that another class ("class B") can be ignorant of class A's concrete type. As with anything this flexible, it's easy to misuse, but in your case it definitely fills the bill.
Using empty parent class just to group other classes. Is there a better approach?
[ "", "c#", "oop", "coding-style", "" ]
I'm looking for a way to have an interactive JIT debugger, preferably integrated with Firebug. I got the idea from PHPEd, which has an "Immediate" debug tab where you can just type in PHP code and modify objects on the fly. This makes debugging a breeze as you can re-assign variables multiple times, re-execute functions, etc without leaving the program. Here's what I think would be superb: - set a breakpoint in Firebug - arrive to breakpoint - have an Execute JS tab where one could enter JS code, similar to what I described above Does anything like this exist already? TIA.
You can already do this in Firebug. Just get to a break point, then go to the "console" tab, and type your commands into the command line at the bottom (where there's the ">>>").
If I understand the question correctly, I think can do that already in firebug. * Set a breakpoint (or use the debugger keyword) * Click the console tab * the bottom line allows you to enter a javascript command. * if you need more space click the icon that looks like an upside down v in the bottom right part of the browser. You might also like the [JS execute extension](https://addons.mozilla.org/en-US/firefox/addon/1729).
Interactive Javascript console (preferably integrated with Firebug)
[ "", "javascript", "debugging", "firefox", "firebug", "" ]
I have a list of objects and each and every object in the list have a position which may not change unless explicitly changed, in other words, the objects are in a queue. What collection should I use in my entity class to store these objects and how should that collection be annotated? I currently have this ``` @Entity class Foo { ... @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL) List<Bar> bars = new ArrayList<Bar>(); ... } ``` If this is not possible with JPA purely, I'm using EclipseLink as my JPA provider, so EclipseLink specific annotations will ok if nothing else helps. EDIT: Note people, the problem is not that Java wouldn't preserv the order, I know most collections do, the problem is that I don't know a smart way for JPA to preserv the order. Having an order id and making the query order by it is possible, but in my case maintaining the order id is laborious (because the user interface allows reordering of items) and I'm looking for a smarter way to do it.
If you want this to be ordered after round-tripping to SQL, you should provide some sort of ordering ID within the entity itself - SQL is naturally set-oriented rather than list-oriented. You can then either sort after you fetch them back, or make sure your query specifies the ordering too. If you give the entity an auto-generated integer ID this *might* work, but I wouldn't like to guarantee it.
Use a sort order id, as Jon suggested, then add an @OrderBy annotation below the @OneToMany. This will order any query by the specified field. As an example, if you add a new field called "sortId" to Bar, Foo would look like this: ``` @Entity class Foo { ... @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL) @OrderBy("sortId ASC") List bars = new ArrayList(); ... } ```
How do I guarantee the order of items in a collection
[ "", "java", "jpa", "eclipselink", "" ]
I am still confused of the concept of ThreadLocal. I have read the JavaDoc, and other related questions posted around here, but the jargons used and all didn't help me much. I kind of get the idea of ThreadLocal, that is, each thread has its own copy of the variable. So...how does this make it different from say...constructing the new variable everytime? For example, using DateFormatter as the example: ``` public void convertDate(String date) { // Contruct new date formatter for every invocation of the method. DateFormatter df = new SimpleDateFormatter(...); .... } public void convertDate(String date) { // Getting date formatter from threadlocal. DateFormatter df = threadLocal.get(); .... } ``` How is the first different from the second one if the all the second one does is just returning a new copy of the variable? Thanks.
ThreadLocal objects are typically static, which means that they preserve their values between function calls within the same thread. In your first code snippet, every time `convertDate` is called, a new `SimpleDateFormatter` object is created. In the second snippet, one `SimpleDateFormatter` object per thread is created. The same object is returned by the `get()` method every time `convertDate` is called within the same thread. ThreadLocal objects are useful in implementing [thread-local storage](http://en.wikipedia.org/wiki/Thread-Specific_Storage), which means maintaining separate instances of variables for each thread.
There are a few different uses for `ThreadLocal`. As in your example, an expensive to construct, thread-unsafe object can be cached. The object than can then be used in a safe manner without the overhead of construction every use. It's not necessarily a win (more, non-local memory is used, for instance), but it might be. It can also be used to 'sleaze' through a context argument into a callback that isn't designed to have context. Or just to make interfaces simpler. In this case the canonical reference to the `ThreadLocal` is probably not static. The object may also be deliberately mutable. I'm not a great fan of encouraging this technique, but some people (such as "crazy" Bob Lee) like it. `ThreadLocal` doesn't work so well when you fork tasks off into multiple threads. `InheritableThreadLocal` appears to have no good uses.
ThreadLocal; isn't it the same as creating a copy of the variable each time?
[ "", "java", "thread-local", "" ]
I am having a hard time with this problem which requires a sort of customer names, customer ids, and finally amount due. I have the whole program figured, but cannot figure out the last prototype needed to do the sorting. i have a struct called Customers, and i will provide the int main() part also. I just need any help to gt started on the prototype SortData(). ``` struct Customers { string Name; string Id; float OrderAmount; float Tax; float AmountDue; }; const int MAX_CUSTOMERS = 1000; bool MoreCustomers(int); Customers GetCustomerData(); void OutputResults(Customers [], int); void SortData(const int, const int, Customers []); int main() { Customers c[MAX_CUSTOMERS]; int Count = 0; do { c[Count++] = GetCustomerData(); } while (MoreCustomers(Count)); for (int i = 0; i < Count; i++) { c[i].Tax = 0.05f * c[i].OrderAmount; c[i].AmountDue = c[i].OrderAmount + c[i].Tax; } SortData(0, Count, c); //0:Sorts by customer name OutputResults(c, Count); GeneralSort(1, Count, c); //1:Sorts by ID OutputResults(c, Count); GeneralSort(2, Count, c); //2: Sorts by amount due OutputResults(c, Count); return 0; } void SortData(const int SortItem, const int count, CustomerProfile c[]) { //0: Sort by name //1: Sort by ID //3: Sort by amount due } ```
You should use C++'s standard sort function, `std::sort`, declared in the `<algorithm>` header. When you sort using a custom sorting function, you have to provide a *predicate function* that says whether the left-hand value is *less than* the right-hand value. So if you want to sort by name first, then by ID, then by amount due, all in ascending order, you could do: ``` bool customer_sorter(Customer const& lhs, Customer const& rhs) { if (lhs.Name != rhs.Name) return lhs.Name < rhs.Name; if (lhs.Id != rhs.Id) return lhs.Id < rhs.Id; return lhs.AmountDue < rhs.AmountDue; } ``` Now, pass that function to your `sort` call: ``` std::sort(customers.begin(), customers.end(), &customer_sorter); ``` This assumes you have an STL container (and not an array, like you have in your sample code) called `customers` containing customers.
Its often overlooked that you can actually use STL range functions with C based arrays, like in your example. So you don't actually have to move over to using an STL based container (I won't debate the merits of doing that here :-)). So, building on the answer from Chris, you could invoke sort as follows: ``` std::sort( customers, customers+Count, &customer_sorter); ```
c++ sort with structs
[ "", "c++", "arrays", "sorting", "struct", "bubble-sort", "" ]
I have some C# code that will upload images and files into a db. Currently I thought It working for all documents that fit a list of mimetypes. However It fails on some pdf's. I have narrowed the problem down to the fact that some pdf's are in the 1.3 format and some are in the 1.4 format. The 1.4 works and is properly uploaded, however 1.3 does not upload and it does not generate any runtime errors it just fails to be added. Some of the current code for uploading the pdf is ``` Checks for valid MIME Type ... byte[] fileData = new byte[uploadFile.ContentLength]; uploadFile.InputStream.Read(fileData, 0, uploadFile.ContentLength); ... Continues on to Uploads to db. ``` For pdf's it is looking for "application/pdf" as the mime type. I don't think there is another type for pdfs in the 1.3 format, but maybe I am wrong. Anyone else ever have this problem before and any advice on how to correct it?
It seems that it was just a stupid mistake. The file had a .PDF extension unlike the rest with a .pdf. Stupid caps got me. A bit of extra debug statements did the trick.
The problem *may* be the way you're reading from the input stream. Whenever you deal with streams, you should read repeatedly, taking note of the return value on each iteration. So your original code should be: ``` byte[] fileData = new byte[uploadFile.ContentLength]; int totalRead = 0; while (totalRead < fileData.Length) { int read = uploadFile.InputStream.Read(fileData, totalRead, fileData.Length - totalRead); if (read == 0) { throw new IOException("Input data was truncated"); } totalRead += read; } ``` However, that may not be the problem. I'd expect that to result in truncated data, not a complete absence of data. When you say it "just fails to be added" could you be more specific? How much logging have you put in? Where's the code which actually inserts the data into the database? What mime type do your logs show for the cases where it's failing? It sounds to me like extra logging would probably make a *huge* difference here... currently either you don't know where it's going wrong, or you just haven't told us. Logging should make that quite clear.
Uploading PDF v1.3 to DB
[ "", "c#", "asp.net", "pdf", "mime-types", "" ]
I have implemented a very basic "plug-in system" as part of a *static library*. Each "plug-in" implements the support for a specific image format, e.g. GIF, JPEG, etc.. Furthermore, I have a Singleton (a class called `PluginManager`) that keeps a list of all available plug-ins. The tricky part is that I want to disable/enable the plug-ins by adding or removing their source files from the project file. To achieve this, each plug-in creates a global variable (with different names) and registers the plug-in in the constructor of that class to `PluginManager`. Something like this for the JPEG format... ``` struct JPEGPlugin { // constructor will register plugin JPEGPlugin() { PluginManager::Singleton().RegisterPlugin(this); } // plenty of other code ... }; JPEGPlugin jpeg_instance; // instantiate in global scope ``` However, while this works perfectly in theory, it fails when linking this static library to other code to build an executable. As long as this executable does not access the plugin globals (like `jpeg_instance`), the linker does not see a connection (he completely ignores the side-effects of the constructor) and does not include the code in the final executable. In other words, the JPEG plug-in is not available in the final app. I ran into the problems a couple of times over the years, and I always searched the net for solutions. Each time, I just found pages that basically say that it's a known problem and that I have to live with it. But maybe someone on SO knows how to make this working?
I don't know if this a solution for the way you solved this problem, but we had a similar problem with static registration of an object factory and in Visual Studio we solved it by declaring the classes involved with \_\_declspec(dllexport) this was necessary even though the libraries involved were not dlls. But without this the linker would omit the not referenced classes. The registry solution we worked a little bit different and did not involve Stack allocated objects. I lifted parts from CPP-unit, that is also where i discovered the \_\_declspec approach iirc. [edit] We also had to `#include` the declaration for the registered class from some part of the code.
Since it is a static libary, you might consider having the manager register the plugins (instead of the plugins registering themselves). The header file can define some preproc symbol (ie JPEG\_PLUGIN) that controls whether or not the manager registers the plugin based on the inclusion of the header: ``` #include "JpegPlugin.h" void PluginManager::RegisterPlugins() { #idef JPEG_PLUGIN RegisterPlugin(&jpeg_instance); #endif } ``` JpegPlugin.h doesn't necessarily need to include the definition of the JpegPlugin. It could be something like this: ``` #ifndef JPEG_PLUGIN_HEADER #define JPEG_PLUGIN_HEADER #if 0 // change this to 1 to use the plugin #define JPEG_PLUGIN #include "Jpeg_PluginCls.h" #endif #endif ```
Object Registration in Static Library
[ "", "c++", "plugins", "static-libraries", "" ]
I've added php as a module for Apache 2.2.11: ``` LoadModule php5_module "c:/php/php5apache2_2.dll" ``` And also added ``` AddType application/x-httpd-php .php ``` And in PHP.ini, my extension dir is set to: `extension_dir = "C:\php\ext"` And **yes**, the directories are correct and all files do exist. But when I start apache, I get these errors: > PHP Warning: PHP Startup: Unable to load dynamic library 'C:\php\ext\php\_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0 > PHP Warning: PHP Startup: Unable to load dynamic library 'C:\php\ext\php\_pdo\_pgsql.dll' - The specified module could not be found.\r\n in Unknown on line 0 > PHP Warning: PHP Startup: Unable to load dynamic library 'C:\php\ext\php\_pgsql.dll' - The specified module could not be found.\r\n in Unknown on line 0 > > [Sun May 17 03:46:01 2009] [notice] Apache/2.2.11 (Win32) PHP/5.2.9-2 configured -- resuming normal operations > [Sun May 17 03:46:01 2009] [notice] Server built: Dec 10 2008 00:10:06 > [Sun May 17 03:46:01 2009] [notice] Parent: Created child process 4652 > > PHP Warning: PHP Startup: Unable to load dynamic library 'C:\php\ext\php\_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0 > PHP Warning: PHP Startup: Unable to load dynamic library 'C:\php\ext\php\_pdo\_pgsql.dll' - The specified module could not be found.\r\n in Unknown on line 0 > PHP Warning: PHP Startup: Unable to load dynamic library 'C:\php\ext\php\_pgsql.dll' - The specified module could not be found.\r\n in Unknown on line 0 > > [Sun May 17 03:46:01 2009] [notice] Child 4652: Child process is running > [Sun May 17 03:46:01 2009] [notice] Child 4652: Acquired the start mutex. > [Sun May 17 03:46:01 2009] [notice] Child 4652: Starting 64 worker threads. > [Sun May 17 03:46:01 2009] [notice] Child 4652: Starting thread to listen on port 80. So I'm probably forgetting something simple here, can someone tell me what I'm forgetting?
Not only you need PHP extension's DLLs in order to add MySQL and PostgreSQL support to PHP. You also need MySQL and PostgreSQL native libraries. PHP extension's DLLs are probably not finding some DLL they depend on, so they can't start. Make sure you have MySQL and PostgreSQL client installed, and their DLLs into some locatable place. I.E. example: * php\_mysql.dll depends on libmysql.dll So, make sure PHP is able to find libmysql.dll (I believe this one comes with the binary distribution of Windows PHP. Not sure though).
To add to Pablo Santa Cruz's advice. On windows you can include the required libraries in the `PATH` environment. (No necessarily copy to Windows folder). When loading libraries widows looks in `PATH` directories as well. If you use standard Win32 binary distribution from php.net for PHP5.2, then the package should contain all the dependencies in the root of the packages. So, if you have installed the PHP5.2 into `C:\php`, add this directory to the `PATH` envar. Restart the Apache and I'd expect extensions to load properly.
PHP extensions won't load on Apache startup
[ "", "php", "windows", "apache", "" ]
[GitPython](http://gitorious.org/git-python) is a way of interacting with git from python. I'm trying to access the basic git commands (e.g. `git commit -m "message"`) from this module, which according to [this](http://pysync.googlecode.com/files/GitPython.pdf) should be accessed through the Git module. Here's what I've tried so far to get these commands working: ``` >>> import git >>> foo = git.Git("~/git/GitPython") >>> bar = "git commit -m 'message'" >>> beef = git.Git.execute(foo,bar) ``` This shows up an error saying that there is no such file or directory. I've also tried the following as paths to my git directory: `~/git/GitPython/.git` `/Users/bacon/git/gitclient/` The only other option is that the command is wrong, so I tried: `commit -m "message"` as well, and still get "no such file or directory". What do I need to do to get these git commands working properly?
I havn't tried it to verify yet but it seems git.Git.execute expects a list of commandline arguments (if you give it a string it'll look for an executable exactly matching the string, spaces and everything - which naturally wouldn't be found), so something like this I think would work: ``` import git import os, os.path g = git.Git(os.path.expanduser("~/git/GitPython")) result = g.execute(["git", "commit", "-m", "'message'"]) ``` other changes: * I expect using a path with ~ in it wouldn't work so I used os.path.expanduser to expand ~ to your home directory * using instance.method(\*args) instead of Class.method(instance, \*args) is generally preferred so I changed that, though it'd still work with the other way There might be saner ways than manually running the commit command though (I just didn't notice any quickly looking through the source) so I suggest making sure there isn't a higher-level way before doing it that way
In the tutorial it says ... ``` The first step is to create a ``Repo`` object to represent your repository. >>> from git import * >>> repo = Repo("/Users/mtrier/Development/git-python") ``` I don't see your Repo. I am looking at the file named tutorial.rst in the doc directory of GitPython.
GitPython and sending commands to the Git object
[ "", "python", "git", "" ]
I have a problem with javascript. I have a list of table cells stored at TabList. I want to find the maximum width, and then set this width to all of them. A sample code is here, but the setting of the width is not working. ``` var MaxTabWidth = 0; for (var i = 0; i < TabList.length-1; i++) { if (TabList[i].offsetWidth>MaxTabWidth) MaxTabWidth = TabList[i].offsetWidth; } for (var i = 0; i < TabList.length-1; i++) { TabList[i].style.width = MaxTabWidth+"px"; // TabList[i].width = MaxTabWidth+"px"; // TabList[i].offsetWidth = MaxTabWidth+"px"; } ``` I have commented my attempts.. Any help? [This](https://stackoverflow.com/questions/456859/any-way-to-synchronize-table-column-widths-with-html-css/458762#458762) didn't do the trick for me.. **update:** I am sure TabList is a list of Cells because I was checking the className. I am looping until TabList.length-1, because I want the last cell to fill the rest of the table's width.
I would suggest you remove all css/styling from the page and testing it to isolate the problem. Things like this are often complicated by css.
If you set the width of the entire table to --i\*MaxTabWidth. Would that evenly distribute the columns? Suppose your table is named myTable. ``` document.getElementById('myTable').width = new String(--i*MaxTabWidth) ``` Edit: Also wouldn't ``` for (var i = 0; i < TabList.length-1; i++) ``` skip the last column by stopping at TabList.length-2?
How to resize table columns width from JavaScript
[ "", "javascript", "css", "column-width", "" ]
I tried to show an error message using the jquery effect `fadeTo` and tried to hide the message by appending a button and using fadeout but doesn't seem to work. What I did was: ``` $("#sub_error") .fadeTo(200, 0.1, function() { $("#sub_error") .html(error.join("<br/><br/>")) .append('<br/><input type="button" name="err_ok" id="err_ok" value="ok">') .addClass('subboxerror') .fadeTo(900,1); }); $("#err_ok").click(function() { $("#sub_error").fadeOut("slow"); }); ``` What am I doing wrong, could someone help me?
the #err\_ok element doesn't exist at first so the .click() handler is not applied to it. You can solve this by putting ``` $("#err_ok").click(function () { $("#sub_error").fadeOut("slow"); }); ``` in a function and call the function after creating the element in the DOM. Edit: This should be a full solution: ``` $("#sub_error").fadeTo(200, 0.1, function() { $("#sub_error") .html(error.join("<br/><br/>")) .append('<br/><input type="button" name="err_ok" id="err_ok" value="ok">') .addClass('subboxerror') .fadeTo(900, 1); bindEvents(); }); function bindEvents() { $("#err_ok").click(function() { $("#sub_error").fadeOut("slow"); }); } ``` There is also a "[live](http://docs.jquery.com/Events/live)" function that binds events to future created DOM elements too.
FWIW, there are filed tickets about fadeTo/fadeOut bugs on the JQuery bug tracker.
How can I bind events to the appended element?
[ "", "javascript", "jquery", "" ]
I'm just wondering, what is the whole point of separating classes into an .h and a .cpp file? It makes it harder to edit, and if your class won't be compiled into a .lib or .dll for outside use, what's the point? Edit: The reason I'm asking is that the Boost libraries put everything in an .hpp file, (most of the libraries anyways), and I wanted to know why it is separated in most of the other code that I see.
C++ has something called the One Definition Rule. It means that (excluding inline functions), definitions can only appear in one compilation unit. Since C++ header files are just "copy and pasted" at every include file, now you are putting definitions in multiple places if you just put the definitions in header files. Of course, you may say, why not make everything inline. Well, if the compiler respects your inline suggestion, code for long functions will be replicated at every call site, making your code excessively large, and possibly causing thrashing, cache issues, and all sorts of unfun stuff. On the other hand, if the compiler does not listen to you, and doesn't inline anything, now you have 2 problems: 1) you don't know which translation unit got your classes definitions, and 2) the compiler still has to wade through your definitions every time you #include them. Moreover, there's no easy way to make sure you haven't accidentally defined the same method twice, in 2 different headers, differently. You also get a circular dependency issue. For a class to invoke another class's method, that class needs to be declared first. So if 2 classes need to invoke each other's methods, each must be declared before either can be defined. There is no way to do this with declarations and definitions in one file. Really, it's how the language and parser were built. It's a pain, but you just have to deal with it.
Well, one of the benefits of having the code this way is that it reduces compile time. Let's say you have these files on your project: * a.h * a.cpp * b.cpp If you already have a.cpp compiled into an object file **a.o**, then if you include **a.h** in **b.cpp**, compilation should be quicker because parser won't have to deal with the whole declaration/definition of **a**.
Why put a class declaration and definition in two separate files in C++?
[ "", "c++", "" ]
How can i convert a vartiables value int anothers name in C++? like in this php snippet. ``` $string = 'testVar'; ${$string} = 'test'; echo $testVar; // test ```
How about using a map? ``` #include <iostream> #include <map> #include <string> using namespace std; map<string, string> hitters; hitters["leadoff"] = "Jeter"; hitters["second"] = "Damon"; hitters["third"] = "Teixiera"; hitters["cleanup"] = "Matsui"; string hitter = "cleanup"; cout << hitters[hitter] << endl; ```
I don't know PHP, but I don't think you can do that in C++. A variable name has no runtime representation in a compiled C++ program, so there is no way to load its name at runtime like that. This seems to be something you can only do in a scripting language where the original source code is in memory or at least some representation of the syntax tree.
C++ string value as another strings name
[ "", "c++", "" ]
Consider the following code. Is DoSomething1() faster then DoSomething2() in a 1000 consecutive executions? I would assume that if I where to call DoSomething1() it 1000 times it would be faster then calling DoSomething2() it 1000 times. Is there any disadvantage to making all my large buffers static? ``` #define MAX_BUFFER_LENGTH 1024*5 void DoSomething1() { static char buf[MAX_BUFFER_LENGTH] ; memset( buf, 0, MAX_BUFFER_LENGTH ); } void DoSomething2() { char buf[MAX_BUFFER_LENGTH] ; memset( buf, 0, MAX_BUFFER_LENGTH ); } ``` Thank you for your time.
**Disadvantage of static buffers:** * If you need to be thread safe then using static buffers probably isn't a good idea. * Memory won't be freed until the end of your program hence making your memory consumption higher. **Advantages of static buffers:** * There are less allocations with static buffers. You don't need to allocate on the stack each time. * With a static buffer, there is less chance of a stack overflow from too high of an allocation.
The stack allocation is a little more expensive if you have /GS enabled in the VC++ compiler, which enables security checks for buffer overruns (/GS is on by default). Really, you should profile the two options and see which is faster. It's possible that something like cache locality in the static memory vs on the stack could make the difference. Here's the non-static version, with the VC++ compiler with /O2. ``` _main PROC ; COMDAT ; Line 5 mov eax, 5124 ; 00001404H call __chkstk mov eax, DWORD PTR ___security_cookie xor eax, esp mov DWORD PTR __$ArrayPad$[esp+5124], eax ; Line 7 push 5120 ; 00001400H lea eax, DWORD PTR _buf$[esp+5128] push 0 push eax call _memset ; Line 9 mov ecx, DWORD PTR __$ArrayPad$[esp+5136] movsx eax, BYTE PTR _buf$[esp+5139] add esp, 12 ; 0000000cH xor ecx, esp call @__security_check_cookie@4 add esp, 5124 ; 00001404H ret 0 _main ENDP _TEXT ENDS ``` And here's the static version ``` ; COMDAT _main _TEXT SEGMENT _main PROC ; COMDAT ; Line 7 push 5120 ; 00001400H push 0 push OFFSET ?buf@?1??main@@9@4PADA call _memset ; Line 8 movsx eax, BYTE PTR ?buf@?1??main@@9@4PADA+3 add esp, 12 ; 0000000cH ; Line 9 ret 0 _main ENDP _TEXT ENDS END ```
Large buffers vs Large static buffers, is there an advantage?
[ "", "c++", "optimization", "performance", "" ]
I've been batting this problem around in my head for a few days now and haven't come to any satisfactory conclusions so I figured I would ask the SO crew for their opinion. For a game that I'm working on I'm using a Component Object Model as described [here](http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/) and [here](http://www.drizzle.com/~scottb/gdc/game-objects_files/frame.htm). It's actually going fairly well but my current storage solution is turning out to be limiting (I can only request components by their class name or an arbitrary "family" name). What I would like is the ability to request a given type and iterate through all components of that type or any type derived from it. In considering this I've first implemented a simple RTTI scheme that stores the base class type through the derived type in that order. This means that the RTTI for, say, a sprite would be: component::renderable::sprite. This allows me to compare types easily to see if type A is derived from type B simply by comparing the all elements of B: i.e. component::renderable::sprite is derived from component::renderable but not component::timer. Simple, effective, and already implemented. What I want now is a way to store the components in a way that represents that hierarchy. The first thing that comes to mind is a tree using the types as nodes, like so: ``` component / \ timer renderable / / \ shotTimer sprite particle ``` At each node I would store a list of all components of that type. That way requesting the "component::renderable" node will give me access to all renderable components regardless of derived type. The rub is that I want to be able to access those components with an iterator, so that I could do something like this: ``` for_each(renderable.begin(), renderable.end(), renderFunc); ``` and have that iterate over the entire tree from renderable down. I have this pretty much working using a really ugly map/vector/tree node structure and an custom forward iterator that tracks a node stack of where I've been. All the while implementing, though, I felt that there must be a better, clearer way... I just can't think of one :( So the question is: Am I over-complicating this needlessly? Is there some obvious simplification I'm missing, or pre-existing structure I should be using? Or is this just inheritly a complex problem and I'm probably doing just fine already? Thanks for any input you have!
You should think about how often you need to do the following: * traverse the tree * add/remove elements from the tree * how many objects do you need to keep track of Which is more frequent will help determine the optimum solution Perhaps instead of make a complex tree, just have a list of all types and add a pointer to the object for each type it is derived from. Something like this: ``` map<string,set<componenet *>> myTypeList ``` Then for an object that is of type component::renderable::sprite ``` myTypeList["component"].insert(&object); myTypeList["renderable"].insert(&object); myTypeList["sprite"].insert(&object); ``` By registering each obejct in multiple lists, it then becomes easy to do something to all object of a given type and subtypes ``` for_each(myTypeList["renderable"].begin(),myTypeList["renderable"].end(),renderFunc); ``` Note that std::set and my std::map construct may not be the optimum choice, depending on how you will use it. Or perhaps a hybrid approach storing only the class heirarchy in the tree ``` map<string, set<string> > myTypeList; map<string, set<component *> myObjectList; myTypeList["component"].insert("component"); myTypeList["component"].insert("renderable"); myTypeList["component"].insert("sprite"); myTypeList["renderable"].insert("renderable"); myTypeList["renderable"].insert("sprite"); myTypeList["sprite"].insert("sprite"); // this isn't quite right, but you get the idea struct doForList { UnaryFunction f; doForList(UnaryFunction f): func(f) {}; operator ()(string typename) { for_each(myTypeList[typename].begin();myTypeList[typename].end(), func); } } for_each(myTypeList["renderable"].begin(),myTypeList["renderable"].end(), doForList(myFunc)) ```
If you want to see code for an existing implementation, the Game Programming Gems 5 article referenced in the Cowboy Programming page comes with a somewhat stripped down version of the code we used for our component system (I did a fair chunk of the design and implementation of the system described in that article). I'd need to go back and recheck the code, which I can't do right now, we didn't represent things in a hierarchy in the way you show. Although components lived in a class hierarchy in code, the runtime representation was a flat list. Components just declared a list of interfaces that they implemented. The user could query for interfaces or concrete types. So, in your example, Sprite and Particle would declare that they implemented the RENDERABLE interface, and if we wanted to do something to all renderables, we'd just loop through the list of active components and check each one. Not terribly efficient on the face of it, but it was fine in practice. The main reason it wasn't an issue was that it actually turns out to not be a very common operation. Things like renderables, for example, added themselves to the render scene at creation, so the global scene manager maintained its own list of renderable objects and never needed to query the component system for them. Similarly with phyics and collision components and that sort of thing.
Structure for hierarchal Component storage
[ "", "c++", "stl", "" ]
I have a problem which requires a reversable 1:1 mapping of keys to values. That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. ``` x = D[y] y == D.inverse[x] ``` The obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, [there's a recipe here but for a large dictionary it can be very slow](https://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833). The other alternative is to make a new class which unites two dictionaries, one for each kind of lookup. That would most likely be fast but would use up twice as much memory as a single dict. So is there a better structure I can use? * My application requires that this should be very fast and use as little as possible memory. * The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index) * We can guarantee that either the key or the value (or both) will be an integer * It's likely that the structure will be needed to store thousands or possibly millions of items. * Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]
``` class TwoWay: def __init__(self): self.d = {} def add(self, k, v): self.d[k] = v self.d[v] = k def remove(self, k): self.d.pop(self.d.pop(k)) def get(self, k): return self.d[k] ```
> *The other alternative is to make a new > class which unites two dictionaries, > one for each kind of lookup. That > would most likely be fast but would > use up twice as much memory as a > single dict.* Not really. Have you measured that? Since both dictionaries would use references to the **same objects** as keys and values, then the memory spent would be just the dictionary structure. That's a lot less than ***twice*** and is a fixed ammount regardless of your data size. What I mean is that the actual data wouldn't be copied. So you'd spend little extra memory. Example: ``` a = "some really really big text spending a lot of memory" number_to_text = {1: a} text_to_number = {a: 1} ``` Only a single copy of the "really big" string exists, so you end up spending just a little more memory. That's generally affordable. I can't imagine a solution where you'd have the key lookup speed when looking by value, if you don't spend *at least* enough memory to store a reverse lookup hash table (which is exactly what's being done in your "unite two `dict`s" solution).
A data-structure for 1:1 mappings in python?
[ "", "python", "data-structures", "" ]
I have the following simple function: ``` private void EnableDisable941ScheduleBButton() { if (this._uosDepositorFrequency.Value != null) this._btnScheduleB.Enabled = ((int)this._uosDepositorFrequency.Value == 0); } ``` It's a member of a Winform class which I'm trying to split into a passive view and presenter. It's obvious there is business logic tangled together with UI wiring. I'm just not sure of the best way to separate them. To give a little context, the function is called from three locations in the form. \_uosDepositorFrequency is a radiobutton group with only two buttons. Any ideas? Update: Ok, maybe it isn't as obvious as I thought. The business rule states that if an employer makes semiweekly deposits (\_uosDepositorFrequency.Value = 0) they are required to fill out a Schedule B form.
First I'd like to thank all those who responded to my question. I spent some time working on this and I believe I've come up with a solution. First I exposed \_uosDepositorFrequency.Value and \_btnScheduleB.Enabled as public properties and update the view interface I also took a few moments to define an enum for the deposit frequencies. ``` public bool EnableScheduleB { get { return _btnScheduleB.Enabled; } set { _btnScheduleB.Enabled = value; } } public DepositFrequency DepositorFrequency { get { return (DepositFrequency)_uosDepositorFrequency.Value; } set { _uosDepositorFrequency.Value = (int)value; } } ``` Then I copied the body of the original function to my presenter and modified it to use the properties I just created. The null checking in the original function turned out to be unnecessary because the \_uosDepositorFrequency control is initialized elsewhere. ``` public void UpdateScheduleBStatus() { ReturnView.EnableScheduleB = ReturnView.DepositorFrequency == DepositFrequency.Semiweekly; } ``` Finally the \_uosDepositorFrequency\_ValueChanged event handler was updated to call UpdateScheduleBStatus. ``` private void _uosDepositorFrequency_ValueChanged(object sender, System.EventArgs e) { Presenter.UpdateScheduleBStatus(); } ``` Comments welcome.
Presenter: ``` if(this._uosDepositorFrequency.Value > 0) //int objects cannot be null ViewData["ScheduleBRequired"] = true; ``` View: ``` private void Draw() { if ((bool)ViewData["ScheduleBRequired"]){ this._btnScheduleB.Enabled = true; this._validatorScheduleB.Active = true; //required data should be checked clientside with js } } ``` If it is a businessrequirement, that this should be filled, it should be triggered by the presenter. the ui is responsible for following the decisions of the presenter. e.g. to require the ScheduleB or not....
Refactoring an enable/disable button toggle function
[ "", "c#", "refactoring", "" ]
Ive narrowed down to this method but i don't understand why its locking the file. I believe you could use something like ``` using( something) { //do stuff here } ``` But im not sure that would A) solve the issue or B) be the correct way if it did. any ideas? ``` [DllImport("user32.dll", CharSet = CharSet.Auto)]private static extern Int32 SystemParametersInfo(UInt32 action, UInt32 uParam, String vParam, UInt32 winIni); private static readonly UInt32 SPI_SETDESKWALLPAPER = 0x14; private static readonly UInt32 SPIF_UPDATEINIFILE = 0x01; private static readonly UInt32 SPIF_SENDWININICHANGE = 0x02; private void SetWallpaper(string path) { try { Image imgInFile = Image.FromFile(path); imgInFile.Save(SaveFile, ImageFormat.Bmp); SystemParametersInfo(SPI_SETDESKWALLPAPER, 3, SaveFile, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); } catch { MessageBox.Show("error in setting the wallpaper"); } } ``` # Updated code ``` private void SetWallpaper(string path) { if (File.Exists(path)) { Image imgInFile = Image.FromFile(path); try { imgInFile.Save(SaveFile, ImageFormat.Bmp); SystemParametersInfo(SPI_SETDESKWALLPAPER, 3, SaveFile, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); } catch { MessageBox.Show("error in setting the wallpaper"); } finally { imgInFile.Dispose(); } } } ```
From [MSDN](http://msdn.microsoft.com/en-us/library/stf701f5.aspx): "The file remains locked until the Image is disposed." - so yes, this should be fixed by: ``` using (Image imgInFile ...) { ... } ``` (As a side note, I would tighten the try catch to just the .Save() and/or SystemParametersInfo() calls)
Once you pass out of the **using** block, all objects initialized within it are disposed. In your case, the objects will be disposed which will remove the lock on the file. You must manually dispose (either through a **using** statement or by calling *.Dispose()* on the object) any unmanaged calls to either COM or Windows API functions (i.e. when you use interop).
why does this code lock my files?
[ "", "c#", ".net", "file", "locking", "wallpaper", "" ]
I need a javascript bookmark to take the url I have in the clipboard parse out the 2 numbers and create a new url, and add a link to the top of the page, that when clicked adds the url to my bookmark menu. Say I have url's like these ``` http://www.website.com/frontpageeditor.jhtml?sectionID=2844&poolID=6276 ``` ``` javascript:getPoolPageUrl(9800,22713) ``` Then I need to add the numbers to this url ``` javascript:frames['content'].getPoolPageUrl(9800,22713) ``` and then add the url to the top of the frame "content". I have tried forever on this, but I can't figure out it out. **Update** I've put something together, to show you what I need. This one doesn't work though. Any ideas why? ``` var url = window.clipboardData.getData('Text'); var reg = /(\d+)/g; var matches = url.match(reg); //returns ["2844","6276"] var newUrl = "javascript:frames['content'].getPoolPageUrl("+matches[0]+","+matches[1]+")"; var link = document.createElement('a'); link.src = newUrl; frames['content'].document.body.appendChild(link); ``` **Update2** This works. Any changes I can do to make it even better? ``` var url = window.clipboardData.getData('text'); var matches = url.match(/(\d+)/g); var link = frames['content'].document.createElement('a'); link.href = "javascript:frames['content'].getPoolPageUrl("+matches[0]+","+matches[1]+")"; link.innerHTML = document.title; frames['content'].document.body.appendChild(link); ```
Ok, first of all I think you cannot retrieve the text from clipboard from java script, my guess that it would be a major security issue if you can. Let's assume you have the clipboard in a string you can call this function: ``` var url = "http://www.website.com/frontpageeditor.jhtml?sectionID=2844&poolID=6276"; //clip var reg = /(\d+)/g; var matches = url.match(reg); //returns ["2844","6276"] var newUrl = "javascript:frames['content'].getPoolPageUrl("+matches[0]+","+matches[1]+")"; frames['content'].document.getElementById("linkPlaceHolderWhereYouWantToAdd").href=newUrl; ```
You're creating the element in one document, and then appending it to a child located in another document. This doesn't work. You need to create the element in the document that you're going to be adding it to. Also, the a object doesn't have a src member, it uses href. Eg: ``` var link = frames['content'].document.createElement('a'); link.href = newUrl; link.innerHTML = newUrl; frames['content'].document.body.appendChild(link); ``` Do note however, that window.clipboardData is IE-specific code.
Parse and add url from clipboard
[ "", "javascript", "regex", "url", "parsing", "bookmarklet", "" ]
I have a question What happend when I declare a variable inside a method, for example. ``` void myMethod() { Ship myShip = new Ship(); } ``` Where is allocated myShip reference, in stack or in the heap ? I think in stack but I'm confused because I was reading in J2ME Game Programming book "Java classes are instantiated onto the Java heap" All java clases ? Thanks in advance
`myShip` is a reference to a `Ship` object, `myShip` is on the method call stack, which is referred to as "the stack". When a method is called a block of memory is pushed onto the top the stack, that memory block has space for all primitives (int, float, boolean etc) and object references of the method, which includes the method parameters. The heap is where the memory for the actual objects is allocated. So `myShip` is on the stack and the `Ship` object is on the heap. Note each thread has its own stack but share the heap.
Java really does things a bit differently. The *reference* is basically on the stack. The memory for the object is allocated in what passes for the heap. However, the implementation of allocable memory isn't quite like the way the heap is implemented in the C/C++ model. When you create a new object like that, it effectively puts the name into the table of references for that scope. That's much like a pointer to an object in C++. When it goes out of scope, that reference is lost; the allocated memory is no longer referenced, and can be garbage-collected.
Where is allocated variable reference, in stack or in the heap?
[ "", "java", "concurrency", "heap-memory", "stack-memory", "" ]
## Part 1 I want to build a PHP Zend Framework application that users can sign up to use. When they register, I would like the application to create a sub-domain that points to their public page, that serves up content specific to that client. For example: <http://mywebapp.com/username> or <http://username.mywebapp.com> **Update:** ["Using sub-domains as account keys"](http://www.noginn.com/2008/09/03/using-subdomains-as-account-keys/) is a good tutorial that pretty much answered my question on this one. This involves using [`Zend_Controller_Router_Route_Hostname`](http://framework.zend.com/manual/en/zend.controller.router.html#zend.controller.router.routes.hostname). However, I am still wondering... **Question #1:** the tutorial doesn't mention setting up a wildcard sub-domain. Is this necessary in order to achieve this? Is there any way around using a wildcard subdomain? --- ## Part 2 I will also need to offer users the ability to register domain names and point them to their page. So if you were to go to <http://clientdomain.com>, you would be seeing <http://clientname.mywebapp.com>, but you would never be able to tell because the url in the address bar shows <http://client1.com>. Does that make sense? I think the process is called domain masking. I basically want to offer my users free domain masking. **Update:** I've just discovered the world of domain reseller APIs. [OpenSRS](http://opensrs.com/) looks nice. Do you have one to recommend? **Question #2:** How does domain masking work? Can it work with a domain reseller API?
For Part 1 of your question you can implement any of the solutions here - but I am not sure you need a router - you will not offer a different functions for each site - you just want to load up different content based on the URL. We handle this in quite a simple way: 1. In your bootstrap.php you need to grab the server URL 2. Take the URL and strip out the portion after http:// and before .mywebapp.com 3. Lookup this prefix in a database table and load any information you need to about the user or other information to do with this prefix 4. Put an object into Zend\_Config that you can then access from any page with the site details (we call this siteinfo). 5. Modify your controllers or views to respond differently based on siteinfo - ie. change what data they retrieve etc You will need to modify apache to handle this - and the easiest way is to make sure your default domain (the pages that come up when a URL is not recognised) is set to your application. Handling the DNS changes is not that easy - you need to have a DNS server that can handle wildcard replies. **Part 2:** I think you are saying that if I enter the URL <http://grouchal.com> that this would redirect to <http://grouchal.yourwebapp.com>. This would require me to update the existing DNS server entries for grouchal.com so that your server is found. If you want to see a good example of this working in practice you should set-up a google apps for your domain account. I have urls like mail.grouchal.com that once typed in become mail.google.com/a/grouchal.com. This required me to set up the grouchal.com DNS server to point at a google server. The google server then puts a redirect in place to change the url to the one they need. Going back to the solution I proposed above you would modify it so that in addition to checking the prefix for when your domain name is there (ie stripping out grouchal from <http://grouchal.mywebapp.com>) it would also look up alternate domains. So if there is no mywebapp.com in the address then it would look up in the database grouchal.com and then set the siteinfo using that data. Hope this makes sense - the problems you will have will not be in PHP but in setting up your wildcat DNS server and getting your customers to configure their DNS servers correctly. Good luck with the project though.
First, you are right. You don't want multiple instances/installs of your app. Setup multiple Apache virtual hosts to point at the Doc Root. ``` ServerName www.serverOne.com DocumentRoot "/htdocs/myapp/public" SetEnv CONFIG_ENV "serverOne" ServerName www.serverTwo.com DocumentRoot "/htdocs/myapp/public" SetEnv CONFIG_ENV "serverTwo" ``` Put all your base urls, paths, etc in different sections of a Zend\_Config\_Xml file. ``` <?xml version="1.0" standalone="yes"?> <config> <siteOne> <base_url>http://www.siteOne.com</base_url> <image_path>/images/siteOne/</image_path> <database> <host>34.23.34.457</host> <name>siteOne_DB</name> <user>siteOne</user> <pass>**********</pass> </database> </siteOne> <siteTwo> <base_url>http://www.siteTwo.com</base_url> <image_path>/images/siteTwo/</image_path> <database> <host>34.23.34.456</host> <name>siteTwo_DB</name> <user>siteTwo</user> <pass>**********</pass> </database> </siteTwo> </config> ``` Then in your /public/index.php ``` <?php require '../common/config/Bootstrap.php'; $bootstrap = new Bootstrap($_SERVER['CONFIG_ENV']); $bootstrap->runApp(); ?> ``` And in Bootstrap.php's runApp() method: ``` function runApp($env) { $root = realpath(dirname(__FILE__) . '/..'); $config = new Zend_Config_Xml($root . '/config.xml', $env); ``` This will work perfectly with relative links, and it doesn't require any pattern matching :) If you don't have a Bootstrap.php file, you can learn how to create & use on in Manning Press's "Zend Framework In Action" book, available instantly as a PDF download. It helped me through some tough times.
How to route sub-domains to account pages? How does domain masking work?
[ "", "php", "zend-framework", "web-applications", "url-routing", "" ]
I just want to get a quick htaccess redirection. ie: domain.com/subfolderGreen --> domain.com/index.php?folder=subfolderGreen (note that the subfolderGreen actually exists) I've been trying but couldn't get to the regex needed. thanks. a. ADDED: Sorry, i want this to work for any subfolder, not just "subfolderGreen" I'm using RewriteRule ^/([^/]+)/?$ /index.php?folder=$1 [L] but it's not working. any clues?
I would think your example would cause an endless loop since /index.php matches what you are doing. Try this: ``` RewriteRule ^([A-Za-z0-9]+)/?$ /index.php?folder=$1 [L] ``` If you want it to work for all directories that exist, this will probably work as well. ``` RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^(.+)/?$ /index.php?folder=$1 [L] ```
``` RewriteRule ([^/]+)$ index.php?folder=$1 ``` I think that will do the trick. RewriteRule has some confusing issues when used in .htaccess which requires the addition of a RewriteBase. What errors/problems are you seeing? If you want to be sure of how it's redirecting adding a [R] can often help with the debugging. Finally... does the subfolderGreen really exist or not? If it exists that could cause some problems.
htaccess (no redirection) [REWRITEURL] (folder to index.php)
[ "", "php", ".htaccess", "" ]
I'm an emacs user who just started working for a new company where eclipse is the standard. I've tried eclipse, but I want to also experiment with JDEE (I'm coming back to Java after a long hiatus). The major stumbling block so far is getting the indentation to match. Is there an easy way to do this, or am I going to need to dig deeply into the nuts and bolts of emacs indentation? EDIT: sorry for the confusion in this question: I do not want to get Eclipse to mimic emacs, I want emacs to mimic Eclipse. I want to be able to use emacs to modify code without screwing up the indentation that the Eclipse users expect.
You need to customize the indentation in java mode. Take a look [here](http://cc-mode.sourceforge.net/html-manual/Indentation-Engine-Basics.html#Indentation-Engine-Basics), [here](http://cc-mode.sourceforge.net/html-manual/Customizing-Indentation.html#Customizing-Indentation) and [here](http://cc-mode.sourceforge.net/html-manual/Adding-Styles.html#Adding-Styles).
The main difference I found between Eclipse (and IntelliJ) and Emacs default java formatting is that Emacs lines up function arguments continued onto a new line with the previous arguments e.g. emacs does: ``` BigLongJavaStuff.doFoobarToQuux("argument 1", "argument 2"); ``` and Eclipse does: ``` BigLongJavaStuff.doFoobarToQuux("argument 1", "argument 2"); ``` The following added to you ~/.emacs file will make Emacs java-mode do the same: ``` ;; eclipse-java-style is the same as the "java" style (copied from ;; cc-styles.el) with the addition of (arglist-cont-nonempty . ++) to ;; c-offsets-alist to make it more like default Eclipse formatting -- function ;; arguments starting on a new line are indented by 8 characters ;; (++ = 2 x normal offset) rather than lined up with the arguments on the ;; previous line (defconst eclipse-java-style '((c-basic-offset . 4) (c-comment-only-line-offset . (0 . 0)) ;; the following preserves Javadoc starter lines (c-offsets-alist . ((inline-open . 0) (topmost-intro-cont . +) (statement-block-intro . +) (knr-argdecl-intro . 5) (substatement-open . +) (substatement-label . +) (label . +) (statement-case-open . +) (statement-cont . +) (arglist-intro . c-lineup-arglist-intro-after-paren) (arglist-close . c-lineup-arglist) (access-label . 0) (inher-cont . c-lineup-java-inher) (func-decl-cont . c-lineup-java-throws) (arglist-cont-nonempty . ++) ))) "Eclipse Java Programming Style") (c-add-style "ECLIPSE" eclipse-java-style) (customize-set-variable 'c-default-style (quote ((java-mode . "eclipse") (awk-mode . "awk") (other . "gnu")))) ```
Eclipse indentation on Emacs
[ "", "java", "eclipse", "emacs", "" ]
I started with a question, and in typing the question, found the answer, but instead of deleting, I thought it might be helpful to A) get confirmation, and B) help others. If I have an event, and several places in the application add listeners, what is the best way to remove all listeners at once? For example, I can ... ``` myPage.OnPageOpened += OpenPage; ``` and later in my code ... ``` myPage.OnPageOpened -= OpenPage; ``` But what if I have unknown 3rd party subscribers and I want to press a magic Reset button that clears everything and starts from scratch? You can use += and -= operators anywhere against the EventHandler, because the operator overloads are public. The = overloaded operator is private it can only be called in the defining class. So in the defining class I can use this to clear my EventHandler. ``` OnPageOpened = null; ``` And to expose that functionality, I could ... ``` public void ClearPageOpenedEvents() { OnPageOpened = null; } ``` Is that correct?
Yes, you are correct. The reason for this is that the compiler creates a `private` `delegate` object under the covers, like this: ``` private EventHandler pageOpened; public EventHandler PageOpened { add { pageOpened += value; } remove { pageOpened -= value; } } ``` Inside your class, you have a reference to the private `delegate` instance, so that's why you can do the assignment. You definitely want to expose a method to clear the targets if that's functionality you need; you don't want to expose the `delegate` itself.
That's the way to do it, but how does something outside the class know that the class should drop all its event listeners? What if someone extending/using your code is expecting that event on an ongoing basis?
How does an EventHandler know to allow = operator only in defining class?
[ "", "c#", "event-handling", "" ]
I have a Filter Method in my User Class, that takes in a list of Users and a string of search terms. Currently, the FindAll predicate splits the terms on spaces then returns a match if any of the searchable properties contain any part of the terms. ``` public static List<User> FilterBySearchTerms( List<User> usersToFilter, string searchTerms, bool searchEmailText ) { return usersToFilter.FindAll( user => { // Convert to lower case for better comparison, trim white space and then split on spaces to search for all terms string[] terms = searchTerms.ToLower().Trim().Split( ' ' ); foreach ( string term in terms ) { // TODO: Is this any quicker than two separate ifs? if ( (searchEmailText && user.Email.ToLower().Contains( term )) || ( user.FirstName.ToLower().Contains( term ) || user.Surname.ToLower().Contains( term ) || user.Position.ToLower().Contains( term ) || user.Company.ToLower().Contains( term ) || user.Office.ToLower().Contains( term ) || user.Title.ToLower().Contains( term ) ) ) return true; // Search UserID by encoded UserInviteID else { int encodedID; if ( int.TryParse( term, out encodedID ) ) { User fromInvite = GetByEncodedUserInviteID( encodedID ); if ( fromInvite != null && fromInvite.ID.HasValue && fromInvite.ID.Value == user.ID ) return true; } } } return false; } ); } ``` I have received a new requirement so that the ordering is now important. For example, a search for 'Mr Smith' should have Mr Adam Smith ahead of Mrs Eve Smith, which might make my use of Contains inappropriate. However, the most important thing is the number of property/part of term matches. I'm thinking I could have a couple of counters to keep track of complete term matches and partial matches, then order by those two. I'm also open to suggestions on how the Filter method can be improved - perhaps using something else entirely.
Here's a LINQ-based solution. It will be a bit more of a pain if you're not using .NET 3.5, I'm afraid. It separates out the details of the matching from the query itself, for clarity. You'll need to create a `LowerCaseUser` method which returns a `User` object with all the properties lower-cased - it makes more sense to do that once than for every search term. If you can put that and `UserMatches` into the `User` class, so much the better. Anyway, here's the code. ``` public static List<User> FilterBySearchTerms (List<User> usersToFilter, string searchTerms, bool searchEmailText) { // Just split the search terms once, rather than for each user string[] terms = searchTerms.ToLower().Trim().Split(' '); return (from user in usersToFilter let lowerUser = LowerCaseUser(user) let matchCount = terms.Count(term => UserMatches(lowerUser, term)) where matchCount != 0 orderby matchCount descending select user).ToList(); } private static bool UserMatches(User user, string term, bool searchEmailText) { if ((searchEmailText && user.Email.Contains(term)) || user.FirstName.Contains(term) || user.Surname.Contains(term) || user.Position.Contains(term) || user.Company.Contains(term) || user.Office.Contains(term) || user.Title.Contains(term)) { return true; } int encodedID; if (int.TryParse(term, out encodedID)) { User fromInvite = GetByEncodedUserInviteID(encodedID); // Let the compiler handle the null/non-null comparison if (fromInvite != null && fromInvite.ID == user.ID) { return true; } } return false; } ```
The first thing, I'd say that you need to do, is to break the large lazily evaluated or conditions into separate conditions. Otherwise you're never going to resolve how many matches you're actually getting. After this you'll probably need a score for each user which reflects how well the search terms match it. I'm also assuming you are able to use LINQ here as you are already using lambda expressions. ``` class ScoredUser { public User User { get; set; } public int Score { get; set; } } public static List<User> FilterBySearchTerms(List<User> usersToFilter, string searchTerms, bool searchEmailText) { // Convert to lower case for better comparison, trim white space and then split on spaces to search for all terms string[] terms = searchTerms.ToLower().Trim().Split(' '); // Run a select statement to user list which converts them to // a scored object. return usersToFilter.Select(user => { ScoredUser scoredUser = new ScoredUser() { User = user, Score = 0 }; foreach (string term in terms) { if (searchEmailText && user.Email.ToLower().Contains(term)) scoredUser.Score++; if (user.FirstName.ToLower().Contains(term)) scoredUser.Score++; if (user.Surname.ToLower().Contains(term)) scoredUser.Score++; // etc. } return scoredUser; // Select all scored users with score greater than 0, order by score and select the users. }).Where(su => su.Score > 0).OrderByDescending(su => su.Score).Select(su => su.User).ToList(); } ``` Having the method return a scored customer also allows you easily tweak the scoring balances later on. Say you want a matching first name matter more than a matching company for example.
How can I order a list by number of matches after filtering by Search Terms in C#?
[ "", "c#", "search", "list", "filter", "" ]
I'm writing a simple VS add-in and would like to programmatically invoke the "Document Format" option (under Edit) within code. Google isn't being very friendly to me today....
``` Command cmd = _applicationObject.Commands.Item("Edit.FormatDocument", -1); object dummy = null; _applicationObject.Commands.Raise(cmd.Guid, cmd.ID, ref dummy, ref dummy); ```
If you have a reference to your document (of type Window), and you have a reference to the \_DTE object, you can call it like this: ``` myDocument.Activate(); myDTE.ExecuteCommand("Edit.FormatDocument", string.Empty); ``` Most of the time, you can get a reference to the \_DTE object from the parameters passed into your add-in.
How do you call "Document Format" programmatically from C#?
[ "", "c#", "visual-studio", "add-in", "" ]
I'm using Eclipse Ganymede to create a web application, but the project's currently just a standard Java project. I want to convert it to a Dynamic Web Project and I need a hand in doing that. I've had suggestions given to me about editing the .project file, but when I restart Eclipse it refuses to open the project claiming the file is corrupt. There's also no facet management options in the project properties. Any suggestions?
Well. I'll *tell* you why, folks. It's because a lot of these guides miss out some fundamental things. 1. Yes, you need to change the .project file to add some missing natures and builders (create a new Dynamic Web Project and examine the created .project file to see what's missing). 2. You also need to add things to the .settings folder. It'll be missing two or three files, one of which is a key xml file. They're all required for it to understand the new natures you've given it. Huzzah for computers.
Although this question is already answered I'd like to say that I managed to convert my project into web project by changing project facets Properties->Project Facet and just checked Dynamic Web Module
Converting a Java Project to a Dynamic Web Project
[ "", "java", "eclipse", "ganymede", "" ]
I need to hold a representation of a document in memory, and am looking for the most efficient way to do this. Assumptions * The documents can be pretty large, up to 100MB. * More often than not the document will remain unchanged - (i.e. I don't want to do unnecessary up front processing). * Changes will typically be quite close to each other in the document (i.e. as the user types). * It should be possible to apply changes fast (without copying the whole document) * Changes will be applied in terms of offsets and new/deleted text (not as line/col). * To work in C# Current considerations * Storing the data as a string. Easy to code, fast to set, very slow to update. * Array of Lines, moderatly easy to code, slower to set (as we have to parse the string into lines), faster to update (as we can insert remove lines easily, but finding offsets requires summing line lengths). There must be a load of standard algorithms for this kind of thing (it's not a million miles of disk allocation and fragmentation). Thanks for your thoughts.
I would suggest to break the file into blocks. All blocks have the same length when you load them, but the length of each block might change if the user edits this blocks. This avoids moving 100 megabyte of data if the user inserts one byte in the front. To manage the blocks, just but them - together with the offset of each block - into a list. If the user modifies a blocks length you must only update the offsets of the blocks after this one. To find an offset, you can use binary search. **File size:** 100 MiB **Block Size:** 16 kiB **Blocks: 6400** **Finding a offset using binary search (worst case):** 13 steps **Modifying a block (worst case):** copy 16384 byte data and update 6400 block offsets **Modifying a block (average case):** copy 8192 byte data and update 3200 block offsets 16 kiB block size is just a random example - you can balance the costs of the operations by choosing the block size, maybe based on the file size and the probability of operations. Doing some simple math will yield the optimal block size. Loading will be quite fast, because you load fixed sized blocks, and saving should perform well, too, because you will have to write a few thousand blocks and not millions of single lines. You can optimize loading by loading blocks only on demand and you can optimize saving by only saving all blocks that changed (content or offset). Finally the implementation will not be to hard, too. You could just use the `StringBuilder` class to represent a block. But this solution will not work well for very long lines with lengths comparable to the block size or larger because you will have to load many blocks and display only a small parts with the rest being to the left or right of the window. I assume you will have to use a two dimensional partitioning model in this case.
Good Math, Bad Math wrote an excellent [article about ropes and gap buffer](http://scienceblogs.com/goodmath/2009/02/gap_buffers_or_why_bother_with_1.php)s a while ago that details the standard methods for representing text files in a text editor, and even compares them for simplicity of implementation and performance. In a nutshell: a gap buffer - a large character array with an empty section immediately after the current position of the cursor - is your simplest and best bet.
Best approach to holding large editable documents in memory
[ "", "c#", "algorithm", "data-structures", "string", "document", "" ]
I have this exported file of some weird (standard for this industry!) format, which I need to import into our Database. The file basically looks like this: ``` DATRKAKT-START KAKT_LKZ "D" KAKT_DAT_STAMM "1042665" DATRKAIB-START KAIB_AZ "18831025" KAIB_STATUS_FM 2 KAIB_KZ_WAE "E" DATRKAIB-END DATRKARP-START KARP_MELD "831025" KARP_ST_MELD "G" DATRKARP-END ... DATRKAKT-END ``` There are 56 sections with a total of 1963 different rows, so I'm really not into creating 56 classes with 1963 properties... How would you handle this file so that you can access some property like it were an object? ``` Datrkaib.Kaib_Status_Fm Datrkarp.karp_St_Meld ```
Unless your programming language lets you add methods to classes at runtime or lets classes respond to calls to undefined methods, there's no way you can do this. The thing is, even if C# did let you do this, you would lose type safety and Intellisense help anyway (presumably among the reasons for wanting it to work like that), so why not just go ahead and read it into some data structure? My inclination would be a hash which can contain values or other hashes, so you'd get calls like (VB): ``` Datrkakt("Lkz") Datrkakt("Dat_Stam") Datrkakt("Kaib")("Az") Datrkakt("Kaib")("Status_Fm") ``` Or if you know all the data items are uniquely named as in your example, just use one hash: ``` Datr("Kakt_Lkz") Datr("Kakt_Dat_Stam") Datr("Kaib_Az") Datr("Kaib_Status_Fm") ``` You can get back Intellisense help by creating an enum of all the data item names and getting: ``` Datr(DatrItem.KAKT_LKZ) Datr(DatrIrem.KAIB_STATUS_FM) ```
It looks like structured data - I'd run search and replace and convert it to a simple xml. and then import. The if you want to generate a code file off of it - consider [codesmith](http://www.codesmithtools.com/) - I think it can do this.
Import textfile with weird format in C#
[ "", "c#", ".net", "import", "" ]
[Duplicate](https://stackoverflow.com/questions/263151/lambdas-and-the-ternary-operator-weird-issue) I can do this: ``` Func<CategorySummary, decimal> orderByFunc; if (orderBy == OrderProductsByProperty.Speed) orderByFunc = x => x.Speed; else orderByFunc = x => x.Price; ``` Why can't I do this: ``` Func<CategorySummary, decimal> orderByFunc = (orderBy == OrderProductsByProperty.Speed) ? x => x.Speed : x => x.Price; ```
The 'type inference' on the conditional operator is not quite good enough, I get a message like > Type of conditional expression cannot > be determined because there is no > implicit conversion between 'lambda > expression' and 'lambda expression' you can always just be explicit on the right-hand-side, a la ``` var o = true ? new Func<int,int>(x => 0) : new Func<int,int>(x => 1); ``` In any case it's just a minor annoyance regarding how the types of lambdas, type inference, and the conditional operator interact.
Just cast the lambda's to `Func<CategorySummary, decimal>` and it will work
C# Func and Conditional Operator
[ "", "c#", "" ]
I have a String which contains XML nodes within it, and am seeking to use DOM parsing to process this string to extract node values and store them in local variables. The XML which is stored in a String variable: ``` <carGarage> <car> <make>Chrysler</make> <color>Red</color> </car> <car> <make>Musano</make> <color>Blue</color> </car> </carGarage> ``` My Java class where I want to extract the XML values and store them in the local attributes: ``` public class CarGarage { String make, color; public void setMake(String make) { this.make = make; } public void setColor(String color) { this.color = color; } public void DOMparsingMethod(Node thisNode) { int typeOfNode = thisNode.getNodeType(); ... } } ``` What is the best way to approach this? I have looked at StringBufferInputStream but that is deprecated. I am truly quite lost. Thankyou, Lucas.
Look at using [DocumentBuilder](http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/DocumentBuilder.html) to parse from any kind input stream. Here's an [example](http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html) that reads to a class like yours from a file.
There are lots of object-to-xml binding libraries out there which do exactly what you want, but they tend to be rather bulky tools. For this simple example, handling the dom yourself makes sense. justinhj's suggestion of the built-in java libraries for this is a good start, although this sometimes gets ugly too, since the jdk doesn't usually provide you with an xml parser, requiring you to plug in your own magically behind the scenes. I tend to prefer [jdom](http://www.jdom.org/) for this sort of thing. It's effectively the same as the DocumentBuilder route, but similar and only partly compatible.
Most effective way to process a string containing XML, in JAVA
[ "", "java", "xml", "jsp", "dom", "javabeans", "" ]
I have built UI, its like a search engine for BioProcess/Disease--> Genes. e.g., User can query: "Stem Cells" or "brain tumor"and in result it will give 50 to 5000 GeneIDs (essentially those are Numbers representing a uniqe Gene at NCBI database) . Its free, you can try at : <http://proteogenomics.musc.edu/genemesh/> Now, the problem is I am liking those GeneIDs to a NCBI site at once. For upto 200 or 400 GeneIDs I can get result fine. But for more than 500 GeneIDs I can get "URI TOO LARGE" error or somehow NCBI website can not accept huge query. I am trying to resolve this problem. Can Javascript, OnClick write a file in UNIX /tmp file? or is there any better solution to this? Any help/guidelines are great at this point... thank you so much in advance, Saurin URL too LONG: <http://view.ncbi.nlm.nih.gov/gene/30980,31208,31442,31789,32083,32855,33156,33392,33498,34309,35197,35974,36057,38545,38701,42945,43162,43256,43288,43739,44900,45339,45775,3772082,260437,393632,406845,379537,379620,399306,100037057,100037058,100037249,10,40,43,60,104,133,174,182,185,186,187,197,207,208,210,238,240,269,284,285,317,324,328,332,335,351,355,356,358,361,366,379,387,388,396,429,462,466,472,482,558,567,573,575,576,577,581,595,596,598,604,648,650,664,672,673,675,706,712,754,761,768,771,800,836,841,842,847,857,860,875,885,889,890,891,902,960,970,978,983,999,1000,1018,1019,1021,1025,1026,1027,1029,1030,1031,1051,1082,1111,1116,1124,1131,1152,1231,1234,1272,1282,1284,1285,1286,1287,1288,1316,1432,1457,1459,1462,1464,1471,1474,1485,1490,1493,1499,1508,1512,1520,1543,1545,1571,1594,1600,1605,1612,1620,1622,1630,1633,1638,1641,1643,1649,1728,1755,1756,1803,1809,1814,1839,1854,1869,1909,1910,1942,1950,1956,1969,2012,2013,2014,2019,2020,2022,2034,2035,2044,2045,2046,2048,2050,2051,2052,2064,2066,2067,2068,2071,2100,2149,2166,2173,2246,2247,2250,2251,2254,2260,2263,2264,2272,2289,2290,2305,2308,2309,2321,2335,2475,2542,2547,2574,2579,2621,2627,2670,2734,2735,2736,2737,2738,2740,2849,2890,2896,2901,2908,2925,2932,2936,2939,2944,2947,2950,2952,2956,3073,3074,3082,3090,3091,3104,3105,3106,3115,3122,3123,3146,3161,3162,3181,3191,3215,3240,3265,3309,3315,3324,3371,3373,3383,3384,3397,3398,3417,3479,3480,3481,3482,3485,3486,3487,3491,3553,3558,3561,3565,3566,3569,3574,3575,3596,3597,3598,3603,3611,3621,3630,3632,3645,3672,3685,3688,3717,3732,3738,3741,3766,3785,3791,3814,3815,3845,3897,3910,3912,3913,3915,3918,3925,3945,3956,3958,3981,3987,4035,4087,4088,4089,4133,4137,4145,4147,4152,4155,4172,4175,4192,4193,4194,4241,4255,4267,4288,4292,4303,4312,4313,4314,4316,4318,4320,4321,4323,4327,4350,4436,4440,4524,4548,4549,4552,4574,4601,4609,4654,4684,4691,4735,4745,4763,4771,4790,4804,4807,4808,4829,4830,4843,4851,4856,4893,4907,4914,4915,4916,4950,4978,4982,5015,5028,5030,5054,5080,5111,5118,5154,5155,5156,5159,5178,5241,5243,5266,5274,5276,5290,5294,5295,5328,5329,5334,5340,5395,5444,5468,5536,5538,5563,5566,5578,5579,5580,5581,5583,5584,5591,5594,5595,5599,5602,5629,5653,5663,5702,5708,5713,5725,5727,5728,5730,5743,5745,5747,5764,5781,5803,5805,5834,5835,5879,5880,5881,5888,5894,5898,5899,5900,5915,5921,5925,5934,5970,5978,5981,5992,6048,6091,6118,6165,6195,6275,6278,6284,6347,6382,6387,6416,6464,6469,6490,6502,6506,6507,6513,6598,6606,6608,6622,6647,6648,6649,6657,6659,6660,6662,6663,6664,6667,6670,6678,6695,6697,6714,6717,6770,6772,6774,6790,6853,6855,6863,6892,6900,6948,7012,7013,7015,7018,7020,7025,7040,7042,7054,7057,7076,7078,7105,7124,7153,7157,7161,7168,7175,7185,7186,7248,7249,7258,7262,7276,7277,7283,7298,7422,7428,7431,7442,7447,7468,7474,7490,7508,7515,7517,7518,7520,7525,7545,7799,7849,7852,7980,8028,8038,8061,8089,8140,8190,8301,8372,8484,8507,8577,8605,8650,8678,8682,8692,8718,8737,8741,8742,8743,8745,8754,8771,8772,8788,8795,8797,8811,8828,8829,8841,8842,8848,8851,8862,8871,8877,8928,8930,9077,9100,9113,9141,9148,9156,9173,9211,9212,9232,9334,9353,9423,9429,9444,9445,9447,9459,9507,9518,9535,9545,9588,9681,9806,9833,9844,9961,10036,10135,10209,10215,10313,10362,10371,10381,10401,10472,10512,10530,10572,10620,10630,10642,10743,10763,10776,10855,10893,10991,11009,11010,11013,11065,11093,11095,11096,11141,11156,11162,11186,11191,11200,11235,11284,22865,22933,22943,23136,23152,23162,23209,23261,23308,23336,23435,23469,23627,23654,23705,25776,25792,25855,26013,26038,26050,26136,26256,26471,26524,27122,28514,29103,29108,29126,29997,29998,30001,50618,50859,50943,51050,51147,51199,51213,51230,51305,51330,51335,51438,51637,51668,51747,51763,53358,53615,53616,54106,54828,55210,55294,55553,55717,55752,55760,55859,56647,56920,57124,57142,57447,57448,57670,60672,63827,64101,64386,64710,64805,65065,79659,79682,79944,80309,80332,80381,80781,81557,83483,83605,83667,83858,84148,84189,84280,84504,84525,84631,84654,84707,84708,91419,92140,112755,114798,116448,116986,121227,129787,139065,140885,146691,146956,160728,162979,163732,200895,253260,253738,259266,284217,284459,286527,338030,342945,375790,399473,406907,406991,407043,646555,728239,100133941,403412,396562,396783,751862,100125840,100125841,282862,100008679,11539,11545,11601,11622,11629,11651,11731,11783,11789,11799,11829,11920,11932,12028,12035,12140,12151,12211,12307,12308,12344,12389,12390,12505,12519,12554,12575,12578,12606,12767,12945,13003,13051,13176,13193,13197,13555,13730,13731,13732,13846,13866,14080,14102,14164,14254,14360,14397,14580,14609,14632,14633,14634,14714,14751,14825,14829,14910,15160,15218,15251,15413,15442,15529,15901,16153,16483,16542,16653,16765,16847,17125,17196,17246,17390,17395,17869,17920,18008,18015,18016,18040,18071,18072,18125,18128,18133,18208,18386,18507,18591,18595,18616,18708,18787,18792,18793,18996,18997,19090,19118,19122,19206,19211,19227,19247,19373,19377,19531,19557,19645,19650,19651,20423,20511,20713,20720,20848,20849,20852,20981,21333,21367,21375,21687,21826,21846,21948,22059,22339,22596,22612,23796,26362,26413,26417,26434,30878,30957,50490,50913,50914,54725,55992,56458,56717,60609,64930,66395,66471,67903,71722,74318,75409,76965,79401,81897,83485,107831,110105,110122,111364,111519,170756,192198,210933,211323,216225,218397,230775,232286,239250,245446,245450,269608,386750,24248,24329,24338,24387,24392,24464,24482,24498,24615,24835,24842,24929,25026,25112,25124,25125,25163,25240,25264,25265,25404,25408,25425,25445,25491,25496,25550,25589,25617,25621,25647,25712,29290,29386,29527,29543,29597,29665,50557,50577,50658,50689,54250,54251,59086,64157,64803,65054,81649,81651,81686,83425,83476,83497,83785,84114,84353,84357,84394,84577,84578,89804,89805,89807,114122,114851,116554,116590,116996,117273,170568,192248,292994,297893,306464,308435,338474,360457,362317,369119,2828259,155871,156110,908122,4981003,4981004,4981005,4981006,4981007,4981008,4981009,4981010,4981011,4981012,4981013,4981014,4981015,4981016,4981017,4981018,4981019,4981020,4981021,4981022,4981023,4981024,4981025,4981026,4981027,4981028,4981029,4981030,4981031,4981032,4981033,4981034,4981035,4981036,4981037,4981038,4981039,4981040,4981041,4981042,4981043,4981045,4981046,4981047,4981048,4981049,4981050,4981051,4981052,4981053,4981054,4981055,4981056,4981057,4981058,4981059,4981060,4981061,4981062,4981063,4981064,4981065,4981066,4981067,4981068,4981069,4981070,4981071,4981072,4981073,4981074,4981075,4981076,4981077,4981078,4981079,4981080,4981081,4981082,4981083,4981084,4981085,4981086,4981087,4981088,4981089,4981090,4981091,4981092,4981093,4981094,4981095,4981096,4981097,4981098,4981099,4981100,4981101,4981102,4981103,4981104,4981105,4981106,4981107,4981108,4981109,4981110,4981111,4981112,4981113,4981115,4981116,4981117,4981118,4981119,4981120,4981121,4981125,4981126,4981128,4981129,4981130,4981131,4981132,4981133,4981134,4981135,4981136,4981137,4981138,4981139,4981140,4981141,4981142,4981143,4981144,4981145,4981146,4981147,4981148,4981149,4981150,4981151,4981152,4981153,4981154,4981155,4981157,4981158,4981159,4981160,4981161,4981162,4981163,4981164,4981165,4981166,4981167,4981168,4981169,4981170,4981171,4981172,4981173,4981174,4981175,4981176,4981177,4981178,4981179,4981180,4981181,4981182,4981183,4981184,4981185,4981186,4981187,4981188,4981189,4981190,4981191,4981192,4981193,4981194,4981195,4981196,4981197,4981198,4981199,4981200,4981201,4981202,4981203,4981204,4981205,4981206,4981207,4981208,4981209,4981210,4981211,4981212,4981213,4981214,4981215,4981216,4981217,4981218,4981219,4981220,4981221,4981222,4981223,4981224,4981225,4981226,4981227,4981228,4981229,4981230,4981231,4981232,4981233,4981234,4981235,4981236,4981237,4981238,4981239,4981240,4981241,4981242,4981243,4981244,4981245,4981246,4981247,4981248,4981249,4981250,4981251,4981252,4981253,4981254,4981255,4981256,4981257,4981258,4981259,4981260,4981261,4981262,4981263,4981264,4981265,4981266,4981267,4981268,4981269,4981270,4981271,944996,946069>
If you cannot use a cookie, the url is too long. Write the data to a temp table in a database. Once the data is saved out, send back an ID, pass that via the URL. You can do this via a web service call without too much of an issue. Also, put a timestamp on the table, prune out old data after a set period of time.
You could write them to a cookie, sort of the equivalent of a tmp file. A much better solution would be to POST your data instead of using a GET.
how to resolve VERY LARGE URL problem for hyperlink...with jQuery or Javascript calling any perl,php etc. script on back
[ "", "javascript", "url", "hyperlink", "ncbi", "" ]
I have implemented this code, but fail at compilation (VC2008 Express Ed.) : Now all code is here. ``` #include <stdio.h> #include <vector> #include <string> #include <hash_map> using namespace std; using namespace stdext; typedef vector type_key; int main(int argc, char* argv[]) { type_key key; hash_map<type_key, string> map_segment; hash_map<type_key, string>::iterator iter_map_segment; iter_map_segment = map_segment.find(key); return 0; } ``` using unordered\_map also occurs the same error too. but replacing the container by a map error does not occur. What can be done to correct? Thank you. [EDITED] Error info : ``` ------ Build started: Project: map_key_test, Configuration: Debug Win32 ------ Compiling... map_key_test.cpp c:\program files\microsoft visual studio 9.0\vc\include\xhash(75) : error C2440: 'type cast' : cannot convert from 'const type_key' to 'size_t' No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called c:\program files\microsoft visual studio 9.0\vc\include\xhash(128) : see reference to function template instantiation 'size_t stdext::hash_value<_Kty>(const _Kty &)' being compiled with [ _Kty=type_key ] c:\program files\microsoft visual studio 9.0\vc\include\xhash(127) : while compiling class template member function 'size_t stdext::hash_compare<_Kty,_Pr>::operator ()(const _Kty &) const' with [ _Kty=type_key, _Pr=std::less<type_key> ] c:\program files\microsoft visual studio 9.0\vc\include\hash_map(78) : see reference to class template instantiation 'stdext::hash_compare<_Kty,_Pr>' being compiled with [ _Kty=type_key, _Pr=std::less<type_key> ] c:\program files\microsoft visual studio 9.0\vc\include\xhash(191) : see reference to class template instantiation 'stdext::_Hmap_traits<_Kty,_Ty,_Tr,_Alloc,_Mfl>' being compiled with [ _Kty=type_key, _Ty=std::string, _Tr=stdext::hash_compare<type_key,std::less<type_key>>, _Alloc=std::allocator<std::pair<const type_key,std::string>>, _Mfl=false ] c:\program files\microsoft visual studio 9.0\vc\include\hash_map(88) : see reference to class template instantiation 'stdext::_Hash<_Traits>' being compiled with [ _Traits=stdext::_Hmap_traits<type_key,std::string,stdext::hash_compare<type_key,std::less<type_key>>,std::allocator<std::pair<const type_key,std::string>>,false> ] c:\users\salamon\documents\visual studio 2008\projects\map_key_test\map_key_test.cpp(17) : see reference to class template instantiation 'stdext::hash_map<_Kty,_Ty>' being compiled with [ _Kty=type_key, _Ty=std::string ] Build log was saved at "file://c:\Users\Salamon\Documents\Visual Studio 2008\Projects\map_key_test\Debug\BuildLog.htm" map_key_test - 1 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== ``` [EDITED] Complete solution : ``` #include <stdio.h> #include <vector> #include <string> #include <hash_map> using namespace std; using namespace stdext; class Vector : public vector<int> { public: operator size_t() const { return (*this).size(); }; }; typedef Vector type_key; struct less_vector { bool operator()(const Vector & x, const Vector & y) const { if ( x != y ) return true; return false; } }; struct greater_vector { bool operator()(const Vector & x, const Vector & y) const { if ( x == y ) return true; return false; } }; int main(int argc, char* argv[]) { Vector key; string str; hash_map<Vector, string, hash_compare <Vector, less_vector > > map_segment; hash_map<Vector, string, hash_compare <Vector, greater_vector > >::iterator iter_map_segment; // key.push_back(0); key.push_back(1); key.push_back(2); str = "012"; map_segment [key] = str; // key.clear(); key.push_back(1); key.push_back(0); key.push_back(2); str = "102"; map_segment [key] = str; // key.clear(); key.push_back(2); key.push_back(1); key.push_back(0); str = "210"; map_segment [key] = str; // key.clear(); key.push_back(1); key.push_back(0); key.push_back(2); iter_map_segment = map_segment.find(key); return 0; } ```
First, make sure that the header that you include really exists on your installation. Second, hash\_map is in the `stdext` namespace, make sure you make this name visible via specifying it explicitly as `stdext::hash_map`, or via a `using` directive. Third, where are the template arguments for your hash\_map in your code? I only see `hash_map` and not `hash_map<vector<int>,string>`. Fourth, I'm not sure if std::vector can be used as a hash key for a hash map just like this. You need to define a hash function for your key (via implementing a `hash_compare` function object and passing it to the `hash_map` as third template parameter). Anyway storing these vectors by value is hardly a good idea, instead you should probably consider using pointers to these vectors as keys.
Even if it works, I smell fish... Under what circumstance do you want to use a vector-of-ints as a key to retrieve a string attribute from a hash-map? Sounds like poor/no design to me... just think about the expense of calculating all those hashCodes for a start.
fail using hash_map<vector<int>,string>, why?
[ "", "c++", "templates", "stl", "" ]
Sorry, I know this is programming 101, but I can't find any good documentation... I have an array, and I want to cast each member as an object and then call them by the name assigned (this would be so much simpler if javascript allowed for non-number index values). For instance: ``` var things = ['chair', 'tv', 'bed']; var costs = ['10', '100', '75']; for (var i = 0; i < things.length; i++) { thing.name = things[i]; thing.cost = costs[i]; } alert(thing.name('tv').cost); ``` Obviously this isn't the way to do this, but the desired outcome would be an alert that said "100". I have gotten as far as creating a class that has a method called name which points back to the main object, like so: ``` function thing(name, cost) { function name(thename) { return this; } this.thingname = name; this.name = name; this.cost = cost; } ``` But this still requires that each object has a unique variable name, which goes against the whole point. What I want is to simply throw all of my array into some generic class and call the values I need by the name. I know this is probably way to easy to ask here, but I'm stuck! Thanks.
Why not use objects? ``` var things = { chair: 10, tv: 100, bed: 75 }; alert(things.chair); // 10 alert(things['tv']); // 100 ```
``` var stuff = { chair: 10, tv: 100, bed: 75 }; alert(stuff.chair); // alerts '10' alert(stuff['chair']); // alerts '10' stuff.house = 100000; stuff['car'] = 10000; alert(stuff['house']); // you get the picture... alert(stuff.car); ```
How to create a method for an array class?
[ "", "javascript", "arrays", "oop", "object", "methods", "" ]
I'm trying to change a Button's Click property/event when a DataTrigger is triggered but I'm not sure if this is the best method to do it. In fact, it won't even compile :) What I have looks like this: ``` <Style TargetType="{x:Type Button}"> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=ObjectTreeView, Path=SelectedItem.Replaceable}" Value="False"> <Setter Property="Content" Value="Add" /> <Setter Property="Button.Click" Value="AddObject_Click" /> </DataTrigger> <DataTrigger Binding="{Binding ElementName=ObjectTreeView, Path=SelectedItem.Replaceable}" Value="True"> <Setter Property="Content" Value="Replace" /> <Setter Property="Button.Click" Value="ReplaceObject_Click" /> </DataTrigger> </Style.Triggers> </Style> ``` Compiling gives me an error message saying "Cannot find the Style Property 'Click' on the type 'System.Windows.Controls.Button'" Any suggestions? If this not possible, what alternatives are there? Thanks! Edit: I thought I found the solution which was to use an EventSetter, but EventSetters aren't supported inside Triggers. What I thought would've worked was: ``` <EventSetter Event="Button.Click" Handlder="AddObject_Click" /> ``` But like I said, this is supported at all.
Click isn't a property, it's an event. Buttons have a property IsPressed that becomes true when the button is being pressed. You could try using that.
Wouldn't it be easier to just have one click event and in that event, an if statement based on your DataTrigger?
Changing a Button's Click event based on a DataTrigger
[ "", "c#", "wpf", "button", "datatrigger", "" ]
I have a limited c++ background and I would like to edit the registry. For example, I want to grab the value of `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\NoDriveTypeAutoRun` and check to see if 0x20 is in it, and then if it is, subtract 0x20 from it's value and write it back (and kill and restart explorer.exe but I can figure that out on my own). How would you do it?
* Open the registry : [RegOpenKeyEx](http://msdn.microsoft.com/en-us/library/ms724897(VS.85).aspx) * Query the value : [RegQueryValueEx](http://msdn.microsoft.com/en-us/library/ms724911(VS.85).aspx) /\* do something with value\*/ * Set the value back : [RegSetValueEx](http://msdn.microsoft.com/en-us/library/ms724923(VS.85).aspx) * close the registry : [RegCloseKey](http://msdn.microsoft.com/en-us/library/ms724837(VS.85).aspx)
Use RegOpenKeyEx(), RegGetValue(), RegSetKeyValue(), and don't forget to RegCloseKey() Here's a link to the reference: <http://msdn.microsoft.com/en-us/library/ms724875(VS.85).aspx> If you use ATL, it has a easy-to-use class CRegKey (a wrapper around the above functions).
Using C++ to edit the registry
[ "", "c++", "windows", "registry", "hex", "" ]
I am simply looking for a way of using drag and drop without jquery or any other library. If a dragged object is dropped on another element the later element should start an event (in FF - better would be browser independent). I know that drag and drop for JavaScript was discussed sometimes before but the previous postings didn't help me. Although I found some examples it is not clear to me if there is a "drop" or "dragdrop" events exist but these things don't work: ``` <p ondrop='alert("It worked");'>Text</p> <p ondragdrop='alert("It worked");'>Text</p> ``` How could this be done? Many thanks in advance.
I agree with the other answers. A library will save you a lot of time and headache. This is coming from someone who just recently created a drag-and-drop control from scratch. If you insist though this is what you'll need to do: 1. Bind a onmousedown event to the div you want to drag (div.onmousedown). 2. Change the div's position style to absolute (div.style.position = 'absolute') 3. Begin capturing mouse movement (document.onmousemove). 4. On mouse move update the div's position (div.style.top|left = '[location]px') 5. On the div's onmouseup event (or the document's) unbind all the handlers and do any other cleanup (null out position changes, etc). Some problems a library will probably solve: 1. While dragging you will select text on the page (looks ugly). 2. Binding to events is different between browsers. 3. You have to calculate the size of the element being dragged if you want to show placeholders and to make it not "pop" when you begin dragging the control (since changing to absolute positioning will remove the element from flow). 4. You will probably want your dragged element to move fluidly so you will have to store some mouse offset when selecting the element or automatically center the element to the mouse. 5. If you want to drag an item in a list you'll have to write a ton more custom code for that list to accept the dragged item. 6. You'll have to take into consideration dragging when the window is scrolled and possibly dragging inside other elements that are positioned strangely.
Hmm. It's probably not that simple that you'd want to do it yourself, but I would look at Peter Michaux's FORK Javascript [drag and drop library](http://forkjavascript.org/drag/docs) -- unlike JQuery or all those big libraries, FORK's modules are decoupled from each other, and are simple enough that you could probably look at Peter's source code and figure out the bits you need. (edit: I'd just use FORK.Drag as it's really small: 7.6KB total minified)
Simple JavaScript drag and drop witout the help of a library
[ "", "javascript", "drag-and-drop", "" ]
I am getting some junk data returned from a ToString() call on a DateTime object in C# and I'm afraid I'm stumped after poking around with it for a while. The function is supposed to format dates to be compliant with RFC 822 (as required by the RSS spec) and looks like: ``` public static string FormatPubDate(DateTime pubDate) { string _rfc822Format = "ddd, dd MMM yyyy HH:mm:ss"; string _tmp = pubDate.ToUniversalTime().ToString(_rfc822Format); return pubDate.ToString(_tmp + " UT"); } ``` Which should be what I want, from what I can read of the DateTime ToString() docs. However, for some dates it's generating junk: ``` Console.WriteLine(FormatPubDate(new DateTime(2008, 12, 16, 13, 44, 33))); Console.WriteLine(FormatPubDate(new DateTime(2008, 12, 17, 13, 44, 33))); Console.WriteLine(FormatPubDate(new DateTime(2009, 3, 18, 4, 17, 20))); Console.WriteLine(FormatPubDate(new DateTime(2009, 4, 30, 10, 44, 33))); ``` Yields: ``` Tue, 16 Dec 2008 19:44:33 UT We17, 17 Dec 2008 19:44:33 UT We18, 18 3ar 2009 09:17:20 UT T10u, 30 Apr 2009 15:44:33 UT ``` Any ideas why it's returning We18 instead of Wed and 3ar instead of Mar?
You're problem is the last ``` return pubDate.ToString(_tmp + " UT"); ``` You're doing a second ToString() on the DateTime with the formatted value, as the formatter... Try changing it to ``` string _rfc822Format = "ddd, dd MMM yyyy HH:mm:ss"; string _tmp = pubDate.ToUniversalTime().ToString(_rfc822Format); return _tmp + " UT"; ```
Can you use this instead?: ``` String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123 ```
Stumped on C# DateTime ToString() formatting problem
[ "", "c#", "datetime", "rfc822", "" ]
I've installed SQL Server 2005 on my machine and now I'm trying to connect to it via SQuirrel SQL, but I am unfortunately running into problems. When installing SQL Server 2005 I chose mixed mode for authentication and I've set up a new user account with which I'm trying to connect. I've also installed the Microsoft SQL Server JDBC Driver and I have successfully used SQuirrel SQL to connect to a remote server before. Currently I'm trying to connect to my database by specifying ``` jdbc:sqlserver://localhost:1433 ``` for the URL and selecting Microsoft SQL Server JDBC Driver. After entering my username and password I'm getting the following error: > test: The TCP/IP connection to the host has failed. > java.net.ConnectException: Connection refused: connect with the following stack trace: ``` com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host has failed. java.net.ConnectException: Connection refused: connect at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(Unknown Source) at net.sourceforge.squirrel_sql.fw.sql.SQLDriverManager.getConnection(SQLDriverManager.java:133) at net.sourceforge.squirrel_sql.client.mainframe.action.OpenConnectionCommand.execute(OpenConnectionCommand.java:97) at net.sourceforge.squirrel_sql.client.mainframe.action.ConnectToAliasCommand$SheetHandler.run(ConnectToAliasCommand.java:279) at net.sourceforge.squirrel_sql.fw.util.TaskExecuter.run(TaskExecuter.java:82) at java.lang.Thread.run(Unknown Source) ``` One last thing, I've checked to make sure TCP/IP connections and named pipes are enabled in the SQL Server Configuration Manager. If anyone has any thoughts on my problem I would be very grateful to hear them.
So after doing some more research, it turns out that my sql server was not listening to the correct port. For anyone else having this problem I recommend reading the following web page which was very useful: <http://www.databasejournal.com/features/mssql/article.php/3689846/Using-Non-Standard-Port-for-SQL-Server.htm> Basically you need to configure your server to always listen on a certain port (I chose 1433) and restart your server. After that it should work like a charm.
Run the surface area configuration tool from: Start > All Programs > Microsoft SQL Server 2005 > Contifuration Tools > Sql Server Surface Area Configuration Click on S**urface Area Configuration for Services and Connections** link. In next window click on **Remote Connections** item under the server you want to configure. now on right hand side chose *'Local and remote connections'* and then select *'Using both TCP/IP and named pipes'*. Hope this solves your problem. EDIT: You may check these articles at [microsoft](http://support.microsoft.com/kb/914277).
Can't connect to SQL Server 2005
[ "", "sql", "sql-server", "database", "connection", "" ]
I have a jar file that uses some txt files. In order to get them it uses `Class.getResourceAsStream` function. ``` Class A { public InputStream getInputStream(String path) throws Exception { try { return new FileInputStream(path); } catch (FileNotFoundException ex) { InputStream inputStream = getClass().getResourceAsStream(path); if (inputStream == null) throw new Exception("Failed to get input stream for file " + path); return inputStream; } } } ``` This code is working perfectly. Problem is, if I define class A as `extends java.io.File`, the InputStream I get from `getResourceAsStream` is null. Also, if I leave class A as regular class (not inherited), and define class B as: ``` Class B extends java.io.File { public InputStream getInputStream(String path) throws Exception { return new A().getInputStream(path); } } ``` the returned InputStream is still null. What is the problem? Is there a way to access the file from the class that inherits `File`? Thanks,
I suspect this is more to do with packages than inheritance. If your class is in a package, then `getResourceAsStream()` will be relative to that package unless you start it with "/" (which makes it an "absolute" resource). An alternative is to use `getClass().getClassLoader().getResourceAsStream()` which doesn't have any idea of a path being relative to a package. Just subclassing `File` shouldn't affect the behaviour at all. If you really believe it does, please post a short but complete program to demonstrate the problem.
Here are some examples that back up Jon Skeet's explanation: Premise: You have a class my.package.A that depends on foo.txt. 1. If you use my.package.A.class.getResourceAsStream("foo.txt") and you place foo.txt at my/package/foo.txt in your jar file, then when you run class A it should find foo.txt. 2. if you use my.package.A.class.getClassLoader().getResourceAsStream("foo.txt") then place foo.txt in any folder on the classpath, when you run class A it should find foo.txt. 3. if you use my.package.A.class.getResourceAsStream("/foo.txt") and you place foo.txt at /foo.txt in my jar file, then when you run project A it should find foo.txt.
getResourceAsStream not working for every class?
[ "", "java", "jar", "" ]
I have something like this set up: ``` class CategoryPage (webapp.RequestHandler): def get(self): ** DO SOMETHING HERE ** def post(self): ** DO SOMETHING HERE ** ** RENDER THE SAME AS get(self) ``` The question is, after I process the posted data, how would I be able to display the same information as the get(self) function?
A redirect, as others suggest, does have some advantage, but it's something of a "heavy" approach. As an alternative, consider refactoring the rendering part into a separate auxiliary method `def _Render(self):` and just ending both the `get` and `post` methods with a call to `self.Render()`.
Call self.redirect(url) to redirect the user back to the same page over GET. That way, they won't accidentally re-submit the form if they hit refresh.
Python Django: Handling URL with Google App Engine - Post then Get
[ "", "python", "google-app-engine", "" ]
I am writing a application that needs to resize massive amounts of images... and these are my requirements: * C/C++ * Support jpeg/png at least * Fast * Cross-Platform So far my options are: * OpenCV * CImg * ImageMagick * GraphicsMagick (it's said to be fast) * DevIL * GIL from Boost * CxImage * Imlib2 (it's said to be fast) * Any others? All of these would get the job done, but I am looking for the **fastest** here, and I was not able to find any benchmarks on their performance.
Take a look at [Intel IPP (Integrated Performance Primitives)](http://en.wikipedia.org/wiki/Integrated_Performance_Primitives) (Wiki link is better then the Intel one...) it works also on AMD and has functions to resize images (bilinear, nearest neighbor, etc) and works on Linux and Windows. It is not free (but it won't break the bank), but its the fastest that you can find.
Take a look at [VIPS](https://libvips.github.io/libvips/). It's the fastest one I've found so far, and is free for commercial use. <https://github.com/libvips/libvips/wiki/Speed-and-memory-use> On that benchmark, it's 2x faster than Pillow-SIMD, 5x faster than imagemagick, 6x faster than opencv, 8x faster than freeimage, etc. It has dramatically lower memory use too: more than 10x less than imagemagick, for example.
Fastest C/C++ image resizing library
[ "", "c++", "c", "image", "resize", "" ]
How can I have a 64-bit integer in PHP? It seems like it is not by a config file, but rather it might be a compile-time option, and it depends on the platform.
Native 64-bit integers require 64-bit hardware AND the 64-bit version of PHP. On 32-bit hardware: ``` $ php -r 'echo PHP_INT_MAX;' 2147483647 ``` On 64-bit hardware: ``` $ php -r 'echo PHP_INT_MAX;' 9223372036854775807 ```
**UPDATE:** It does now (tested on AMD quad core, Windows 8.1). Note that PHP on Windows does not support 64-bit integers at all, even if both the hardware and PHP are 64-bit. See [this link](http://permalink.gmane.org/gmane.comp.php.devel/55886) for details: > On Windows x86\_64, PHP\_INT\_MAX is 2147483647. This is because in the underlying C code, a long is 32 bit. > > However, Linux on x86\_64 uses a 64-bit long, so PHP\_INT\_MAX is going to be > 9223372036854775807.
How can I have a 64-bit integer in PHP?
[ "", "php", "64-bit", "integer", "" ]
I was just wondering how i would let my java program continue running, but always be ready to take input. Right now i am using a bufferreader and reading in a line, but that makes my program halt and wait for input. I want the program to continue running but be ready to take input whenever needed, is there a way to do this?
I would expect that you're going to have to look into multithreading your application in order to get this working as you desire. **Edit**: Of course, while this functionality can be achieved by a purely CLI interface, you would probably be better off exploring other options (i.e. GUI options) if you intend on having a full response/event-driven system running in a multithreaded fashion.
Here is a quick example of how a multi-threaded command line interface application may work. This will not require polling for input, nor a GUI interface in order to perform tasks in the background while waiting for input from a user in a console. In this example, a `Thread` is running in the background, which can be told to output a greeting in a specified number of seconds later. ``` public class CommandLineMultiThread { public static void main(String[] args) { Scanner s = new Scanner(System.in); // Makes and runs the background thread. MyThread myThread = new MyThread(); Thread t = new Thread(myThread); t.start(); // Get the number of seconds to wait from the console. // Exit when "0" is entered. int waitDuration; do { waitDuration = s.nextInt(); myThread.setGreetIn(waitDuration); } while (waitDuration != 0); myThread.quit(); } static class MyThread implements Runnable { boolean running = true; // Boolean to keep thread alive. long greetingTime = Long.MAX_VALUE; // Time to greet at. public void setGreetIn(int i) { greetingTime = System.currentTimeMillis() + (i * 1000); } public void quit() { running = false; } public void run() { while (running) { if (System.currentTimeMillis() > greetingTime) { System.out.println("Hello!"); greetingTime = Long.MAX_VALUE; } try { Thread.sleep(100); } catch (InterruptedException e) {} } } } } ``` The [`Scanner`](http://java.sun.com/javase/6/docs/api/java/util/Scanner.html) class can be used to accept user input from the command line interface by routing the input from the [`System.in`](http://java.sun.com/javase/6/docs/api/java/lang/System.html#in) object. Then, while the background thread `myThread` is running, the main thread is waiting for an input from `System.in` via the [`Scanner.nextInt`](http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#nextInt()) method. Once the seconds to wait has been accepted, the background thread is told to wait until a certain time, and once that time arrives, the greeting `Hello!` is output to the console.
Taking input in Java without program hanging?
[ "", "java", "input", "continuous", "" ]
What is a good pywin32 odbc connector documentation and tutorial on the web?
The only 'documentation' that I found was a unit test that was installed with the pywin32 package. It seems to give an overview of the general functionality. I found it here: python dir\Lib\site-packages\win32\test\test\_odbc.py I should also point out that I believe it is implements the Python Database API Specification v1.0, which is documented here: <http://www.python.org/dev/peps/pep-0248/> Note that there is also V2.0 of this specification (see PEP-2049) On a side note, I've been trying to use pywin32 odbc, but I've had problems with intermittent crashing with the ODBC driver I'm using. I've recently moved to pyodbc and my issues were resolved.
Alternatives: * mxODBC by [egenix.com](http://egenix.com) (if you need ODBC) * [pyODBC](http://code.google.com/p/pyodbc) * [sqlalchemy](http://www.sqlalchemy.org/) and DB-API 2.0 modules (which isn't ODBC) but it's maybe better alternative
Is there any pywin32 odbc connector documentation available?
[ "", "python", "windows", "odbc", "pyodbc", "" ]
At the Boost library conference today, [Andrei Alexandrescu](http://en.wikipedia.org/wiki/Andrei_Alexandrescu), author of the book Modern C++ Design and the Loki C++ library, gave a talk titled "Iterators Must Go" ([video](https://archive.org/details/AndreiAlexandrescuKeynoteBoostcon2009), [slides](http://accu.org/content/conf2009/AndreiAlexandrescu_iterators-must-go.pdf)) about why iterators are bad, and he had a better solution. I tried to read the presentation slides, but I could not get much out of them. 1. Are iterators bad? 2. Is his replacement really better? 3. Will C++ implementators pick up his ideas?
First, to answer your questions: 1. No. In fact, I argued [elsewhere](https://stackoverflow.com/questions/296/should-i-learn-c/22362#22362) that iterators are the most important/fundamental concept of computer science ever. I (unlike Andrei) also think that iterators are *intuitive*. 2. Yes, definitely but that shouldn't come as a surprise. 3. Hmm. Looking at [Boost.Range](http://www.boost.org/doc/libs/1_38_0/libs/range/index.html) and C++0x – haven't they already? Andrei's big contribution here is just to say: drop the concept of iterators altogether, see ranges not just as a convenience wrapper but rather as a core construct. Other languages have already done this (much of Andrei's concepts just echo .NET's LINQ or Python's iterators) but they all only offer *output ranges*. Andrei argues for different types of ranges, much like the conventional iterator categories. In that light, it's odd that he starts by mocking the arbitrariness of these iterator categories. I also think that his examples are off, especially his file copying: yes, the iterator variant is a **huge** improvement over the 1975 code. It reduces a loop with complicated break condition down to *one* statement. What he's really taking issue with here is just the syntax. Well, excuse me: we're talking about C++ here – *of course* the syntax is ugly. And yes, using ranges here *is* an improvement – but only syntactically. I also think that Andrei's `find` implementation is off. What he really defines there is the `DropUntil` operation (naming is hard!) from LINQ. The `find` operation should really return either one or zero elements (or an iterator!). Shunning iterators here isn't helpful in my opinion since we might want to modify the value directly instead of copying it. Returning a one-element range here only adds overhead without a benefit. Doing it Andrei's way is bad because then the name of the method is just wrong and misleading. That said, I essentially agree with Andrei in almost all points. Iterators, while being my pet concept from computer science, are certainly a big syntactical burden and many ranges (especially infinite generators) can (and should) be implemented conveniently without them.
I agree with him that iterators are mostly inferior to ranges, and I don't know if 'something better' will get picked up. "The good is the enemy of the best" is strongly at play here, as it usually is. Iterators are useful and firmly entrenched, so it's hard to know if something better like ranges can supplant them in a reasonable amount of time.
C++ iterators considered harmful?
[ "", "c++", "iterator", "language-design", "" ]
Maybe I'm dumb but ... I have: ``` public interface IRequest { IList<IRequestDetail> Details { get; set; } // stuff } public interface IRequestDetail { // stuff } ``` I then have: ``` public class MyRequest : IRequest { IList<MyRequestDetail> Details {get; set; } // stuff } public class MyRequestDetail : IRequestDetail { // stuff } ``` It doesn't work. C# gets pissed at me because MyRequest does not implement the interface due to not having an IList of IRequestDetail. Now if I change it so the Details is IList of IRequestDetail I then have to cast it to MyRequestDetail everywhere in the code I use a non-interface member (I have several requests that share common stuff, but then specialize). I kind of understand why its wrong, but not fully!
I think, based on the question that the problem is that you want to treat Details as a generic list and enforce that it implements IRequestDetail. You also want it to be more specifically typed for the implementing classes. In this case, you need to make IRequest generic. Try this: ``` public interface IRequest<T> where T : IRequestDetail { IList<T> Details { get; set; } // stuff } public class MyRequest : IRequest<MyRequestDetail> { public IList<MyRequestDetail> Details {get; set; } // stuff } ``` This should work for you. **EDIT 2017-03-17** In reply to @Robert's comment, see the expanded code below: ``` public interface IRequestDetail { } public class MyRequestDetail : IRequestDetail { } public interface IRequest<T> where T : IRequestDetail { IList<T> Details { get; set; } // stuff } public class MyRequest<T> : IRequest<T> where T : IRequestDetail { public IList<T> Details { get; set; } // stuff } public class Consumer { public void MyFunction<T>(IRequest<T> request) where T : IRequestDetail { } public void Foo() { var test = new MyRequest<MyRequestDetail>(); MyFunction(test); } } ```
Exact. Michael has the solution. the problem is a little trickier. its that there is no explicit conversion from ``` IList<MyRequestDetail> ``` to ``` IList<IRequestDetail> ``` because that would imply that you can add other objects, that are based on different classes (e.g. MyRequestDetail2), that are not "MyRequestDetail" to the second object. and that would be illegal for the first.
Interface with a list of Interfaces
[ "", "c#", "generics", "interface", "" ]
I'm building an ASP .NET 2.0 (C#) based web application, which is primarily intended for intra-net use, i.e. to be used inside an organization's Local Area Network. With respect to the User Interface, there are 2 approaches which I need to choose from. 1. Build a 1 page web app, with lots of ASP .NET AJAX 1.0 controls (modal popups) to show categorized content which would otherwise have gone into a separate .aspx page. 2. Use the traditional approach and build multiple pages. The 1 page UI looks and feels very cool. However, I have doubts with respect to its scalability. Agreed that the application is intended for use over a LAN, but since it is a web app, it could potentially be used from over the internet if the client wanted to. Owing to the 1 page UI, there's already around 2600 lines of code in the single .aspx page and another 1600 lines of code in the code-behind (.aspx.cs) This is going to grow - to at most - 10,000 lines of code (10,000 in .aspx and 10,000 in .aspx.cs). So I need to know - how much is too much for an ASP .NET based page - is 2600 + 1600 lines of code okay for Intranet AND Internet access? How about 10,000 lines of code? What is the bottle-neck? Is this single-page approach okay or do I need to fall back to the traditional multiple-page approach?
Before I say what I intend to say I would like to state that I do not think this is a good idea. Any class (ASP.NET) or not that is 5k or 10k lines long needs to be refactored. There are a lot of comments here that keep stating that your download times will be too long. Just because you have an .aspx file that has 5k lines of code embedded or 5k in a code behind file (or both) this doesn't mean that your download times will be significant just because of this. Those lines of code are compiled and executed on the server, they are not passed to the client. So there is not a direct relationship between # of lines of code to download size. Sayed Ibrahim Hashimi My Book: [Inside the Microsoft Build Engine : Using MSBuild and Team Foundation Build](https://rads.stackoverflow.com/amzn/click/com/0735626286)
Regardless of the increased download time for an incredibly bloated single page like that, it would be an absolute nightmare to maintain. I agree with Brad, the single page approach is not right. And I can't think of any way to justify 10k+ lines in a single codebehind.
ASP.NET web application - 5000 lines of code in 1 page - acceptable?
[ "", "c#", "asp.net", "scalability", "intranet", "" ]
[Conkeror](http://conkeror.org/) has changed the way I browse the web: it's basically Emacs + Firefox with javascript based configuration in [.conkerrorc](http://conkeror.org/ConkerorRC) rather than elisp configuration in .emacs. I've built up a huge library of .emacs customizations over the years by getting little bits and pieces from others. I'm just starting with Conkeror but the fact that it uses JS (far more widely known than Elisp) must mean that there's some amazing stuff out there. Care to share your pieces? **I'm particularly interested in stuff that interacts well with pages produced by Django (or other dynamic web pages).** For example, I'd love a Conkeror-based action recorder that let me browse a site and find bugs, and then immediately save & submit the sequence of actions as a bug report with a single keystroke. By including the JS actions required to replicate the error, it would be the ultimate testing harness -- even better than Selenium because it would be totally keyboard driven.
Since no one else seems interested in posting an actual reply, I will. ``` function my_title_format (window) { return 'conkeror {'+get_current_profile()+'}'+window.buffers.current.description; } ``` I find it helpful to have the profile name in the window title as I use multiple profiles. It doesn't help me so much now that I use [StumpWM](http://www.nongnu.org/stumpwm/) and don't look at the window list much, but it's very helpful in other window managers. ``` define_key(content_buffer_normal_keymap, "C-x C-c", "confirm-quit"); can_kill_last_buffer = false; ``` These two keep me from accidentally closing a conkeror window by closing the last buffer.
Here's mine: ``` // homepage = "http://www.google.com"; // set default webjump read_url_handler_list = [read_url_make_default_webjump_handler("google")]; // possibly valid URL function possibly_valid_url (str) { return (/[\.\/:]/.test(str)) && !(/\S\s+\S/.test(str)) && !(/^\s*$/.test(str)); } // page modes require("page-modes/google-search-results.js"); // google search results require("page-modes/wikipedia.js"); // wikipedia mode // webjumps define_webjump("gmail", "https://mail.google.com"); // gmail inbox define_webjump("twitter", "http://twitter.com/#!/search/%s", $alternative = "https://twitter.com/"); // twitter define_webjump("w3schools", "http://www.w3schools.com"); // w3schools site define_webjump("w3search", "http://www.google.com/search?sitesearch=www.w3schools.com&as_q=%s"); // w3schools search define_webjump("jquery", "http://docs.jquery.com/Special:Search?ns0=1&search=%s"); // jquery define_webjump("archwiki", "https://wiki.archlinux.org/index.php?search=%s"); // arch wiki define_webjump("stackoverflow", "http://stackoverflow.com/search?q=%s", $alternative = "http://stackoverflow.com/"); // stackoverflow define_webjump("sor", "http://stackoverflow.com/search?q=[r]+%s", $alternative = "http://stackoverflow.com/questions/tagged/r"); // stackoverflow R section define_webjump("stats", "http://stats.stackexchange.com/search?q=%s"); // stats define_webjump("torrentz", "http://torrentz.eu/search?q=%s"); // torrentz define_webjump("avaxsearch", "http://avaxsearch.com/avaxhome_search?q=%s&a=&c=&l=&sort_by=&commit=Search"); // avaxsearch define_webjump("imdb", "http://www.imdb.com/find?s=all;q=%s"); // imdb define_webjump("duckgo", "http://duckduckgo.com/?q=%s", $alternative = "http://duckduckgo.com"); // duckduckgo define_webjump("blekko", "http://blekko.com/ws/%s", $alternative = "http://blekko.com/"); // blekko define_webjump("youtube", "http://www.youtube.com/results?search_query=%s&aq=f", $alternative = "http://www.youtube.com"); // youtube define_webjump("duckgossl", "https://duckduckgo.com/?q=%s"); // duckduckgo SSL define_webjump("downforeveryoneorjustme", "http://www.downforeveryoneorjustme.com/%s"); // downforeveryoneorjustme define_webjump("urbandictionary", "http://www.urbandictionary.com/define.php?term=%s"); // urban dictionary define_webjump("rts", "http://rts.rs"); // RTS define_webjump("facebook", "http://www.facebook.com"); // facebook homepage // tab bar require("new-tabs.js"); // clicks in new buffer require("clicks-in-new-buffer.js"); // Set to either OPEN_NEW_BUFFER(_BACKGROUND) clicks_in_new_buffer_target = OPEN_NEW_BUFFER_BACKGROUND; // Now buffers open in background. // history webjump define_browser_object_class( "history-url", null, function (I, prompt) { check_buffer (I.buffer, content_buffer); var result = yield I.buffer.window.minibuffer.read_url( $prompt = prompt, $use_webjumps = false, $use_history = true, $use_bookmarks = false); yield co_return (result); }); interactive("find-url-from-history", "Find a page from history in the current buffer", "find-url", $browser_object = browser_object_history_url); interactive("find-url-from-history-new-buffer", "Find a page from history in the current buffer", "find-url-new-buffer", $browser_object = browser_object_history_url); define_key(content_buffer_normal_keymap, "h", "find-url-from-history-new-buffer"); define_key(content_buffer_normal_keymap, "H", "find-url-from-history"); // load session module require("session.js"); session_auto_save_auto_load = true; // auto-load session // don't open download buffer automatically remove_hook("download_added_hook", open_download_buffer_automatically); // don't show clock remove_hook("mode_line_hook", mode_line_adder(clock_widget)); // add favicons require("favicon"); add_hook("mode_line_hook", mode_line_adder(buffer_icon_widget), true); read_buffer_show_icons = true; // add content handlers content_handlers.set("application/pdf", content_handler_save); // pdf // torrent // mp3 // ogg function define_switch_buffer_key (key, buf_num) { define_key(default_global_keymap, key, function (I) { switch_to_buffer(I.window, I.window.buffers.get_buffer(buf_num)); }); } for (let i = 0; i < 10; ++i) { define_switch_buffer_key(String((i+1)%10), i); } function enable_scrollbars (buffer) { buffer.top_frame.scrollbars.visible = true; } add_hook("create_buffer_late_hook", enable_scrollbars); ```
What does your .conkerorrc look like?
[ "", "javascript", "firefox", "configuration", "emacs", "conkeror", "" ]
I have a simple text file with several thousands of words, each in its own line, e.g. ``` aardvark hello piper ``` I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose): ``` my_set = set(open('filename.txt')) ``` The above code produces a set with the following entries (each word is followed by a space and new-line character: ``` ("aardvark \n", "hello \n", "piper \n") ``` What's the simplest way to load the file into a set but get rid of the space and \n? Thanks
The strip() method of strings removes whitespace from both ends. ``` set(line.strip() for line in open('filename.txt')) ```
Just load all file data and split it, it will take care of one word per line or multiple words per line separated by spaces, also it will be faster to load whole file at once unless your file is in GBs ``` words = set(open('filename.txt').read().split()) ```
Python: load words from file into a set
[ "", "python", "text-files", "" ]
Is there a way to automatically generate source and javadoc jars in Netbeans? Ideally I would like to place jars of my source and JavaDoc in the dist folder each time i build.
Here is what I personally add to my ant files (build.xml) : ``` <target description="bundle sources in a jar" name="package-sources"> <jar basedir="src" destfile="dist/${ant.project.name}-sources.jar"/> </target> <target depends="-javadoc-build" description="bundle javadoc in a jar" name="package-doc"> <jar basedir="dist/javadoc" destfile="dist/${ant.project.name}-javadoc.jar"/> </target> ``` With Netbeans call these targets manually, or you can use hook targets : ``` <target name="-post-jar" depends="package-sources, package-doc" /> ```
Please try adding this to build.xml. I've tested it on NetBeans IDE 7.0 ``` <target name="-post-jar" description="bundle sources and javadoc in a jar" depends="javadoc"> <jar compress="${jar.compress}" basedir="${src.dir}" jarfile="${dist.dir}/${application.title}-sources.jar"/> <jar compress="${jar.compress}" basedir="${test.src.dir}" jarfile="${dist.dir}/${application.title}-test.jar"/> <jar compress="${jar.compress}" basedir="${dist.javadoc.dir}" jarfile="${dist.dir}/${application.title}-javadoc.jar"/> </target> ```
Automatically generating source and doc jars in Netbeans
[ "", "java", "netbeans", "ant", "build", "jar", "" ]
Two types of users visit my website: registered users and guests. Registered users are tracked and retained by PHP session, cookies and individual logins. Guests I find trickier to manage so I give little to no authority to contribute content. I want to open up editing for users (registered or not) to save favourites, shopping carts, vote in polls, moderate, tag, upload and comment. At the same time, protect the data from other non-registered users. What are some options or best practices to determine a unique visitor from another and some security measures to consider when allowing them to contribute more? Should I work around their security/restriction settings to provide contribution service or should I expect them to meet in the middle and relax some of their settings to allow cookies etc? **IP Address** - The IP is an option but only temporary. It can change for a user reconnecting to their Internet with a different IP, and for that matter another user may eventually share the same IP. IP can also be anonymous, shared or misleading. **PHP Sessions** - OK for a session (and if enabled) but lost on closing the browser. **Cookies** - Can store session data but is easily (and often) disabled from the client-side. **Header data** - combining known details of he user might at least group users - ISP, browser, operating system, referring website etc. **Edit:** I'm still having trouble getting my head around all the the key factors involved... we set up a cookie for a guest. Attach a bunch of edits and user history to that session. If the cookie is removed, the data floats around attached to nothing and the user loses their data. Or if the user logs in, the guest and user data should be merged...
I think cookies would probably be the best option here as it's the only way you are going to be 100% sure requests are unique. Of course, you could possibly add a mix: if cookies are disabled you might be able to try other options of identification such as the IP address method, but that could make it overly-complex. As you say, IP address is liable to change and in some organizations there may be a group of proxy servers setup which make requests originate from different IPs. Of course, you could check X\_FORWARDED\_FOR, but they are still liable to change. Header data is probably going to prove difficult to get good results on I think. If you've got an organization that has the same browser, OS, IP it is going to show people as being the same. Even people not in the same organization may still appear similar (i.e AOL users who get their traffic usually routed through proxy servers, the majority will probably be using the 'AOL browser' that gets shipped with it giving similar headers). Out of those two options, the IP one is going to be easy to implement but obviously there are the problems I outlined. Checking for unique data in the headers will prove to be absolute pain I think. Obviously as you say, sessions are lost on closing the browser, and it appears you want the system to behave as if they were a registered user so cookies seem a more obvious choice (especially as you want the 'favourites' to be persistent).
I would just go with sessions. Your users could change IP addresses (prone to mixup behind NATs and proxies), modify/delete cookies (certainly possible), or change their header (easily through switching browsers). There is no secure way of identifying a guest if they do not want to be identified. Just go with the standard: cookies/sessions.
Ways to determine returning "anonymous" guests in PHP
[ "", "php", "" ]
I'm interested in precisely extracting portions of a PCM WAV file, down to the sample level. Most audio modules seem to rely on platform-specific audio libraries. I want to make this cross platform and speed is not an issue, are there any native python audio modules that can do this? If not, I'll have to interpret the PCM binary. While I'm sure I can dig up the PCM specs fairly easily, and raw formats are easy enough to walk, I've never actually dealt with binary data in Python before. Are there any good resources that explain how to do this? Specifically relating to audio would just be icing.
I read the question and the answers and I feel that I must be missing something completely obvious, because nobody mentioned the following two modules: * [audioop](https://docs.python.org/library/audioop.html): manipulate raw audio data * [wave](https://docs.python.org/library/wave.html): read and write WAV files Perhaps I come from a parallel universe and Guido's time machine is actually a space-time machine :) Should you need example code, feel free to ask. PS Assuming 48kHz sampling rate, a video frame at 24/1.001==23.976023976… fps is 2002 audio samples long, and at 25fps it's 1920 audio samples long.
I've only written a PCM reader in C++ and Java, but the format itself is fairly simple. A decent description can be found here: <http://ccrma.stanford.edu/courses/422/projects/WaveFormat/> Past that you should be able to just read it in (binary file reading, <http://www.johnny-lin.com/cdat_tips/tips_fileio/bin_array.html>) and just deal with the resulting array. You may need to use some bit shifting to get the alignments correct (<https://docs.python.org/reference/expressions.html#shifting-operations>) but depending on how you read it in, you might not need to. All of that said, I'd still lean towards David's approach.
How to edit raw PCM audio data without an audio library?
[ "", "python", "audio", "binary", "wav", "" ]
I have a stored procedure.. ``` Proc: spMyStoredProcedure ``` Takes a Param: ``` @List varchar(255) ``` The @List would be a comma separated list of values i.e... @List = '1,2,3' *(clarity.. a single value of 1 would mean all records with col1 = true)* I have a table with these columns: **ID** int, **col1** bit, **col2** bit, **col3** bit, **col4** bit. ``` ID | col1 | col2 | col3 | col4 ------------------------------ 12 | 0 | 1 | 0 | 0 13 | 1 | 0 | 0 | 0 14 | 0 | 0 | 1 | 0 15 | 0 | 0 | 0 | 1 ``` I'd like my result to only include ID's for those rows in the list. i.e. 12,13,14. My first thought is to loop through the list and do a select. ie. for the first value being 1, I grab all records with a 1 (true) in col1 (resulting in record 12). Then move onto the second value being 2 and grab all records with a 1 (true) in col2 (resulting in record 14) and so on.. I'm wondering if there's a more efficient/better/cleaner way to do this?
I think this solves the problem: ``` declare @sql as nvarchar(max) set @sql = 'select * from table where col' + replace(@list, ',', '=1 or col') + '=1' sp_executesql @sql ``` This is assuming that list is not user-generated, and it's code generated, so I'm not guarding against SQL injection attacks. A list like this isn't generally something that's user-generated, so that's why I'm assuming as such. Is this what you're looking for?
\*\* wrong answer, check Eric's answer for a better reply! Luckily, your list seems to match the IN format: ``` select * from yourtable where id in (1,2,3,4) ``` So you could easily build a dynamic query: ``` declare @query varchar(4000) set @query = 'select * from yourtable where id in (' + @list + ')' exec sp_executesql @query ``` Keep in mind that your client has to ensure the @list parameter is injection clean. You could verify in the stored procedure that it doesn't contain any single quotes.
Need SQL Query Help, matching a stored procedure list parameter against individual columns
[ "", "sql", "t-sql", "stored-procedures", "" ]
The title is pretty self-explanatory: does anyone know of a (good) properties file reader library for C or, if not, C++? Edit: To be specific, I want a library which handles the .properties file format used in Java: <http://en.wikipedia.org/wiki/.properties>
[STLSoft](http://www.stlsoft.org/)'s [1.10 alpha](https://sourceforge.net/project/showfiles.php?group_id=238860&package_id=294944) contains a `platformstl::properties_file` class. It can be used to read from a file: ``` using platformstl::properties_file; properties_file properties("stuff.properties"); properties_file::value_type value = properties["name"]; ``` or from memory: ``` properties_file properties( "name0=value1\n name1 value1 \n name\\ 2 : value\\ 2 ", properties_file::contents); properties_file::value_type value0 = properties["name0"]; properties_file::value_type value1 = properties["name1"]; properties_file::value_type value2 = properties["name 2"]; ``` Looks like the latest 1.10 release has a bunch of comprehensive unit-tests, and that they've upgraded the class to handle all the rules and examples given in the [Java documentation](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Properties.html#load(java.io.InputStream)). The only apparent rub is that the `value_type` is an instance of [`stlsoft::basic_string_view`](http://www.stlsoft.org/doc-1.9/classstlsoft_1_1basic__string__view.html) (described in [this Dr Dobb's article](http://www.ddj.com/cpp/184402064)), which is somewhat similar to `std::string`, but doesn't actually own its memory. Presumably they do this to avoid unneccessary allocations, presumably for performance reasons, which is something the STLSoft design holds dear. But it means that you can't just write ``` std::string value0 = properties["name0"]; ``` You can, however, do this: ``` std::string value0 = properties["name0"].c_str(); ``` and this: ``` std::cout << properties["name0"]; ``` I'm not sure I agree with this design decision, since how likely is it that reading properties - from file or from memory - is going to need the absolute last cycle. I think they should change it to use `std::string` by default, and then use the "string view" if explicitly required. Other than that, the `properties_file` class looks like it does the trick.
libconfuse (C library) is useful, too; it's been around forever & is flexible. * ( www.nongnu.org/confuse/ ) <http://www.nongnu.org/confuse/tutorial-html/index.html> It goes way, way beyond java.util.Properties. Though, it won't necessarily handle the corner cases of the java properties file format (which seems to be your requirement). See the examples: * simple: www.nongnu.org/confuse/simple.conf * crazy: www.nongnu.org/confuse/test.conf No C++ wrapper library, that I'm aware of, though.
Properties file library for C (or C++)
[ "", "c++", "c", "properties", "" ]
Is there a way to calculate the MD5 hash of a file before the upload to the server using Javascript?
While there are [JS implementations](http://pajhome.org.uk/crypt/md5/) of the MD5 algorithm, **older browsers are generally unable to read files from the local filesystem**. I wrote that in 2009. So what about new browsers? **With a browser that supports the [FileAPI](http://www.w3.org/TR/FileAPI/), you *can* read the contents of a file** - the user has to have selected it, either with an `<input>` element or drag-and-drop. As of Jan 2013, here's how the major browsers stack up: * FF 3.6 supports [FileReader](https://developer.mozilla.org/en/DOM/FileReader), FF4 supports even more file based functionality * Chrome has supported the FileAPI since [version 7.0.517.41](http://googlechromereleases.blogspot.com/2010/10/stable-channel-update.html) * Internet Explorer 10 has partial [FileAPI support](http://msdn.microsoft.com/en-us/ie/hh272905#_HTML5FileAPI) * Opera 11.10 has [partial support for FileAPI](http://dev.opera.com/articles/view/the-w3c-file-api/) * Safari - I couldn't find a good official source for this, but [this site suggests partial support from 5.1, full support for 6.0](http://caniuse.com/fileapi). Another article reports [some inconsistencies with the older Safari versions](http://www.thebuzzmedia.com/html5-drag-and-drop-and-file-api-tutorial/) **How?** See the [answer below by Benny Neugebauer](https://stackoverflow.com/a/21458021/6521) which uses the [MD5 function of CryptoJS](https://github.com/sytelus/CryptoJS/blob/v3.1.2/rollups/md5.js)
it is pretty easy to calculate the MD5 hash using the [MD5 function of CryptoJS](https://github.com/sytelus/CryptoJS/blob/v3.1.2/rollups/md5.js) and the [HTML5 FileReader API](http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api). The following code snippet shows how you can read the binary data and calculate the MD5 hash from an image that has been dragged into your Browser: ``` var holder = document.getElementById('holder'); holder.ondragover = function() { return false; }; holder.ondragend = function() { return false; }; holder.ondrop = function(event) { event.preventDefault(); var file = event.dataTransfer.files[0]; var reader = new FileReader(); reader.onload = function(event) { var binary = event.target.result; var md5 = CryptoJS.MD5(binary).toString(); console.log(md5); }; reader.readAsBinaryString(file); }; ``` I recommend to add some CSS to see the Drag & Drop area: ``` #holder { border: 10px dashed #ccc; width: 300px; height: 300px; } #holder.hover { border: 10px dashed #333; } ``` More about the Drag & Drop functionality can be found here: [File API & FileReader](http://html5demos.com/file-api) I tested the sample in Google Chrome Version 32.
How to calculate md5 hash of a file using javascript
[ "", "javascript", "md5", "" ]
I need to get up to speed on various ways to integrate ASP.Net C# web apps with SharePoint. From the most loosely coupled (just pull a bit of content from SharePoint) to full bidirectional sync, version control, workflow, etc. What are some links or books that can quickly get me oriented as to best options and approaches?
Not very sure if this is helpful for you or not, but "[Deployment for Windows SharePoint Services 3.0 technology](http://go.microsoft.com/fwlink/?LinkID=115666)" free ebook may help you with that.
At the risk of stating the obvious, Microsoft actually has tried to make the documentation for SharePoint 3 much better than versions past. * TechNet: [Windows SharePoint Services 3.0](http://technet.microsoft.com/en-us/library/cc288070.aspx) * MSDN: [Windows SharePoint Services Developer Center](http://msdn.microsoft.com/en-us/sharepoint/default.aspx) * MSDN: [Windows SharePoint Services 3.0 SDK](http://msdn.microsoft.com/en-us/library/ms441339.aspx) * MSDN: [Windows SharePoint Services 3.0](http://msdn.microsoft.com/en-us/library/bb931737.aspx)
What are some good resources on integrating web apps with SharePoint?
[ "", "c#", "asp.net", "sharepoint", "integration", "" ]
``` public class Main3 { public static void main(String[] args) { Integer min = Integer.MIN_VALUE; String minHex = Integer.toHexString(Integer.MIN_VALUE); System.out.println(min + " " + minHex); System.out.println(Integer.parseInt(minHex, 16)); } } ``` Gives ``` -2147483648 80000000 Exception in thread "main" java.lang.NumberFormatException: For input string: "80000000" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:459) at Main3.main(Main3.java:7) ``` Whats up?
It's documented that `Integer.toHexString` returns a string representation of the integer as an unsigned value - while `Integer.parseInt` takes a signed int. If you use `Integer.toString(value, 16)` instead you'll get what you want.
This is something that's always annoyed me. If you initialize an int with a hex literal, you can use the full range of positive values up to `0xFFFFFF`; anything larger than `0x7FFFFF` will really be a negative value. This is very handy for bit masking and other operations where you only care about the *locations* of the bits, not their meanings. But if you use Integer.parseInt() to convert a string to an integer, anything larger than `"0x7FFFFFFF"` is treated as an error. There's probably a good reason why they did it that way, but it's still frustrating. The simplest workaround is to use Long.parseLong() instead, then cast the result to int. ``` int n = (int)Long.parseLong(s, 16); ``` Of course, you should only do that if you're sure the number is going to be in the range `Integer.MIN_VALUE..Integer.MAX_VALUE`.
Java negative int to hex and back fails
[ "", "java", "parsing", "decimal", "hex", "signed", "" ]
There are two buttons in my cakephp page,one for registering new users and the other one for login. Can both the button's action be directed to the same function in the controller and have the same view.ctp file? If yes, how can I do it?
Yes, just set the correct URL in your buttons. But I don't know why you would do this. If it is just about re-using the view.ctp then you do not need to use a single action just to use the same view. Example: ``` <?php class FoobarController extends AppController { function view() { // This will render views/foobar/view.ctp because the action // is named "view" } function register() { // Normally this would render views/foobar/register.ctp but you can // call the render() function manually and render something else. The // following call will render views/foobar/view.ctp $this->render('view'); } function login() { // Same thing here... $this->render('view'); } } ?> ```
I create buttons in my CRUD admin pages that allow either "Confirm (edit/delete/create/etc)" or "Cancel". I do this by creating 2 submit buttons in the form, and giving each a unique name. For example: View code: ``` ... $form->submit('Delete', array('name' => 'delete')); $form->submit('Cancel', array('name' => 'cancel')); ... ``` Action logic: ``` function admin_delete( ... ) { // Bail if cancel button pressed if (isset($this->params['form']['cancel'])) { $this->redirect('/'); } // Delete if delete button pressed if (isset($this->params['form']['delete'])) { // delete stuff ... } ... } ``` On the flip side, you're essentially smashing 2 actions into one for the sake of reusing a view. [Sander Marechal's solution](https://stackoverflow.com/questions/806262/cakephp-contollers/845052#845052) is better.
Can I direct two different buttons to the same function in a controller with the same view in CakePHP?
[ "", "php", "cakephp", "" ]