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 the following bit of script to load another one: ``` $.getScript("CAGScript.js", function () { try { CAGinit(); } catch(err) { console.log(err); } }); ``` The idea is that $.getScript loads the script, then executes the callback when it's done. `CAGInit()` is a function that lives in `CAGScript.js`. The problem is that roughly half the time, `CAGInit()` doesn't fire (in any browser). Logging to the Firebug console reports that it's not defined. The rest of the time it works perfectly. Does anyone have any ideas what I'm doing wrong? Thanks.
In order to make sure CAGScript.js is LOADED and EXECUTED before calling CAGinit function, the surest way is to have the function call inside CAGScript.js. CAGScript.js: ``` ... /* your code */ function CAGinit(){ ... } ... /* last line */ CAGinit(); ``` and then, in your main file just call getScript(): ``` $.getScript("CAGScript.js"); ```
I noticed the same issue with FF 3.6. A solution is to load the script synchronously. As mentioned in [jQuery's documentation](http://api.jquery.com/jQuery.getScript/), getScript is shorthand for: ``` $.ajax({ url: url, dataType: 'script', success: success }); ``` Everything works fine if I use the following instead of getScript: ``` $.ajax({ url: url, dataType: 'script', success: success, async: false }); ```
Is the callback on jQuery's getScript() unreliable or am I doing something wrong?
[ "", "javascript", "jquery", "" ]
I've been throwing a little bit of spare time at writing a BitTorrent client, mostly out of curiosity but partly out of a desire to improve my c# skills. I've been using [the theory wiki](http://wiki.theory.org/BitTorrentSpecification) as my guide. I've built up a library of classes for handling BEncoding, which I'm quite confident in; basically because the sanity check is to regenerate the original .torrent file from my internal representation immediately after parsing, then hash and compare. The next stage is to get tracker announces working. Here I hit a stumbling block, because trackers reject my requests without terribly useful error messages. Take, for instance, the [latest stack overflow database dump](https://blog.stackoverflow.com/wp-content/uploads/so-export-2009-07.7z.torrent). My code generates the following announce URI: ``` http://208.106.250.207:8192/announce?info_hash=-%CA8%C1%C9rDb%ADL%ED%B4%2A%15i%80Z%B8%F%C&peer_id=01234567890123456789&port=6881&uploaded=0&downloaded=0&left=0&compact=0&no_peer_id=0&event=started ``` The tracker's response to my code: ``` d14:failure reason32:invalid info hash and/or peer ide ``` The tracker's response to that string dropped into Chrome's address bar: ``` d8:completei2e11:external ip13:168.7.249.11110:incompletei0e8:intervali600e5:peerslee ``` The peer\_id is (valid) garbage, but changing it to something sensible (impersonating a widely used client) doesn't change anything. Like I said, I'm pretty sure I'm pulling the info dictionary out properly and hashing (SHA1) like I should, and the peer id is well formed. My guess is I'm doing some minor thing stupidly wrong, and would appreciate any help in spotting what it is exactly. Its kind of hard to guess what code would be pertinent (and there's far to much to just post). However, I'll try and post anything asked for. *EDIT* I wasn't hex encoding the info\_hash, which sort of helps. This is the code that takes the generates URI and try's to fetch a response: ``` //uri is the above WebRequest req = WebRequest.Create(uri); WebResponse resp = req.GetResponse(); Stream stream = resp.GetResponseStream(); ```
[MonoTorrent](http://en.wikipedia.org/wiki/MonoTorrent) is a BitTorrent implementation that comes with Mono. In the [HTTPTracker class](http://anonsvn.mono-project.com/viewvc/trunk/bitsharp/src/MonoTorrent/MonoTorrent.Client/Tracker/HTTPTracker.cs?view=markup) there is a `CreateAnnounceString` method. Maybe you can compare your implementation with how that method is doing it? (You probably need to hunt down where the `AnnounceParameters` instance is created.)
What exactly are you hashing? You should only hash the `info` section, not the whole torrent file... So basically, decode the file, reencode the `info` section, hash that. ie. For the torrent posted, all you should be hashing is: ``` d6:lengthi241671490e4:name20:so-export-2009-07.7z12:piece lengthi262144e6:pieces18440:<lots of binary data>e ```
BitTorrent tracker announce problem
[ "", "c#", "bittorrent", "" ]
I am developing an app that utilizes very large lookup tables to speed up mathematical computations. The largest of these tables is an int[] that has ~10 million entries. Not all of the lookup tables are int[]. For example, one is a Dictionary with ~200,000 entries. Currently, I generate each lookup table once (which takes several minutes) and serialize it to disk (with compression) using the following snippet: ``` int[] lut = GenerateLUT(); lut.Serialize("lut"); ``` where Serialize is defined as follows: ``` public static void Serialize(this object obj, string file) { using (FileStream stream = File.Open(file, FileMode.Create)) { using (var gz = new GZipStream(stream, CompressionMode.Compress)) { var formatter = new BinaryFormatter(); formatter.Serialize(gz, obj); } } } ``` The annoyance I am having is when launching the application, is that the Deserialization of these lookup tables is taking very long (upwards of 15 seconds). This type of delay will annoy users as the app will be unusable until all the lookup tables are loaded. Currently the Deserialization is as follows: ``` int[] lut1 = (Dictionary<string, int>) Deserialize("lut1"); int[] lut2 = (int[]) Deserialize("lut2"); ... ``` where Deserialize is defined as: ``` public static object Deserialize(string file) { using (FileStream stream = File.Open(file, FileMode.Open)) { using (var gz = new GZipStream(stream, CompressionMode.Decompress)) { var formatter = new BinaryFormatter(); return formatter.Deserialize(gz); } } } ``` At first, I thought it might have been the gzip compression that was causing the slowdown, but removing it only skimmed a few hundred milliseconds from the Serialization/Deserialization routines. Can anyone suggest a way of speeding up the load times of these lookup tables upon the app's initial startup?
First, deserializing in a background thread will prevent the app from "hanging" while this happens. That alone may be enough to take care of your problem. However, Serialization and deserialization (especially of large dictionaries) tends to be very slow, in general. Depending on the data structure, writing your own serialization code can dramatically speed this up, particularly if there are no shared references in the data structures. That being said, depending on the usage pattern of this, a database might be a better approach. You could always make something that was more database oriented, and build the lookup table in a lazy fashion from the DB (ie: a lookup is lookup in the LUT, but if the lookup doesn't exist, load it from the DB and save it in the table). This would make startup instantaneous (at least in terms of the LUT), and probably still keep lookups fairly snappy.
I guess the obvious suggestion is to load them in the background. Once the app has started, the user has opened their project, and selected whatever operation they want, there won't be much of that 15 seconds left to wait.
Storing Large Lookup Tables
[ "", "c#", "performance", "optimization", "serialization", "lookup-tables", "" ]
I want to check is a function exists in a library that I am creating, which is static. I've seen function and method\_exists, but haven't found a way that allows me to call them in a relative context. Here is a better example: ``` class myClass{ function test1() { if(method_exists("myClass", "test1")) { echo "Hi"; } } function test2() { if(method_exists($this, "test2")) { echo "Hi"; } } function test3() { if(method_exists(self, "test3")) { echo "Hi"; } } } // Echos Hi myClass::test1(); // Trys to use 'self' as a string instead of a constant myClass::test3(); // Echos Hi $obj = new myClass; $obj->test2(); ``` I need to be able to make test 3 echo Hi if the function exists, without needing to take it out of static context. Given the keyword for accessing the class should be 'self', as $this is for assigned classes.
`static::class` is available since PHP 5.5, and will return the "[Late Static Binding](http://php.net/manual/en/language.oop5.late-static-bindings.php)" class name: ``` class myClass { public static function test() { echo static::class.'::test()'; } } class subClass extends myClass {} subClass::test() // should print "subClass::test()" ``` [`get_called_class()`](http://ca.php.net/get_called_class) does the same, and was introduced in PHP 5.3 ``` class myClass { public static function test() { echo get_called_class().'::test()'; } } class subClass extends myClass {} subClass::test() // should print "subClass::test()" ``` --- The [`get_class()`](http://ca.php.net/manual/en/function.get-class.php) function, which as of php 5.0.0 does not require any parameters if called within a class will return the name of the class in which the function was declared (e.g., the parent class): ``` class myClass { public static function test() { echo get_class().'::test()'; } } class subClass extends myClass {} subClass::test() // prints "myClass::test()" ``` The [`__CLASS__` magic constant](https://www.php.net/manual/en/language.constants.predefined.php) does the same [[link](https://www.php.net/manual/en/language.constants.predefined.php#44214)]. ``` class myClass { public static function test() { echo __CLASS__.'::test()'; } } class subClass extends myClass {} subClass::test() // prints "myClass::test()" ```
# Update: Ahh, apologies. I was temporarily blind :) You'll want to use the magic constant \_\_CLASS\_\_ e.g. ``` if (method_exists(__CLASS__, "test3")) { echo "Hi"; } ```
Find out if a method exists in a static class
[ "", "php", "static", "object", "" ]
For a web application I want to be able to handle numbers up to 64 bits in size. During testing, I found that javascript (or the browser as a whole) seems to handle as much as 17 digits. A 64-bit number has a maximum of 20 digits, but after the javascript has handled the number, the least significant 3 digits are rounded and set to 0.... Any ideas where this comes from? More importantly, any idea how to work around it?
In Javascript, all numbers are [IEEE double precision](http://en.wikipedia.org/wiki/Double_Precision) floating point numbers, which means that you only have about 16 digits of precision; the remainder of the 64 bits are reserved for the exponent. As Fabien notes, you will need to work some tricks to get more precision if you need all 64 bits.
I think you need to treat them as strings if you have reached Javascript limit ([see here](http://www.trans4mind.com/personal_development/JavaScript/longnumSub.htm))
How can I handle numbers bigger than 17-digits in Firefox/IE7?
[ "", "javascript", "numbers", "" ]
I have a bit of script that deletes all .png files in a directory: ``` foreach (glob("*.png") as $filename) { echo "$filename size " . filesize($filename) . "\n"; unlink($filename); } ``` How do I take this one step further to delete all `.png` files over a certain file size? I have another bit of script that finds out the file size of all the files in the directory: ``` $bytes = filesize('example.png'); ``` How do I combine the two?
You can use an [if](http://php.net/manual/en/control-structures.if.php) statement to check whether the size is above the threshold: ``` $threshold = 1024; foreach (glob("*.png") as $filename) { $size = filesize($filename); if ($size > $threshold) { unlink($filename); } } ```
``` $maxsize = 1024; // example foreach (glob("*.png") as $filename) { $filesize = filesize($filename); echo "$filename size " .$filesize . "\n"; if ($filesize > $maxsize) unlink($filename); } ```
Deleting all files of a directory over a given file size each
[ "", "php", "" ]
So I have a system that is going to allow specific users the ability to create new user accounts but, for several reasons, they cannot get a listing of all users on the system. That could make creating new user names difficult (if they can't see a list of used names) Are there any standard ways of creating a user name out of a person's first and last name? Right now the system tries to default using first initial last name...but what if that's a taken name? Is there an easy way of creating this new user name without making the person try again and again? (And I'd rather not end up with jsmith1234) I have PHP, jquery, mySQL at my disposal
You could always use the person's email address in authentication instead of a traditional username. If other people can't see the username anyway this would be the best approach.
Since names aren't unique either, I can't see how that would work. Basically you have to be able to handle collision, which also lets people pick their own usernames. My advice though is don't submit the whole form and then return it to the user "username not available", usually with the password fields cleared (so you have to type those in with every attempt). This is one of my biggest pet peeves with registration processes. Use AJAX to check availability. Either with an explicit "Check availability" button or when the text field loses focus (blur event) you go check yourself.
Creating unique usernames
[ "", "php", "mysql", "" ]
I have this situation that when **AbstractMethod** method is invoked from **ImplementClass** I want to enforce that **MustBeCalled** method in the **AbstractClass** is invoked. I’ve never come across this situation before. Thank you! ``` public abstract class AbstractClass { public abstract void AbstractMethod(); public void MustBeCalled() { //this must be called when AbstractMethod is invoked } } public class ImplementClass : AbstractClass { public override void AbstractMethod() { //when called, base.MustBeCalled() must be called. //how can i enforce this? } } ```
An option would be to have the Abstract class do the calling in this manner. Otherwise, there is no way in c# to require an inherited class to implement a method in a certain way. ``` public abstract class AbstractClass { public void PerformThisFunction() { MustBeCalled(); AbstractMethod(); } public void MustBeCalled() { //this must be called when AbstractMethod is invoked } //could also be public if desired protected abstract void AbstractMethod(); } public class ImplementClass : AbstractClass { protected override void AbstractMethod() { //when called, base.MustBeCalled() must be called. //how can i enforce this? } } ``` Doing this creates the desired public facing method in the abstract class, giving the abstract class over how and in what order things are called, while still allowing the concrete class to provide needed functionality.
How about ``` public abstract class AbstractClass { public void AbstractMethod() { MustBeCalled(); InternalAbstractMethod(); } protected abstract void InternalAbstractMethod(); public void MustBeCalled() { //this must be called when AbstractMethod is invoked } } public class ImplementClass : AbstractClass { protected override void InternalAbstractMethod() { //when called, base.MustBeCalled() must be called. //how can i enforce this? } } ```
How to enforce a method call (in the base class) when overriding method is invoked?
[ "", "c#", "inheritance", "overriding", "method-call", "" ]
I am developing a Flex / Flash application which talks to an ASP.Net / C# backend. Is there any way I can share code between the two? The server provides a reasonably interesting domain model which the client is designed to maniuplate. Ideally I would like to be able to define this domain model once and have both sides use it for consistency. I am after all the benefits that come with being DRY. I'm new to Flex but the sort of thing I had in mind was some intermediate language that compile to both C# and ActionScript. ## Update I currently have a basic REST style web service which sends XML serialized versions of the objects down the wire to Flex. This works fine but what I am really interested in is being able to share simple business logic that goes along with these objects. There are certain business rules that need to be processed on both the server and the client and is possible I would prefer not to have to call back to the server for performance reasons.
I faced this problem as well, so I wrote a C# to ActionScript converter. <http://cs2as.codeplex.com/> Write your logic in C#, and add this utility as a post-build step. Then your business logic will be available in both environments. It works very well for me - I'm using it to share over 30,000 lines of code.
I'd hack together a domain model specification and have it generate models in both languages. But that's probably not the most time-effective thing to do.
How can I share code between C# and Flex?
[ "", "c#", "apache-flex", "flash", "client-server", "" ]
I'm trying to make the `add_day` function work, but I'm having some trouble. Note that I can't make any changes to the `struct` (it's very simplistic) because the point of the exercise is to make the program work with what's given. The code is ``` #include "std_lib_facilities.h" struct Date{ int y, m, d; Date(int y, int m, int d); void add_day(int n); }; void Date::add_day(int n) { d+=n; } ostream& operator<<(ostream& os, const Date& d) { if(d.m<1 || d.m>12 || d.d<1 || d.d>31) cout << "Invalid date: "; return os << '(' << d.y << ',' << d.m << ',' << d.d << ')'; } int main() { Date today(1978,6,25); today.add_day(1); cout << today << endl; keep_window_open(); } ``` I'm getting a linker error that says `undefined reference to Date::Date(int,int,int)`, but I can't figure out what's wrong. It seems like it's something to do with the `Date` constructor, but I'm not sure what. I'd also like to add in a line of code for tomorrow like ``` Date tomorrow = today.add_day(1); ``` but I've got a feeling that since add\_day is a void type there will be a conversion issue. Any help would be appreciated - thanks. P.S. Don't worry about adding days at the end of the month. It's something that's going to be implemented later.
The linker error is because you are not defining the constructor. ``` Date::Date( int yr, int mo, int day ) : y(year), m(month), d(day) { } ``` For the add\_day question: you are correct that you need to change the return type. It should return a Date object. You can construct a new Date object and return it with the day value incremented or just increment the day value and return \*this.
You have a constructor declared ``` Date(int y, int m, int d); ``` but you never wrote the definition for the constructor. Presumably you will want to add some code like ``` Date::Date(int y, int m, int d):y(y),m(m),d(d) { } ``` Additionally, ``` Date tomorrow = today.add_day(1); ``` `Date::add_day(int)` must return a new day for this to work. ``` Date Date::add_day(int n) { d+=n; return *this; } ``` This will return a copy of `this` after modifying it.
Class issue, adding a day
[ "", "c++", "date", "linker", "" ]
Does anyone have an idea how I can disable Drag & Drop for all my TextBox Elements? I found something [here](http://www.switchonthecode.com/tutorials/wpf-snippet-disabling-dragging-from-a-textbox), but that would need me to run a loop for all Elements.
You can easily wrap what this article describes into a attached property/behaviours... ie. TextBoxManager.AllowDrag="False" (For more information check out these 2 CodeProject articles - [Drag and Drop Sample](http://www.codeproject.com/KB/WPF/WPFDragDrop.aspx) and Glass Effect Sample[link text](http://www.codeproject.com/KB/WPF/WPFGlass.aspx)) Or try out the new Blend SDK's Behaviors **UPDATE** * Also read [this](http://wekempf.spaces.live.com/feed.rss) article by Bill Kempf about attached behaviors * And as kek444 pointed out in the comments, you then just create a default style for textbxo whit this attached property set!
Use the following after InitializeComponent() ``` DataObject.AddCopyingHandler(textboxName, (sender, e) => { if (e.IsDragDrop) e.CancelCommand(); }); ```
WPF/C#: Disable Drag & Drop for TextBoxes?
[ "", "c#", "wpf", "textbox", "drag-and-drop", "" ]
Whenever I read an article on linq to entities, I sounds like I should embed my business logic in the generated entity-classes. This would means that the "user" of the business-objects (controller, service-layer, ...) would have to know about the datacontext-object that's needed to use linq. It would also mean that the DAL-logic and the business-logic will be mixed up. A lot of microsoft examples use some kind of DTO-approach. I'm not a big fan of the DTO pattern. So should I let the business-object encapsulate the linq-entity and provide access to it using properties, or should I stick with the DTO pattern? What are your suggestions? Thanks
The entity model generates *partial* classes. In a project of mine I'm using an entity model inside a class library and added a few .cs files to it that add functionality to the default entity classes. (Mostly functions related to error and message logging to a database table and a method to import/export all data to XML.) But true business logic is located in a second class library that refers to this entity class library. --- Let's explain. First I created an entity model from a database. It contains a list of company names and addresses. I do this by choosing "New project|Class library" and then add an ADO.NET Entity Data Model to this library. The Entity model will be linked to my SQL Server database, importing the tables I need and auto-creates classes for the tables I want to access. I then add a second .cs file for every table that I want to expand. This would be a few raw methods that are strongly linked to the database. (Mostly import/export methods and error logging.) This I will call Entity.Model, which will compile to Entity.Model.dll. Then I add a second project which will contain the business logic. Again, I use "New project|Class library" to create it and add Entity.Model.dll to it's references. I then start writing classes which will translate the database-specific classes to more logical classes. In general, I would not have to make many changes except that I will protect or hide certain fields and add a few calculated fields. The business logic would only expose the functionality that I want to access from my client application and not a single method more. Thus, if I don't allow the client to delete companies then the "Delete" function in the entity model will *not* be exposed in the business layer. And maybe I want to send a notification when a company changes their address, so I'll add an event that gets triggered when the address field of the company is changed. (Which will write a message log or whatever.) I'll call this business.logic and it compiles to Business.Logic.dll. Finally, I'll create the client application and will add a reference to Business.Logic.dll. (But NOT to the entity model.) I can now start to write my application and access the database through the business layer. The business layer will do validations, trigger a few events and do whatever else in addition to modifying the database through the entity model. And the entity model just serves to keep the database relations simple, allowing me to "walk through" the data through all foreign links in the database.
I prefer to wrap calls to the entity classes in business classes. (Call it BC for short.) Each BC has several constructors, one or more of which allows the context to be passed to it. This allows one BC to call another BC and load related data in the same context. This also makes working with collections of BCs that need a shared context simpler. In the constructors that don't take a context, I create a new context in the constructor itself. I make the context available through a read-only property that other BCs can access. I write using the MVVM pattern. The nice thing about this approach is that so far I have been able to write my viewmodels without ever refering to the data context, just the BCs that form my models. Hence if I need to modify my data access (replace entity framework, or upgrade to version 4 when it is out of beta) my views and viewmodels are isolated from the changes required in the BCs. Not sure this is the best approach, but so far I have liked the results. It does take tweaking to get the BCs designed correctly, but I end up with a flexible, extensible, and maintainable set of classes.
Linq to entities and business logic
[ "", "c#", ".net", "architecture", "linq-to-entities", "" ]
In .Net, given a type name, is there a method that tells me in which assembly (instance of System.Reflection.Assembly) that type is defined? I assume that my project already has a reference to that assembly, just need to know which one it is.
Assembly.GetAssembly assumes you have an instance of the type, and Type.GetType assumes you have the fully qualified type name which includes assembly name. If you only have the base type name, you need to do something more like this: ``` public static String GetAssemblyNameContainingType(String typeName) { foreach (Assembly currentassembly in AppDomain.CurrentDomain.GetAssemblies()) { Type t = currentassembly.GetType(typeName, false, true); if (t != null) {return currentassembly.FullName;} } return "not found"; } ``` This also assumes your type is declared in the root. You would need to provide the namespace or enclosing types in the name, or iterate in the same manner.
``` Assembly.GetAssembly(typeof(System.Int32)) ``` Replace `System.Int32` with whatever type you happen to need. Because it accepts a `Type` parameter, you can do just about anything this way, for instance: ``` string GetAssemblyLocationOfObject(object o) { return Assembly.GetAssembly(o.GetType()).Location; } ```
How to get the assembly (System.Reflection.Assembly) for a given type in .Net?
[ "", "c#", ".net", "reflection", ".net-assembly", "" ]
I have a transaction that contains multiple SQL Statements (INSERT, UPDATE and/or DELETES). When executing, I want to ignore Duplicate Error statements and continue onto the next statement. What's the best way of doing that?
Although my emphatic advice to you is to structure your sql so as to not attempt duplicate inserts (Philip Kelley's snippet is probably what you need), I want to mention that an error on a statement doesn't necessarily cause a rollback. Unless `XACT_ABORT` is `ON`, a transaction will not automatically rollback if an error is encountered unless it's severe enough to kill the connection. `XACT_ABORT` defaults to `OFF`. For example, the following sql successfully inserts three values into the table: ``` create table x ( y int not null primary key ) begin transaction insert into x(y) values(1) insert into x(y) values(2) insert into x(y) values(2) insert into x(y) values(3) commit ``` Unless you're setting `XACT_ABORT`, an error is being raised on the client and causing the rollback. If for some horrible reason you can't avoid inserting duplicates, you ought to be able to trap the error on the client and ignore it.
I think you are looking for the IGNORE\_DUP\_KEY option on your index. Have a look at IGNORE\_DUP\_KEY ON option documented at <http://msdn.microsoft.com/en-us/library/ms186869.aspx> which causes duplicate insertion attempts to produce a warning instead of an error.
How to Ignore "Duplicate Key" error in T-SQL (SQL Server)
[ "", "sql", "sql-server", "" ]
I heard this phrase when I was listening to dot net rocks this morning. apparently linq to sql only supports one to one table mapping.
One to one, one to many, many to many are terms that define the multiplicity of relationships. <http://www.databaseprimer.com/relationship.html>
One-to-one mapping means that one parent row can have only one child row. There are different kinds of mapping when you consider design One-To-Many: A car has many parts Many-To-One: Many cars use the same part Many-To-Many: Many parts are used in many cars One-To-One: One part is used only once in one car
what does one to one table mapping mean?
[ "", "sql", "sql-server", "database", "database-design", "" ]
When loading tables from SAS to Teradata, SAS loads the data (usually using the FASTLOAD facility) and then continues down the script. However, I often get critical errors because SAS says the data is loaded, but Teradata is still assembling the data within the table. So the data is in the database, but not ready to be used. I have yet to find a way to know if the data is ready for processing with other tables. I have been successful at using a sleep command, but that is arbitrary and unreliable (because who knows how long it will take). How would you fix this problem?
I would try the following: 1. Test if the [DBCOMMIT=](http://support.sas.com/documentation/cdl/en/acreldb/61890/HTML/default/a001371531.htm) data set option can help 2. If 1. doesn't help, use a loop over the [OPEN](http://support.sas.com/onlinedoc/913/getDoc/en/lrdict.hlp/a000148395.htm) function to query if the table is ready, like this: ``` data _null_; dsid=0; do i=1 to 3600 while(dsid<=0); ts=SLEEP(1,1); dsid=OPEN('TERADATA.MYTABLE','I'); end; if dsid then dsid=CLOSE(dsid); run; ```
Could you sleep, try to query, catch any error and loop until ready?
Loading data from SAS to Teradata - When is it ready?
[ "", "sql", "sas", "etl", "teradata", "" ]
I added a custom user field in Liferay, and set a value on a specific user. How can I access this value programmatically? If I try this, I always get null: ``` String customAttr = (String)user.getExpandoBridge().getAttribute("customAttr"); ``` `user.getExpandoBridge().getAttribute("customAttr")` returns a value of Type `java.IO.Serializable`. Maybe the cast here is wrong? But the Custom Attribute does exist (following code prints out the attribute key): ``` for (Enumeration<String> attrs = user.getExpandoBridge().getAttributeNames(); attrs.hasMoreElements();) _log.info("elem: '" + attrs.nextElement() + "'"); ``` Somehow I miss the point here....
It was a security problem... In `com.liferay.portlet.expando.service.impl.ExpandoValueServiceImpl.getData(String className, String tableName, String columnName, long classPK)`: ``` if (ExpandoColumnPermission.contains( getPermissionChecker(), column, ActionKeys.VIEW)) { return expandoValueLocalService.getData( className, tableName, columnName, classPK); } else { return null; } ``` I only had to set the view permisson on the custom expando value, and everything worked fine.
I know it's a bit late, but for those still trying to figure out why a custom field turns out to be null (although it is clearly set and visible in Liferay), please make sure first that the custom field has the permissions properly set (Control Panel -> Custom fields -> User -> choose the appropiate custom field and click Action -> Permissions). By default, the Owner has all rights, but in my case, for example, I needed a View permission with a Guest account (user in the process of logging in). Hope this helps.
Getting a custom user field value (expando) in Liferay
[ "", "java", "liferay", "expando", "" ]
I am writing a small class for driving integration testing of a win form application. The test driver class has access to the main Form and looks up the control that needs to be used by name, and uses it to drive the test. To find the control I am traversing the Control.Controls tree. However, I get stuck when I want to get to controls in a dialog window (a custom form shown as a dialog). How can I get hold of it?
You can get a reference to the currently active form by using the static [`Form.ActiveForm`](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.activeform.aspx) property. Edit: If no `Form` has the focus, `Form.ActiveForm` will return `null`. One way to get around this is to use the `Application.OpenForms` collection and retrieve the **last** item, witch will be the active `Form` when it is displayed using `ShowDialog`: ``` // using Linq: var lastOpenedForm = Application.OpenForms.Cast<Form>().Last() // or (without Linq): var lastOpenedForm = Application.OpenForms[Application.OpenForms.Count - 1] ```
I'm not sure if you can access controls on a pre-built dialog box; they seem all packaged together. You may have more luck building a dialog box of your own that does what you want it to do. Then you can access the .Controls inside of it.
How can I get the reference to currently active modal form?
[ "", "c#", ".net", "winforms", "" ]
This bug took me a while to find... Consider this method: ``` public void foo(Set<Object> set) { Object obj=set.iterator().next(); set.remove(obj) } ``` I invoke the method with a non-empty hash set, but no element will be removed! Why would that be?
For a HashSet, this can occur if the object's hashCode changes after it has been added to the set. The HashSet.remove() method may then look in the wrong Hash bucket and fail to find it. ~~This probably wouldn't happen if you did iterator.remove()~~, but in any case, storing objects in a HashSet whose hashCode can change is an accident waiting to happen (as you've discovered).
Puzzle? If `Object.hashCode`, `Object.equals` or the "hash set" were implemented incorrectly (see for instance, `java.net.URL` - use `URI`). Also if the set (directly or indirectly) contains itself, something odd is likely to happen (exactly what is implementation and phase of the moon dependent).
Why won't it remove from the set?
[ "", "java", "puzzle", "" ]
I have installed Apache Tomcat 6 as a Service in a Windows XP computer (French) My problem is that Tomcat itself and all webapps (Sonar and Hudson) now show french messages. I want English messages of course so I went to the "Regional Settings" window in Control panel and changed everything to English (US) Tomcat however is **still** in French. Nothing changed at all. I suspect that because it runs as a service it does not pick the settings from control panel. So is there any way to trick the Tomcat JVM so that it uses English instead of French? I have sys admin access to the machine (XP PRO French) Thank you
You need to set `user.language` and `user.region` appropriately, e.g. ``` java -Duser.language=en -Duser.region=CA ``` in your Tomcat startup (probably `catalina.bat`). Check [this link](http://java.sun.com/developer/technicalArticles/J2SE/locale/) for more info, and for references to the sets of valid ISO codes for the above.
The Tomcat manager was showing up in French for me, despite the fact that I tried some of the suggestions above. The issue turned out to be browser specific. Chrome had "French" listed as one of my languages and as soon as I removed it from the list in preferences and refreshed the page, Tomcat showed up in English. I hope that will be helpful for anybody else in the future who is having this sort of problem.
Setting default locale for Tomcat Service in Windows XP
[ "", "java", "tomcat", "service", "locale", "" ]
Pythons installed under WinXP have dirs like DLLs, DOC, include, etc. but python (2.5) installed with cygwin is a bare python.exe. My motivation for asking is that 'things' under XP don't seem to be finding 'other things' under cygwin and vice versa, I want to start developing with Qt, I like shells, and I do not like MS; I thought if I got all the components under one roof, I could finally start to have scripts find executables which could find files and such. 1. Can I simply copy the contents of an XP installation into the cygwin tree? 2. Is the XP flavor of Python different from the cygwin flavor? (Same CPU, he pointed out, naively.) 3. Someone must work with a full-fledged (if snakes had feathers...) Python from within cygwin; how is it done? Disclaimer 1: I have never compiled anything under XP or cygwin; had hoped not to have to go there, hence, python in the first place. Disclaimer 2: sorry if this is a ServerFault question, but they seemed to be system people over there and this is (in my case) a lowly desktop.
I use Python from within cygwin, but I don't use the version that cygwin gives you the option of installing as I don't have the control over version number used that I need (we use an older version at work). I have my python version installed via the windows installer (the xp version as you put it) and add the /cygdrive/c/Python2x directory to my PATH environment variable.
This probably has little value, but... I found myself in this exact situation -- we use ActivePython2.5 in production (pure windows environment) and I was trying to do my development within cygwin and cygwin's Python... After ripping out half of my hair, I have now switched over to Console2, gvim, iPython and ActivePython2.5. I'm less than thrilled dealing with Windows tools (and their concomitant warts), but at least I'm not getting in my own way when it comes to development. For a while I found I was spending more time trying to get my tools to play nice than actually getting any work done. Good luck on this one.
Best way to have full Python install under cygwin/XP?
[ "", "python", "windows-xp", "cygwin", "" ]
I cannot understand why this piece of code does not compile: ``` namespace A { class F {}; // line 2 class H : public F {}; } namespace B { void F(A::H x); // line 7 void G(A::H x) { F(x); // line 9 } } ``` I am using `gcc 4.3.3`, and the error is: ``` s3.cpp: In function ‘void B::G(A::H)’: s3.cpp:2: error: ‘class A::F’ is not a function, s3.cpp:7: error: conflict with ‘void B::F(A::H)’ s3.cpp:9: error: in call to ‘F’ ``` I think that because in line 9 there is no namespace prefix, `F(x)` should definitively mean only `B::F(x)`. The compiler tries to cast `x` into its own superclass. In my understanding it should not. Why does it do that?
That's because compiler will search function in the same namespace its arguments from. Compiler found there `A::F` identifier but it is not a function. In result you'll get the error. It is standard behaviour as far as I can remember. > **3.4.2 Argument-dependent name lookup** > When an unqualified name is used as the postfix-expression in a function call (5.2.2), other namespaces not considered during the usual unqualified lookup (3.4.1) may be searched, and namespace-scope friend function declarations (11.4) not otherwise visible may be found. These modifications to the search depend on the types of the arguments (and for template template arguments, the namespace of the template argument). > > For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero or more associated classes to be considered. The sets of namespaces and classes is determined entirely by the types of the function arguments (and the namespace of any template template argument). > Typedef names and using-declarations used to specify the types do not contribute to this set. The sets of namespaces and classes are determined in the following way... This rule allows you to write the following code: ``` std::vector<int> x; // adding some data to x //... // now sort it sort( x.begin(), x.end() ); // no need to write std::sort ``` **And finally: Because of [Core Issue 218](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#218) some compilers would compile the code in question without any errors.**
Have you tried using other compilers yet? There is a [gcc bug report](http://gcc.gnu.org/ml/gcc-bugs/2006-01/msg02891.html) here which is suspended (whatever that means). EDIT: After some research, I found this [more official bug](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17365).
Namespace Clashing in C++
[ "", "c++", "namespaces", "polymorphism", "" ]
If I wanted to take a first name / last name string separated by a comma and change the order, how might I go about that? last name, firstname should be changed to firstname lastname (without the comma) Thanks.
This should do it. ``` $string = 'last,first'; list($last,$first) = explode( ",", $string ); echo $first . ' ' . $last; ```
If you wanted to get it done in a spiffy one-liner you could do this: ``` <?php $name = "Smith, Dave"; echo implode(' ', array_reverse(explode(',', $name))); ```
How can I easily change the order of a string. I need a string function
[ "", "php", "" ]
A piece of javascript code I'm working on is causing the nasty "Operation Aborted" message in IE. I am well aware that you cannot modify the DOM until after it has loaded. Sure enough the line of javascript code causing the error is the one which appends a new div tag to the body. However the function which the line is located within is called via FastInit.addOnLoad! I thought this meant the function would be called after the DOM was ready. Is there a better solution to this problem that using FastInit?
N.B. SO is playing silly buggers with the formatting; sorry about that. The "Operation Aborted" error occurs when you try to modify the grandparent element of the script element. So, for example, the following code will cause it because the script is attempting to modify the body from a child div, meaning it is trying to modify its grandparent element: ``` <body> <div id="foo"> <script type="text/javascript"> var newThing = document.createElement("div"); /* ### The next line will cause the error ### */ document.body.appendChild(newThing); <script> </div> </body> ``` The same code changed to: ``` <body> <div id="foo"> </div> <script type="text/javascript"> var newThing = document.createElement("div"); /* ### The next line will NOT cause an error ### */ document.body.appendChild(newThing); <script> </body> ``` would *not* cause the error, as the script is now modifying its parent, which IE can handle. The most common reason for this happening is that you have failed to close a `div` (or other element) further up the page; find the missing close tag and you'll fix it. Alternatively, if your script actually *is* inside another element, move it out so it is a child of the `body`.
I'm not sure about FastInit, but I just answered a similar question about waiting for the DOM to be ready here: [Initiate onclick faster than with document.onload](https://stackoverflow.com/questions/1153858/initiate-onclick-faster-than-with-document-onload/1153988#1153988) Basically, you can do it in IE by using the defer attribute on your script tag: ``` <script type="text/javascript" defer> </script> ``` This will delay parsing the script until after the DOM is ready.
IE7 "Operation Aborted" even with FastInit?
[ "", "javascript", "internet-explorer", "dom", "" ]
Ok, If you can answer this question, you deserve the nobel peace prize. Anyways, here's the situation. I'm using Slicehost dot net, and I have 2 slices (two different IPs). One slice is my mail server and the other is my normal website. I'm running Ubuntu (8.04 or 8.10, something like that, it shouldn't matter). What I'm trying to do is access the MySQL database on the Mail server from the other slice. I'm trying to do that with PHP. I really appreciate any help.
[`mysql_connect()`](http://php.net/mysql_connect) ``` $resource = mysql_connect('other-server-address.com', 'username', 'password'); ``` The first parameter is the mysql server address. > **Server Param** > > The MySQL server. It can also include > a port number. e.g. "hostname:port" or > a path to a local socket e.g. > ":/path/to/socket" for the localhost. > > If the PHP directive > mysql.default\_host is undefined > (default), then the default value is > 'localhost:3306'. In SQL safe mode, > this parameter is ignored and value > 'localhost:3306' is always used. Unless I'm misunderstanding... this setup is pretty common. Any trouble you're having might be related to the following: * Firewall settings * [Grant access to the mysql user to connect from the other host](https://stackoverflow.com/questions/282084/php-access-to-remote-database) * [my.ini settings not allowing outside connections](https://stackoverflow.com/questions/53491/how-do-i-enable-external-access-to-mysql-server) Some other related SO questions: * [Connecting to MySQL from other machines](https://stackoverflow.com/questions/804772/connecting-to-mysql-from-other-machines) * [How do I enable external access to MySQL Server?](https://stackoverflow.com/questions/53491/how-do-i-enable-external-access-to-mysql-server) * [php access to remote database](https://stackoverflow.com/questions/282084/php-access-to-remote-database) * [How to make mysql accept connections externally](https://stackoverflow.com/questions/938047/how-to-make-mysql-accept-connections-externally) * [Remote mysql connection](https://stackoverflow.com/questions/670949/remote-mysql-connection)
Assuming your mail server is at IP 192.168.1.20 and web server is 192.168.1.30 First of all you need to allow the web server to access the mysql database on your Mail server . On 192.168.1.20 you run the mysql command and grant access on the database needed to your web server ``` mysql> grant all on mydb.* to 'someuser'@'192.168.1.30' identified by 'secretpass; ``` Your PHP code connects to that database with something like: ``` $conn = mysql_connect('192.168.1.20', 'someuser', 'secretpass'); ```
How do I access another MySQL Database from another IP Address with PHP?
[ "", "php", "mysql", "" ]
I am parsing some XML with the elementtree.parse() function. It works, except for some utf-8 characters(single byte character above 128). I see that the default parser is XMLTreeBuilder which is based on expat. Is there an alternative parser that I can use that may be less strict and allow utf-8 characters? This is the error I'm getting with the default parser: ``` ExpatError: not well-formed (invalid token): line 311, column 190 ``` The character causing this is a single byte x92 (in hex). I'm not certain this is even a valid utf-8 character. But it would be nice to handle it because most text editors display this as: í **EDIT**: The context of the character is: canít , where I assume it is supposed to be a fancy apostraphe, but in the hex editor, that same sequence is: 63 61 6E 92 74
I'll start from the question: "Is there an alternative parser that I can use that may be less strict and allow utf-8 characters?" All XML parsers will accept data encoded in UTF-8. In fact, UTF-8 is the default encoding. An XML document may start with a declaration like this: ``` `<?xml version="1.0" encoding="UTF-8"?>` ``` or like this: `<?xml version="1.0"?>` or not have a declaration at all ... in each case the parser will decode the document using UTF-8. However your data is NOT encoded in UTF-8 ... it's probably Windows-1252 aka cp1252. If the encoding is not UTF-8, then either the creator should include a declaration (or the recipient can prepend one) or the recipient can transcode the data to UTF-8. The following showcases what works and what doesn't: ``` >>> import xml.etree.ElementTree as ET >>> from StringIO import StringIO as sio >>> raw_text = '<root>can\x92t</root>' # text encoded in cp1252, no XML declaration >>> t = ET.parse(sio(raw_text)) [tracebacks omitted] xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 9 # parser is expecting UTF-8 >>> t = ET.parse(sio('<?xml version="1.0" encoding="UTF-8"?>' + raw_text)) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 47 # parser is expecting UTF-8 again >>> t = ET.parse(sio('<?xml version="1.0" encoding="cp1252"?>' + raw_text)) >>> t.getroot().text u'can\u2019t' # parser was told to expect cp1252; it works >>> import unicodedata >>> unicodedata.name(u'\u2019') 'RIGHT SINGLE QUOTATION MARK' # not quite an apostrophe, but better than an exception >>> fixed_text = raw_text.decode('cp1252').encode('utf8') # alternative: we transcode the data to UTF-8 >>> t = ET.parse(sio(fixed_text)) >>> t.getroot().text u'can\u2019t' # UTF-8 is the default; no declaration needed ```
It looks like you have CP1252 text. If so, it should be specified at the top of the file, eg.: ``` <?xml version="1.0" encoding="CP1252" ?> ``` This does work with ElementTree. If you're creating these files yourself, don't write them in this encoding. Save them as UTF-8 and do your part to help kill obsolete text encodings. If you're receiving CP1252 data with no encoding specification, and you know for sure that it's always going to be CP1252, you can just convert it to UTF-8 before sending it to the parser: ``` s.decode("CP1252").encode("UTF-8") ```
Alternative XML parser for ElementTree to ease UTF-8 woes?
[ "", "python", "xml", "utf-8", "elementtree", "" ]
I'm trying to implement a fairly simple [card game](http://www.sirlin.net/yomi) in Python so that two players can play together other the Internet. I have no problem with doing the GUI, but I don't know the first thing about how to do the networking part. A couple libraries I've found so far: * [PyRO](http://pyro.sourceforge.net/manual/PyroManual.html): seems nice and seems to fit the problem nicely by having shared Card objects in various states. * [Twisted](http://twistedmatrix.com/trac/) with [pyglet-twisted](http://code.google.com/p/pyglet-twisted/): this looks powerful but complicated; I've used Pyglet before though so maybe it wouldn't be too bad. Can anyone recommend the most appropriate one for my game (not necessarily on this list, I've probably missed lots of good ones)?
Both of those libraries are very good and would work perfectly for your card game. Pyro might be easier to learn and use, but Twisted will scale better if you ever want to move into a very large number of players. Twisted can be daunting at first but there are some books to help you get over the hump. The are some other libraries to choose from but the two you found are mature and used widely within the Python community so you'll have a better chance of finding people to answer any questions. My personal recommendation would be to use Pyro if you're just wanting to play around with networking but go with Twisted if you have grand plans for lots of players on the internet.
If you decide you don't want to use a 3rd party library, I'd recommend the [`asynchat module`](http://docs.python.org/library/asynchat.html) in the standard library. It's perfect for sending/receiving through a simple protocol.
Python networking library for a simple card game
[ "", "python", "networking", "" ]
I have a windows forms application that is deployed to two different locations. * Intranet - ClickOnce * Internet - Installed on a citrix farm through Windows installer I display ClickOnce version number for click-once deployed version`ApplicationDeployment.IsNetworkDeployed`. ``` if (ApplicationDeployment.IsNetworkDeployed) return ApplicationDeployment.CurrentDeployment.CurrentVersion; ``` But for the non-click application, I am not sure how to retrieve clickonce version unless I hardcode the version number in assembly info. Is there an automatic way of retrieve ClickOnce version number for non-clickonce deployed version?
No I do not believe that there is a way. I believe the ClickOnce information comes from the manifest which will only be available in a ClickOnce deployment. I think that hard coding the version number is your best option.
1. **Add an assembly reference to `System.Deployment` to your project.** 2. **Import the namespace in your class file:** VB.NET: ``` Imports System.Deployment.Application ``` C#: ``` using System.Deployment.Application; ``` 3. **Retrieve the ClickOnce version from the `CurrentVersion` property.** You can obtain the current version from the `ApplicationDeployment.CurrentDeployment.CurrentVersion` property. This returns a [`System.Version`](http://msdn.microsoft.com/en-us/library/system.version.aspx) object. Note (from MSDN): > *`CurrentVersion` will differ from `UpdatedVersion` if a new update has > been installed but you have not yet called `Restart`. If the deployment > manifest is configured to perform automatic updates, you can compare > these two values to determine if you should restart the application.* NOTE: The `CurrentDeployment` static property is only valid when the application has been deployed with ClickOnce. Therefore before you access this property, you should check the `ApplicationDeployment.IsNetworkDeployed` property first. It will always return a false in the debug environment. VB.NET: ``` Dim myVersion as Version If ApplicationDeployment.IsNetworkDeployed Then myVersion = ApplicationDeployment.CurrentDeployment.CurrentVersion End If ``` C#: ``` Version myVersion; if (ApplicationDeployment.IsNetworkDeployed) myVersion = ApplicationDeployment.CurrentDeployment.CurrentVersion; ``` 4. **Use the `Version` object:** From here on you can use the version information in a label, say on an "About" form, in this way: VB.NET: ``` versionLabel.Text = String.Concat("ClickOnce published Version: v", myVersion) ``` C#: ``` versionLabel.Text = string.Concat("ClickOnce published Version: v", myVersion); ``` (`Version` objects are formatted as a four-part number (major.minor.build.revision).)
How to display ClickOnce Version number on Windows Forms
[ "", "c#", ".net", "deployment", "clickonce", "" ]
I can't see where I'm going wrong with the code below, its probably something obvious but I'm too blind to see it at this stage. I'm passing a date of "01/01/2009" to an instance of calendar. I then try and set the month to 2 for March and the output I see is formatted: 01/01/2009 cal month: 2 ``` cal.set( Calendar.MONTH, mth ); //mth = int 2 log.debug("formatted: " + formatter.format(cal.getTime())); log.debug("cal month: "+Integer.valueOf(cal.get(Calendar.MONTH)).toString()); ``` When I set the Calendar.DAY to the max value the date comes out as 31/01/2009 Why does my setting of the Month not take?
I'll look into exactly what's going on, but the general rule of thumb is: **don't use java.util.{Date,Calendar}**. Use [Joda Time](http://joda-time.sourceforge.net/) instead... it's *so* much cleaner... EDIT: I can't reproduce your issue at the moment. I'd still recommend using Joda, but if you could post a short but *complete* program to demonstrate the problem, we may be able to work out what's going wrong. EDIT: Based on another comment, I wonder whether your formatter is wrong... are you really using "dd/mm/yyyy" rather than "dd/MM/yyyy"? "mm" means minutes, not months.
We ran into this and the result was that the value you set doesn't get used until you actually try to 'get' the value from Calendar. We were puzzled because using the debugger the value never seemed to get set, but when you actually 'get' it, it works. <http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html> Getting and Setting Calendar Field Values The calendar field values can be set by calling the set methods. Any field values set in a Calendar will not be interpreted until it needs to calculate its time value (milliseconds from the Epoch) or values of the calendar fields. Calling the get, getTimeInMillis, getTime, add and roll involves such calculation.
Java Calendar.set not giving correct result
[ "", "java", "date", "calendar", "" ]
**Problem:** to open a new window with the select -option ``` <form onsubmit="return handleSubmit()" target="_blank" method="get" name="moduleForm" id="moduleForm"> <font size=2 face = verdana color= #0000ff ><b>Search</b></font> <select name="allSelect" id="allSelect"> <optgroup label="Historical"> <option value="http://www.something.com/cse?cx=0000000000000&sa=Search&q=">Open in a new window 1</option> <option value="http://www.google.com/cse?cx=0000000000000000A-cmjrngmyku&ie=UTF-8&sa=Search&q=">Open in a new window 2</option> </optgroup> </select> <input type="text" name="allQuery" id="allQuery" size="22" /> <input type="submit" value=" Go " /> ``` **Question:** How can I open the content to a new window with a select-box?
Modify [your `handleSubmit` function](http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGNawvAEM) as follows: ``` function handleSubmit() { var form = _gel("moduleForm"), elm = _gel("allQuery"), selectElm = _gel("allSelect"); if (elm != "" && selectElm != "") { var query = elm.value; var searchUrl = selectElm.value; if (query != "" && searchUrl != "") { searchUrl += escape(query); window.open(searchUrl, form.target || "_blank"); } } return false; } ```
You can open your links by window.open() : ``` <select name="allSelect" id="allSelect"> <optgroup label="Historical"> <option value="http://www.something.com/cse?cx=0000000000000&sa=Search&q=">Open in a new window 1</option> <option value="http://www.google.com/cse?cx=0000000000000000A-cmjrngmyku&ie=UTF-8&sa=Search&q=">Open in a new window 2</option> </optgroup> </select> <input type="button" value="open in a new window" onclick="window.open(document.getElementById(allSelect).value);" /> ```
HTML: target="_blank" for a drop-down list
[ "", "javascript", "html", "" ]
I want to return an age in years as an int in a Java method. What I have now is the following where getBirthDate() returns a Date object (with the birth date ;-)): ``` public int getAge() { long ageInMillis = new Date().getTime() - getBirthDate().getTime(); Date age = new Date(ageInMillis); return age.getYear(); } ``` But since getYear() is deprecated I'm wondering if there is a better way to do this? I'm not even sure this works correctly, since I have no unit tests in place (yet).
JDK 8 makes this easy and elegant: ``` public class AgeCalculator { public static int calculateAge(LocalDate birthDate, LocalDate currentDate) { if ((birthDate != null) && (currentDate != null)) { return Period.between(birthDate, currentDate).getYears(); } else { return 0; } } } ``` A JUnit test to demonstrate its use: ``` public class AgeCalculatorTest { @Test public void testCalculateAge_Success() { // setup LocalDate birthDate = LocalDate.of(1961, 5, 17); // exercise int actual = AgeCalculator.calculateAge(birthDate, LocalDate.of(2016, 7, 12)); // assert Assert.assertEquals(55, actual); } } ``` Everyone should be using JDK 8 by now. All earlier versions have passed the end of their support lives.
Check out [Joda](http://joda-time.sourceforge.net/), which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API). e.g. ``` LocalDate birthdate = new LocalDate (1970, 1, 20); LocalDate now = new LocalDate(); Years age = Years.yearsBetween(birthdate, now); ``` which is as simple as you could want. The pre-Java 8 stuff is (as you've identified) somewhat unintuitive. EDIT: Java 8 has [something very similar](http://docs.oracle.com/javase/tutorial/datetime/) and is worth checking out. EDIT: This answer pre-dates the Java 8 date/time classes and is not current any more.
How do I calculate someone's age in Java?
[ "", "java", "date", "calendar", "" ]
For eaxmple, LINQ to SQL is sending the following: ``` exec sp_executesql N'SELECT [t0].[HomeID], [t0].[Bedrooms], [t0].[ImageURL], [t0].[Price], [t0].[Available], [t0].[Description] FROM [dbo].[Homes] AS [t0] WHERE ([t0].[Description] LIKE @p0) AND ([t0].[Available] = @p1) AND ([t0].[Price] >= @p2) AND ([t0].[Price] <= @p3) ORDER BY [t0].[Price] DESC', N'@p0 nvarchar(4000),@p1 int,@p2 int,@p3 int', @p0=N'%private%', @p1=1, @p2=200000, @p3=750000 ``` Why does it use sp\_executesql?
This notation allows the runtime compiled TSQL statement to be re-used with different parameters; i.e. the statement only gets compiled once which improves efficiency.
**EDIT, oops did I say paramterization instead of parameter replacement, thanks stephbu** sp\_executesql is preferred over execute because it supports parameter substitution, and tends to perform more efficiently.
Why does LINQ send sp_executesql instead of directly executing the SQL?
[ "", "sql", "linq-to-sql", "" ]
``` private void button1_Click(object sender, EventArgs e) { string name; name = textBox5.Text; SqlConnection con10 = new SqlConnection("con strn"); SqlCommand cmd10 = new SqlCommand("select * from sumant where username=@name"); cmd10.Parameters.AddWithValue("@name",name); cmd10.Connection = con10; cmd10.Connection.Open();//line 7 SqlDataReader dr = cmd10.ExecuteReader(); } if ( textBox2.Text == dr[2].ToString()) { //do something; } ``` When I debug until line 7, it is OK, but after that `dr` throws an exception: > Invalid attempt to read when no data is present. I don't understand why I'm getting that exception, since I do have data in the table with username=sumant. Please tell me whether the 'if' statement is correct or not. And how do I fix the error?
You have to call [`DataReader.Read()`](https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader.read?view=dotnet-plat-ext-6.0#system-data-sqlclient-sqldatareader-read) to fetch the result: ``` SqlDataReader dr = cmd10.ExecuteReader(); if (dr.Read()) { // read data for single/first record here } ``` `DataReader.Read()` returns a `bool` indicating if there are more blocks of data to read, so if you have more than 1 result, you can do: ``` while (dr.Read()) { // read data for each record here } ```
You have to call `dr.Read()` before attempting to read any data. That method will return false if there is nothing to read.
Invalid attempt to read when no data is present
[ "", "c#", "ado.net", "sqldatareader", "" ]
I have an hour field in a database like 1.4, 1.5, 1.7 that I need to convert back to HH:MM. What is the easiest way to do this?
[`TimeSpan.FromHours`](http://msdn.microsoft.com/en-us/library/system.timespan.fromhours.aspx): ``` double value; TimeSpan t = TimeSpan.FromHours(value); ``` Example: ``` Console.WriteLine(TimeSpan.FromHours(1.4)); // prints 01:24:00 to the console. ```
The HH (hour) figure is the number before the decimal. To get the minutes figure, subtract the whole number portion so you only have the amount after the decimal, then multiply the fraction by 60 to get the minutes.
Decimal Hour into Time?
[ "", "c#", "asp.net", "" ]
I need to run through a List in reverse order using Java. So where this does it forwards: ``` for(String string: stringList){ //...do something } ``` Is there some way to iterate the stringList in reverse order using the *for each* syntax? For clarity: I know how to iterate a list in reverse order but would like to know (for curiosity's sake ) how to do it in the *for each* style.
The Collections.reverse method actually returns a new list with the elements of the original list copied into it in reverse order, so this has O(n) performance with regards to the size of the original list. As a more efficient solution, you could write a decorator that presents a reversed view of a List as an Iterable. The iterator returned by your decorator would use the ListIterator of the decorated list to walk over the elements in reverse order. For example: ``` public class Reversed<T> implements Iterable<T> { private final List<T> original; public Reversed(List<T> original) { this.original = original; } public Iterator<T> iterator() { final ListIterator<T> i = original.listIterator(original.size()); return new Iterator<T>() { public boolean hasNext() { return i.hasPrevious(); } public T next() { return i.previous(); } public void remove() { i.remove(); } }; } public static <T> Reversed<T> reversed(List<T> original) { return new Reversed<T>(original); } } ``` And you would use it like: ``` import static Reversed.reversed; ... List<String> someStrings = getSomeStrings(); for (String s : reversed(someStrings)) { doSomethingWith(s); } ```
For a list, you could use the [Google Guava Library](https://github.com/google/guava/): ``` for (String item : Lists.reverse(stringList)) { // ... } ``` Note that [`Lists.reverse`](http://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Lists.html#reverse(java.util.List)) *doesn't* reverse the whole collection, or do anything like it - it just allows iteration and random access, in the reverse order. This is more efficient than reversing the collection first. To reverse an arbitrary iterable, you'd have to read it all and then "replay" it backwards. (If you're not already using it, I'd *thoroughly* recommend you have a look at the [Guava](https://github.com/google/guava/). It's great stuff.)
Can one do a for each loop in java in reverse order?
[ "", "java", "reverse", "foreach", "" ]
Is there a easy way to accomplish the same thing in Python as xsl accomplishes with: ``` <xsl:strip-space elements="*"/> ``` So for instance in the following ``` for event, elem in ElementTree.iterparse("/tmp/example.xml"): if elem.tag == "example": print ElementTree.tostring(elem) ``` when the example nodes are printed out all the spaces and line feeds in the input file between children of the example node will be removed?
If you can use the [lxml](http://pypi.python.org/pypi/lxml) module, this becomes much easier. From [the lxml tutorial](http://lxml.de/tutorial.html#parser-objects): ``` >>> parser = etree.XMLParser(remove_blank_text=True) # lxml.etree only! >>> root = etree.XML("<root> <a/> <b> </b> </root>", parser) >>> etree.tostring(root) b'<root><a/><b> </b></root>' ```
I believe you need to explicitly manipulate the subtree to strip every text and tail: ``` from xml.etree import ElementTree for event, elem in ElementTree.iterparse("/tmp/example.xml"): if elem.tag == "example": subiter = ElementTree.ElementTree(elem).getiterator() for x in subiter: if x.text: x.text = x.text.strip() if x.tail: x.tail = x.tail.strip() print ElementTree.tostring(elem) ```
Stripping spaces between XML nodes with Python
[ "", "python", "xml", "xslt", "" ]
Say I have a regex that checks for alphanumeric. I now want to create another regex that checks for at least 1 number in the password. And I want to check if it has at least 1 non-alphanumeric character (somethign other than a letter or number). Should I just call each one seperatley, and if one fails return false or is there a way to combine them into 1 call?
Depends on exactly what criteria you're using, but it would probably be better to do a single pass through the string and set a number of flags based on what you've seen: * hasDigit * hasAlpha * hasSymbol * etc Then use these at the end to decide if the password is complex enough. **Even Better:** As lexu suggests, using counts instead of flags would allow greater flexibility.
I would compose small methods using &&: ``` internal bool HasDigit(string password) { .. } internal bool HasNonAlpha(string password) { .. } bool IsStrong(string password) { return HasDigit(password) && HasNonAlpha(password); } ```
Creating a regex to check for a strong password
[ "", "c#", "regex", "passwords", "" ]
Any recommendations for a good cross-platform library for reading ELF file debug information in DWARF format? I'd like to read the DWARF debug info in a Python program.
There's a new kid on the block - [pyelftools](https://github.com/eliben/pyelftools) - a pure Python library for parsing the ELF and DWARF formats. Give it a try. It aims to be feature-complete and is currently in active development, so any problems should be handled quickly and enthusiastically :-)
The concept of "ELF debug info" doesn't really exist: the ELF specification leaves the content of the .debug section deliberately unspecified. Common debug formats are STAB and [DWARF](http://dwarfstd.org/). A library to read DWARF is [libdwarf](http://www.prevanders.net/dwarf.html).
Library to read ELF file DWARF debug information
[ "", "python", "debugging", "elf", "dwarf", "" ]
Is there a standard and/or portable way to represent the smallest negative value (e.g. to use negative infinity) in a C(++) program? DBL\_MIN in float.h is the smallest *positive* number.
`-DBL_MAX` [in ANSI C](http://www.csse.uwa.edu.au/programming/ansic-library.html#float), which is defined in float.h.
Floating point numbers (IEEE 754) are symmetrical, so if you can represent the greatest value (`DBL_MAX` or [`numeric_limits<double>::max()`](http://en.cppreference.com/w/cpp/types/numeric_limits/max)), just prepend a minus sign. And then is the cool way: ``` double f; (*((uint64_t*)&f))= ~(1LL<<52); ```
minimum double value in C/C++
[ "", "c++", "c", "math", "" ]
I can't find a template for a linq to sql class in .net 2.0 project, based on what i know you can work with linq in .NET 2.0 as long as you have 3.5 in your development machine and ship system.core.dll with your application? so based on that how can I add a Linq to Sql model to my project when "Linq to Sql Classes" template is missing from the add new item window? **Edit:** Just to clear things up, This is a server application and the server will have .net 3.5 SP1. the only issues is that we can not upgrade the project to .net 3.5 at the moment.
I figured it out, All you have to do is add a new text file to the project, but change the extension from .txt to .dbml and it'll automatically be picked up by visual studio. it will even generate all the code behind for you.
If you ship System.Core with your application, it won't pick up future security fixes and won't have the optimized build installed (MS internally uses and profiling NGEN for distributed framework libraries). Either require .NET 3.5, avoid using Linq, or implement your own extensions for a [custom Linq provider](http://netpl.blogspot.com/2009/03/valuable-custom-linq-provider-tutorials.html).
Linq to SQL Templates in .NET 2.0 Projects
[ "", "c#", ".net", "visual-studio", "linq", "linq-to-sql", "" ]
Given a string: ``` string = "Test abc test test abc test test test abc test test abc"; ``` This seems to only remove the first occurrence of `abc` in the string above: ``` string = string.replace('abc', ''); ``` How do I replace *all* occurrences of it?
In the latest versions of most popular browsers, you can use [`replaceAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) as shown here: ``` let result = "1 abc 2 abc 3".replaceAll("abc", "xyz"); // `result` is "1 xyz 2 xyz 3" ``` But check [Can I use](https://caniuse.com/?search=replaceAll) or another compatibility table first to make sure the browsers you're targeting have added support for it first. --- For Node.js and compatibility with older/non-current browsers: **Note: Don't use the following solution in performance critical code.** As an alternative to regular expressions for a simple literal string, you could use ``` str = "Test abc test test abc test...".split("abc").join(""); ``` The general pattern is ``` str.split(search).join(replacement) ``` This used to be faster in some cases than using `replaceAll` and a regular expression, but that doesn't seem to be the case anymore in modern browsers. Benchmark: <https://jsben.ch/TZYzj> ### Conclusion: If you have a performance-critical use case (e.g., processing hundreds of strings), use the regular expression method. But for most typical use cases, this is well worth not having to worry about special characters.
**As of August 2020:** [Modern browsers have support](https://www.caniuse.com/mdn-javascript_builtins_string_replaceall) for the [`String.replaceAll()` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) defined by the ECMAScript 2021 language specification. --- **For older/legacy browsers:** ``` function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } ``` Here is how this answer evolved: ``` str = str.replace(/abc/g, ''); ``` In response to comment "what's if 'abc' is passed as a variable?": ``` var find = 'abc'; var re = new RegExp(find, 'g'); str = str.replace(re, ''); ``` In response to [Click Upvote](https://stackoverflow.com/users/49153/click-upvote)'s comment, you could simplify it even more: ``` function replaceAll(str, find, replace) { return str.replace(new RegExp(find, 'g'), replace); } ``` **Note:** Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the `find` function above without pre-processing it to escape those characters. This is covered in the [Mozilla Developer Network](https://developer.mozilla.org/en-US/)'s [JavaScript Guide on Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping), where they present the following utility function (which has changed at least twice since this answer was originally written, so make sure to check the MDN site for potential updates): ``` function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } ``` So in order to make the `replaceAll()` function above safer, it could be modified to the following if you also include `escapeRegExp`: ``` function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } ```
How do I replace all occurrences of a string in JavaScript?
[ "", "javascript", "string", "replace", "" ]
[![alt text](https://i.stack.imgur.com/B4jPz.gif)](https://i.stack.imgur.com/B4jPz.gif) (source: [googlepages.com](http://parasu516.googlepages.com/Image1.gif)) In above image I want to mark Circle's edge with red color something like this [![alt text](https://i.stack.imgur.com/LiV53.gif)](https://i.stack.imgur.com/LiV53.gif) (source: [googlepages.com](http://parasu516.googlepages.com/Image.gif)) I have no idea how should proceed, Any help/suggestions would be highly appreciated...
Morphological filtering would work great as long as you are working with binary images like the one you provided. Dilate the image and then subtract the original. [alt text http://img29.imageshack.us/img29/1420/morphf.png](http://img29.imageshack.us/img29/1420/morphf.png) Here's a MATLAB example: ``` lImage = zeros(19, 19, 3); lImage(7:13, 7:13, :) = repmat( ... [0 0 1 1 1 0 0; ... 0 1 1 1 1 1 0; ... 1 1 1 1 1 1 1; ... 1 1 1 1 1 1 1; ... 1 1 1 1 1 1 1; ... 0 1 1 1 1 1 0; ... 0 0 1 1 1 0 0;], [1 1 3]); figure; imshow(lImage); lOutline = imdilate(lImage, strel('disk', 1)) - lImage; lOutline(:, :, 2:3) = 0; figure; imshow(lImage + lOutline); ```
Quick and dirty solution. Run the image pixel by pixel, if the color change, just paint the pixel red. PS: Notice this may not work for a square, unless you do the same vertically and horizontally
black and white Image processing in C#
[ "", "c#", "image-processing", "image-manipulation", "" ]
Here is what I'm trying to setup My class is named Inventory I have a static function named List\_Departments() I would like to be able to add an additional function to modify the previous For Example: Inventory.List\_Departments().ToHTML() would return an HTML formatted string containing the data from List\_Departments() If possible i'd like to reuse the same code for another function such as List\_Categories() I would really appreciate a nudge in the right direction on this. I just can't seem to find the correct terminology/ search term to pull up the info I need. Thank you very much for your help, and sorry for the somewhat stupid question.
It sounds like what you're referring to is [Extension Methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx)
You need to make the `List_Departments` method return an object that has a `ToHtml` method. Depending on what your exactly methods are returning, you might make a class called something like ObjectList, which would have a `ToHtml` method, and have the `ListDepartments` and `ListCategories` return instances of it. Alternatively, and especially if your methods are returning existing classes such a `DataTable`, you could make an [extension method](http://msdn.microsoft.com/en-us/library/bb383977.aspx) for that class called `ToHtml`.
How do I setup a nested/chained function within a C# Class
[ "", "c#", "" ]
I am using the Dundas Chart Controls and Microsoft Chart Controls for .NET. Currently I have a method which populates the chart control with a date from a generic List. Let's say that I populate the chart with data from one list. Then I want to populate the chart with data from another list. I have a problem populating the chart with the data from the second list. I end up with a chart that displays the combined data from list 1 and list 2, whereas I want it to display only the data from the first list, and then clear the chart before displaying the data from the second list. I have tried various method calls to clear the chart control before populating it with the data from the second list but to no avail. Is there a way of doing this?
I found it! Do this: ``` chart1.Series[0].Points.Clear(); ```
A comment for others who may come across this: To clear out the chart series, titles, and legends: ``` //clear chart Chart1.Series.Clear(); Chart1.Titles.Clear(); Chart1.Legends.Clear(); //create chart ```
Microsoft Chart Controls/Dundas Charts Clear Contents?
[ "", "c#", ".net", "microsoft-chart-controls", "dundas", "" ]
C has perror and errno, which print and store the last error encountered. This is convenient when doing file io as I do not have to fstat() every file that fails as an argument to fopen() to present the user with a reason why the call failed. I was wondering what is the proper way to grab errno when gracefully handling the IOError exception in python? ``` In [1]: fp = open("/notthere") --------------------------------------------------------------------------- IOError Traceback (most recent call last) /home/mugen/ in () IOError: [Errno 2] No such file or directory: '/notthere' In [2]: fp = open("test/testfile") --------------------------------------------------------------------------- IOError Traceback (most recent call last) /home/mugen/ in () IOError: [Errno 13] Permission denied: 'test/testfile' In [5]: try: ...: fp = open("nothere") ...: except IOError: ...: print "This failed for some reason..." ...: ...: This failed for some reason... ```
The Exception has an `errno` attribute: ``` try: fp = open("nothere") except IOError as e: print(e.errno) print(e) ```
Here's how you can do it. Also see the `errno` module and `os.strerror` function for some utilities. ``` import os, errno try: f = open('asdfasdf', 'r') except IOError as ioex: print 'errno:', ioex.errno print 'err code:', errno.errorcode[ioex.errno] print 'err message:', os.strerror(ioex.errno) ``` * <http://docs.python.org/library/errno.html> * <http://docs.python.org/library/os.html> For more information on IOError attributes, see the base class EnvironmentError: * <http://docs.python.org/library/exceptions.html?highlight=ioerror#exceptions.EnvironmentError>
How to get the errno of an IOError?
[ "", "python", "exception", "errno", "ioerror", "" ]
I'm writting an WPF application using the mvvm toolkint. In the main windows I have a command in a button that open another window using: ``` catView.ShowDialog(); ``` Well, I close that window (using a close button or the X) and when I close the main window, the app is still running and I have to kill it. If I don't open the second window, the app shutdown normally. Why if I open another window I can't close the app normally? I have this in the close button of the second window: ``` this.DialogResult = true; this.Close(); ``` On the other hand, I start the app in this way (mvvm toolkit way): ``` Views.MainView view = new Views.MainView(); view.DataContext = new ViewModels.MainViewModel(); view.Show(); ``` Thank you very much.
The problem is probably unrelated to opening and closing the window but is somthing inside that window. This usually happens when you have another thread still running when you close the application, check for anything that might be creating a new thread inside the window's code (including System.Threading.Thread, ThreadPool, BackgroundWorker and 3rd party components), make sure all background threads shut down before closing the application (or if you can't shut them down at least mark them as background threads). Also look for anything that can open another (invisible) window, it's common to use window messages to an invisible window as an inter-process communication mechanism, again look for 3rd party code that might be doing that.
Nir is correct, a thread is probably still running in your other window. You can fix this by terminating the application's thread dispatcher when the window closes. ``` public Window1() { InitializeComponent(); // This line should fix it: this.Closed += (sender, e) => this.Dispatcher.InvokeShutdown(); } ``` I'm happy to be corrected if this is not the right way to do things. Worked well for me though. PS. If your other window is designed to run in a different thread, then read this by Eugene Prystupa: [running-wpf-application-with-multiple-ui-threads](http://eprystupa.wordpress.com/2008/07/28/running-wpf-application-with-multiple-ui-threads/)
My WPF app still running if I open another Window
[ "", "c#", "wpf", "" ]
I'm curious. What could be the reason that a Comparator shuffles entries on each application start? ``` final static class ContactsListComparator implements Comparator { public int compare(Object o1, Object o2) { if((o1.toString().compareTo(o2.toString()))<0) { return -1; } if((o1.toString().compareTo(o2.toString()))>0) { return 1; } else { return 0; } } } ``` First App Start: ![alt text](https://files.getdropbox.com/u/357576/saves/shuffel1.png) Second App Start ![alt text](https://files.getdropbox.com/u/357576/saves/shuffel2.png) As mentioned in one the answer The Comparator actually compares an custom object Contact ``` public class Contact { // Members private String _contactFirstName; private String _contactLastName; private long _contactLastModified; // Constructor public Contact() { set_contactLastModified(); } public Contact(String contactFirstName) { _contactFirstName = contactFirstName; set_contactLastModified(); } // Accessable Getters public String get_contactFirstName() { return _contactFirstName; } public String get_contactLastName() { return _contactLastName; } public long get_contactLastModified() { return _contactLastModified; } public void set_contactLastModified() { _contactLastModified = System.currentTimeMillis(); } } ```
your toString method probably isn't overridden for your objects representing the contacts. It will return a hash string for those objects, which varies every time your app is run. You can fix this either of two ways: * Override the `toString()` method in your `Contact` object to return the contact's name (1), or * Change the `Comparator` to `Comparator<Contact>` so it gets `Contact` objects as parameters (2) for (1), add this to your Contact class: ``` @Override public String toString() { return get_contactFirstName(); } ``` for (2) you would end up with this Comparator implementation: ``` final static class ContactsListComparator implements Comparator<Contact> { public int compare(Contact o1, Contact o2) { return contact1.get_contactFirstName().compareTo(contact2.get_contactFirstName()); } } ``` you don't even need to check for the <0 or >0, but you can just return whatever the String comparison gives.
I would use: ``` final static class ContactsListComparator implements Comparator<Contact> { public int compare(Contact c1,Contact c2) { int i=c1.get_contactLastName().compareTo(c2.get_contactLastName()); if(i!=0) return i; return c1.get_contactFirstName().compareTo(c2.get_contactFirstName());; } } ```
Strange behaviour: Java Comparator randomizes list entries
[ "", "java", "blackberry", "list", "" ]
I'm working on an appender for log4net and I'm faced with the problem of how to manage dependencies on the log4net version my class library is built against vs. the actual version deployed on the site. My class library has to reference log4net dlls and as such it becomes tied to the version I'm referencing at built time. However, the sites this component will be deployed will have various log4net versions, some older than mine, some will be newer. How should I approach this problem? I don't want to release a new version of my appender for each log4net new version and place the burden of correctly matching them on my users. I also don't want to ask my appender users to do complex side-by-side manifest tricks. I just want my appender to be simply copied on the end user location and work out-of-the-box with whatever log4net version is present there. Is this achievable? Am I missing something obvious? **Update**: The only working solution is to use the manifest. I tested with two 'homemade' log4net builds and adding the following configuration section solves my problem: ``` <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="log4net" publicKeyToken="..." culture="neutral" /> <bindingRedirect oldVersion="1.2.10.0" newVersion="..."/> </dependentAssembly> </assemblyBinding> </runtime> ``` where the publicKeyToken is the actual key token of the real log4net assembly, 1.2.10 is the version my appender is built with and the newVersion is the currently deployed version on site. The section can be added to the deployed appconfig or webconfig (it can be done in machine config too, but I rather not recommend that...).
Lot of projects have the same problem that you've just described. As far as I know, this is not something that you as a publisher can control. You can set a [publisher policy](http://msdn.microsoft.com/en-us/library/dz32563a.aspx) that allows you to automatically specify that a certain version of your assembly should be used when older versions of your assemblies are referenced, but there is no way to specify this for assemblies that you do not control (like log4net). On your user side, the administrator can specify that requests for an older version of log4net(which your assembly might reference) by redirected to a specific version via an [assembly redirect](http://msdn.microsoft.com/en-us/library/7wd6ex19(VS.71).aspx).
You could handle the AssemblyResolve event: ``` AppDomain current = AppDomain.CurrentDomain; current.AssemblyResolve += current_AssemblyResolve; ``` You could then use string manipulation on the Name property (from the ResolveEventArgs) to remove the version number and load the assembly without specifying its version.
Version independent reference dependencies in managed class libraries
[ "", "c#", "reflection", "reference", "log4net", "" ]
If I have a date 01/01/2009, I want to find out what day it was e.g. Monday, Tuesday, etc... Is there a built-in function for this in SQL Server 2005/2008? Or do I need to use an auxiliary table?
Use [`DATENAME`](https://learn.microsoft.com/en-us/sql/t-sql/functions/datename-transact-sql) or [`DATEPART`](https://learn.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql): ``` SELECT DATENAME(dw,GETDATE()) -- Friday SELECT DATEPART(dw,GETDATE()) -- 6 ```
Even though [SQLMenace's answer](https://stackoverflow.com/a/1111013/1501497) has been accepted, there is one important `SET` option you should be aware of > [SET DATEFIRST](https://learn.microsoft.com/en-us/sql/t-sql/statements/set-datefirst-transact-sql) [DATENAME](https://learn.microsoft.com/en-us/sql/t-sql/functions/datename-transact-sql) will return correct date *name* but not the same [DATEPART](https://learn.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql) value if the first day of week has been changed as illustrated below. ``` declare @DefaultDateFirst int set @DefaultDateFirst = @@datefirst --; 7 First day of week is "Sunday" by default select [@DefaultDateFirst] = @DefaultDateFirst set datefirst @DefaultDateFirst select datename(dw,getdate()) -- Saturday select datepart(dw,getdate()) -- 7 --; Set the first day of week to * TUESDAY * --; (some people start their week on Tuesdays...) set datefirst 2 select datename(dw,getdate()) -- Saturday --; Returns 5 because Saturday is the 5th day since Tuesday. --; Tue 1, Wed 2, Th 3, Fri 4, Sat 5 select datepart(dw,getdate()) -- 5 <-- It's not 7! set datefirst @DefaultDateFirst ```
Get day of week in SQL Server 2005/2008
[ "", "sql", "sql-server", "datetime", "" ]
I've found some strange code... ``` //in file ClassA.h: class ClassA { public: void Enable( bool enable ); }; //in file ClassA.cpp #include <ClassA.h> void ClassA::Enable( bool enable = true ) { //implementation is irrelevant } //in Consumer.cpp #include <ClassA.h> .... ClassA classA; classA.Enable( true ); ``` Obviously since `Consumer.cpp` only included `ClassA.h` and not `ClassA.cpp` the compiler will not be able to see that the parameter has a default value. When would the declared default value of `ClassA::Enable` in the signature of the method implementation have any effect? Would this only happen when the method is called from within files that include the `ClassA.cpp`?
Default values are just a compile time thing. There's no such thing as default value in compiled code (no metadata or things like that). It's basically a compiler replacement for "if you don't write anything, I'll specify that for you." So, if the compiler can't see the default value, **it assumes there's not one**. Demo: ``` // test.h class Test { public: int testing(int input); }; // main.cpp #include <iostream> // removing the default value here will cause an error in the call in `main`: class Test { public: int testing(int input = 42); }; int f(); int main() { Test t; std::cout << t.testing() // 42 << " " << f() // 1000 << std::endl; return 0; } // test.cpp #include "test.h" int Test::testing(int input = 1000) { return input; } int f() { Test t; return t.testing(); } ``` Test: ``` g++ main.cpp test.cpp ./a.out ```
Let me admit first that this is the first time I have seen this type of code. Putting a default value in header file **IS** the normal practice but this isn't. My guess is that this default value can only be used from code written in the same file and this way the programmer who wrote this wanted to put it in some type of easiness in calling the function but he didn't want to disturb the interface (the header file) visible to the outside world.
What if the default parameter value is defined in code not visible at the call site?
[ "", "c++", "header", "" ]
I'm working on a GUI in SDL. I've created a slave/master class that contains a std::list of pointers to it's own slaves to create a heirarchy in the GUI (window containing buttons. Button a label and so on). It worked fine for a good while, until I edited a *completely different* class that doesn't effect the slave/master class directly. The call to the list.push\_front() in the old slave/master class now throws the following error when debugging in VS C++ 2008 express and I can't find what's causing it. > "Unhandled exception at 0x00b6decd in > workbench.exe: 0xC0000005: Access > violation reading location > 0x00000004." \*workbench.exe is my project. The exception is raised in the \_Insert method in the list code on row 718: ``` _Nodeptr _Newnode = _Buynode(_Pnode, _Prevnode(_Pnode), _Val); ``` The list is created in the master/slave class' definition and the slave/master class is created on the heap to be inserted in another master's slave list. The list that crashes is empty when push\_front() is called but it is second in line in the heirarchy, so it worked once. As I said, it worked fine before and the slave/master class hasn't been altered to cause the error. The new class does use lists aswell. **Can the use of several lists cause clashes? May I have accidentally screwed up the heap?** Any help and tips to what I could look for is appreciated. P.S The code is rather large now so I would guess it's better to not include it. Especially since I'm not exactly sure just what causes the error. Sorry if it's a bit scarce **Update:** I've replaced the push\_front() with creating an iterator and using insert(). The result was an iterator pointing to "baadf00d" after assigning the list.begin(). baadf00d is some error/NULL pointer that VS uses to objects that haven't been assigned anything, as far as I can tell. I guess it's another sign that the list is corrupt?
Finally after looking through every nook and cranny I've found the bug! It was completely unexpected and I feel a bit embarrassed about it. I had recently re-arranged the files. Prior to that I had generic classes in one folder and my user interface files in a subfolder. I copied the GUI files to the main folder and I thought I linked everything up correctly, but obviously I missed *one* line and it never occurred to me when it started acting up. My library compiled since that was linked fine, but my testing program wasn't... it simply looked at the old header files! Worked fine to begin with ofcourse since the headers were the same, but then I edited one and the class declared in it started acting funny as mentioned, obviously, since it couldn't recognize the damn thing anymore. It looked like corrupted memory, so that's what I looked for. Lesson learned: Don't keep two versions close to each other or at all.
Usually errors like this with addresses like 0x00000004 indicate dereferencing a NULL pointer, e.g. ``` struct point { int x; int y; }; struct point *pt = NULL; printf("%d\n", pt->y); ``` can create an error like that. Doesn't smell like heap corruption to me, usually those errors tend to be subtler, I bet this is a case of a NULL pointer. I'd go up the call stack and hunt for null pointers, could be a member of the the object you're pushing on to the fron of the list or that object itself. If you do think this is a heap corruption issue, you can use [`gflags`](http://technet.microsoft.com/en-us/library/cc738763%28WS.10%29.aspx), which is free, to enable page heap and the like which will let you detect heap corruption earlier, hopefully as it happens, rather than by the side effects it causes later.
<list> throws unhandled exception when calling push_front()
[ "", "c++", "memory", "list", "" ]
Suppose I have a string like this: ``` string = "Manoj Kumar Kashyap"; ``` Now I want to create a regular expression to match where Ka appears after space and also want to get index of matching characters. I am using java language.
You can use regular expressions just like in Java SE: ``` Pattern pattern = Pattern.compile(".* (Ka).*"); Matcher matcher = pattern.matcher("Manoj Kumar Kashyap"); if(matcher.matches()) { int idx = matcher.start(1); } ```
You don't need a regular expression to do that. I'm not a Java expert, but according to the [Android docs](http://developer.android.com/reference/java/lang/String.html): > **public int indexOf (String string)** > Searches in this string for the first > index of the specified string. The > search for the string starts at the > beginning and moves towards the end of > this string. > > **Parameters** > string the string to find. > > **Returns** You'll probably end up with something like: ``` int index = somestring.indexOf(" Ka"); ```
How do I create a regular expression for this in android?
[ "", "java", "android", "regex", "" ]
How do I stop thinking every query in terms of cursors, procedures and functions and start using SQL as it should be? Do we make the transition to thinking in SQL just by practise or is there any magic to learning the set based query language? What did you do to make the transition?
A few examples of what should come to your mind first if you're real `SQL` geek: * [**Bible concordance**](http://en.wikipedia.org/wiki/Bible_concordance) is a `FULLTEXT` index to the `Bible` * [**Luca Pacioli**](http://en.wikipedia.org/wiki/Luca_Pacioli)'s *Summa de arithmetica* which describes double-entry bookkeeping is in fact a normalized database schema * When `Xerxes I` counted his army by walling an area that `10,000` of his men occupied and then marching the other men through this enclosure, he used `HASH AGGREGATE` method. * `The House That Jack Built` should be rewritten using a self-join. * `The Twelve Days of Christmas` should be rewritten using a self-join and a `ROWNUM` * `There Was An Old Woman Who Swallowed a Fly` should be rewritten using `CTE`'s * If the `European Union` were called `European Union All`, we would see `27` spellings for the word `euro` on a [**Euro banknote**](http://en.wikipedia.org/wiki/File:EUR_500_reverse_(2002_issue).jpg), instead of `2`. And finally you can read a lame article in my blog on how *I* stopped worrying and learned to love `SQL` (I almost forgot I wrote it): * [**Click**](http://explainextended.com/2009/06/21/click/) And one more article just on the subject: * [**Double-thinking in SQL**](http://explainextended.com/2009/07/12/double-thinking-in-sql/)
The key thing is you're manipulating SETS & elements of sets; and relating different sets (and corresponding elements) together. That's really the heart of it, imho. That's why every table should have a primary key; why you see set operators in the language; and why set operators like UNION won't (by defualt) return duplicate rows. Of course in practice, the rules of sets are bent or broken but it's not that hard to see when this is necessary (otherwise, SQL would be TOO limited). Imho, just crack open your discrete math book and reacquaint yourself with some set exercises.
How to think in SQL?
[ "", "sql", "database", "rdbms", "" ]
I am trying to have some fun in summer. Writing a piece of code that enables presenting Arabic language in systems that support Unicode but no support for eastern languages it. I am writing only the logic hopefully with no integration code initially. Should I use C++ or C? Which is the easier language to write portable code and easier to integrate with Python possibly? --- ### Edit: I am fairly good with C/C++ though I consider myself closer to C++. But It seems it is easier to write C and plug it every where or I am wrong ? I would write some functions to process Arabic Unicode String. presenting Arabic language need some processing because ALMOST ALL characters have different shapes in different contexts. --- ### Edit: It seems I will go with C++, just to make it more fun.
I would use C++, mostly because it provides a lot more "stuff" to use and as far as my experience goes is as portable as C. However, I have not used straight C/C compiler for 10 years or more. --- ### EDIT A commenter questioned my experience with portability. Mine is limited to Linux and Win32 primarily. I assumed this would be sufficient OSes for this exercise.
I strongly disagree with the assertion that C and C++ are comparable when portability is a concern. True, if you limit yourself to recent Visual Studio and g++, C++ is "portable". But things like boost are a maintenance nightmare if you care about more platforms than that (older gcc/visual studio, many other old compilers on proprietary unices). In this context, C is much more portable than C++ in my experience. If you look at most open source projects which use C++ (mozilla, some google code) , they limit themselves to a very restricted subset of C++. Now, for strings handling, I would say that both C and C++ are quite bad languages :) I would certainly look at something much higher level, with good support for unicode string handling.
Is C or C++ better for making portable code?
[ "", "c++", "c", "portability", "" ]
I'm writing an application that needs to read a list of strings from a file, save them in a data structure, and then look up those strings by prefixes. The list of strings is simply a list of words in a given language. For example, if the search function gets "stup" as a parameter, it should return ["stupid", "stupidity", "stupor"...]. It should do so in O(log(n)\*m) time, where n is the size of the data structure and m is the number of results and should be as fast as possible. Memory consumption is not a big issue right now. I'm writing this in python, so it would be great if you could point me to a suitable data structure (preferably) implemented in c with python wrappers.
You want a trie. <http://en.wikipedia.org/wiki/Trie> I've used them in Scrabble and Boggle programs. They're perfect for the use case you described (fast prefix lookup). Here's some sample code for building up a trie in Python. This is from a Boggle program I whipped together a few months ago. The rest is left as an exercise to the reader. But for prefix checking you basically need a method that starts at the root node (the variable `words`), follows the letters of the prefix to successive child nodes, and returns True if such a path is found and False otherwise. ``` class Node(object): def __init__(self, letter='', final=False): self.letter = letter self.final = final self.children = {} def __contains__(self, letter): return letter in self.children def get(self, letter): return self.children[letter] def add(self, letters, n=-1, index=0): if n < 0: n = len(letters) if index >= n: return letter = letters[index] if letter in self.children: child = self.children[letter] else: child = Node(letter, index==n-1) self.children[letter] = child child.add(letters, n, index+1) def load_dictionary(path): result = Node() for line in open(path, 'r'): word = line.strip().lower() result.add(word) return result words = load_dictionary('dictionary.txt') ```
Some Python implementations of [tries](http://en.wikipedia.org/wiki/Trie): * <http://jtauber.com/2005/02/trie.py> * <http://www.koders.com/python/fid7B6BC1651A9E8BBA547552FE3F039479A4DECC45.aspx> * <http://filoxus.blogspot.com/2007/11/trie-in-python.html>
most efficient data structure for a read-only list of strings (about 100,000) with fast prefix search
[ "", "python", "data-structures", "dictionary", "lookup", "" ]
Not that I would want to use this practically (for many reasons) but out of strict curiousity I would like to know if there is a way to reverse order a string using LINQ and/or LAMBDA expressions in **one line of code**, without utilising any framework "Reverse" methods. e.g. ``` string value = "reverse me"; string reversedValue = (....); ``` and reversedValue will result in "em esrever" **EDIT** Clearly an impractical problem/solution I know this, so don't worry it's strictly a curiosity question around the LINQ/LAMBDA construct.
I don't see a practical use for this but just for the sake of fun: ``` new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray()) ```
Well, I can do it in one very long line, even without using LINQ or a lambda: ``` string original = "reverse me"; char[] chars = original.ToCharArray(); char[] reversed = new char[chars.Length]; for (int i=0; i < chars.Length; i++) reversed[chars.Length-i-1] = chars[i]; string reversedValue = new string(reversed); ``` (Dear potential editors: do *not* unwrap this onto multiple lines. The whole point is that it's a single line, as per the sentence above it and the question.) However, if I saw anyone avoiding using framework methods for the sake of it, I'd question their sanity. Note that this doesn't use LINQ at all. A LINQ answer would be: ``` string reverseValue = new string(original.Reverse().ToArray()); ``` Avoiding using Reverse, but using OrderByDescending instead: ``` string reverseValue = new string(original.Select((c, index) => new { c, index }) .OrderByDescending(x => x.index) .Select(x => x.c) .ToArray()); ``` Blech. I like Mehrdad's answer though. Of course, all of these are far less efficient than the straightforward approach. Oh, and they're all wrong, too. Reversing a string is more complex than reversing the order of the code points. Consider combining characters, surrogate pairs etc...
Can you reverse order a string in one line with LINQ or a LAMBDA expression
[ "", "c#", "linq", "string", "lambda", "" ]
I feed a Microsoft Chart control with a IEnumerable of my own class ChartPoint ``` public class ChartPoint { public double Xvalue { get; set; } public double Yvalue { get; set; } public string Url { get; set; } public string Tooltip { get; set; } } ``` then i tries to DataBind the IEnumerable< ChartPoint>: ``` serie.Points.DataBind(points, "Xvalue", "Yvalue", "Tooltip=Tooltip,Url=Url"); ``` but i then hits a NotImplementedException on that row: ``` System.Linq.Iterator`1.System.Collections.IEnumerator.Reset() +29 System.Web.UI.DataVisualization.Charting.DataPointCollection.DataBind(IEnumerable dataSource, String xField, String yFields, String otherFields) +313 ``` What am I doing wrong?
Are you using a C# iterator? C# iterators do not implement the Reset function on the generated IEnumerator and will throw a NotImplementedException if it is called. It looks like the particular control requires that method to be present. You will likely have to use a collection which supports Reset on it's iterator. The easiest way to achieve this is to use a `List<T>` to wrap your existing `IEnumerable<T>` For example ``` List<ChartPoint> list = new List<ChartPoint>(points); serie.Points.DataBind(list, "Xvalue", "Yvalue", "Tooltip=Tooltip,Url=Url"); ```
Are you using iterator blocks (i.e. `yield return`)? The compiler ~~won't generate a `Reset` method if you do~~ generates a `Reset` method but the method throws a `NotImplementedException`.
Databind with Chart controls gives NotImplementedException
[ "", "c#", "charts", "" ]
I need to detect if a flag is set within an enum value, which type is marked with the Flag attribute. Usually it is made like that: ``` (value & flag) == flag ``` But since I need to do this by generic (sometimes at runtime I event have only an "Enum" reference. I can not find an easy way to use the & operator. At the moment I make it like this: ``` public static bool IsSet<T>(this T value, T flags) where T : Enum { Type numberType = Enum.GetUnderlyingType(typeof(T)); if (numberType.Equals(typeof(int))) { return BoxUnbox<int>(value, flags, (a, b) => (a & b) == b); } else if (numberType.Equals(typeof(sbyte))) { return BoxUnbox<sbyte>(value, flags, (a, b) => (a & b) == b); } else if (numberType.Equals(typeof(byte))) { return BoxUnbox<byte>(value, flags, (a, b) => (a & b) == b); } else if (numberType.Equals(typeof(short))) { return BoxUnbox<short>(value, flags, (a, b) => (a & b) == b); } else if (numberType.Equals(typeof(ushort))) { return BoxUnbox<ushort>(value, flags, (a, b) => (a & b) == b); } else if (numberType.Equals(typeof(uint))) { return BoxUnbox<uint>(value, flags, (a, b) => (a & b) == b); } else if (numberType.Equals(typeof(long))) { return BoxUnbox<long>(value, flags, (a, b) => (a & b) == b); } else if (numberType.Equals(typeof(ulong))) { return BoxUnbox<ulong>(value, flags, (a, b) => (a & b) == b); } else if (numberType.Equals(typeof(char))) { return BoxUnbox<char>(value, flags, (a, b) => (a & b) == b); } else { throw new ArgumentException("Unknown enum underlying type " + numberType.Name + "."); } } private static bool BoxUnbox<T>(object value, object flags, Func<T, T, bool> op) { return op((T)value, (T)flags); } ``` But I don't like the never ending if - else blocks, so is there a way to cast these values that I can use the & operator or any other solution to check this?
Personally, I think that look fine because you've wrapped it into a single purpose function. If you had that code scattered through an entire program I think you would have some problems, but what you've created improves clarity everywhere it is used and the function itself is clear enough what it does. Just my opinion of course. You could though, use the is keyword, which might help a little ``` public static bool IsSet<T>(this T value, T flags) where T : Enum { if (value is int) { return ((int)(object)a & (int)(object)b) == (int)(object)b); } //etc... ```
For me it looks overcomplicated. How about this (keeping in mind that enum is always mapped to an integer value type): ``` public static bool IsSet<T>(T value, T flags) where T : struct { // You can add enum type checking to be perfectly sure that T is enum, this have some cost however // if (!typeof(T).IsEnum) // throw new ArgumentException(); long longFlags = Convert.ToInt64(flags); return (Convert.ToInt64(value) & longFlags) == longFlags; } ```
Comparing enum flags in C#
[ "", "c#", "enums", "casting", "generics", "flags", "" ]
Is it possible to get access to a file on my FTP doing the following? ``` <input type="file" name="final" id="final" value="http://www.blah.com.au/artwork/<?=$OrderID?>/<?=$ItemID?>/Final/Final.pdf">; ``` I know that this specifically didn't work for me, but is there a way to get the file from the FTP so I can send the information to the next page to use?
There is no way. Why not use PHP to retrieve the file from your FTP or HTTP site yourself? A simple `file_get_contents()` will suffice (yes, it works for FTP and HTTP links). ``` $file_contents = file_get_contents('http://www.blah.com.au/artwork/'.$OrderID.'/'.$ItemID.'/Final/Final.pdf'); ``` ## Edit Based on new information, you might want to provide a select box with all the files on the ftp folder. You may do so by using [`ftp_connect()`](http://www.php.net/manual/en/function.ftp-connect.php), [`ftp_login()`](http://www.php.net/manual/en/function.ftp-login.php), [`ftp_nlist()`](http://www.php.net/manual/en/function.ftp-nlist.php) and [`ftp_close()`](http://www.php.net/manual/en/function.ftp-close.php) ``` <?php // set up basic connection $conn_id = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); // get contents of the current directory $contents = ftp_nlist($conn_id, "."); // output $contents var_dump($contents); ?> ```
No. This is not possible. File type input elements are used for uploading files from the client's machine to the web server. They cannot pull remote content. This is a restriction of the HTML standard. What do you want to accomplish with this? Perhaps there is an alternative solution.
Using <input type="file"> with a FTP value
[ "", "php", "ftp", "input", "" ]
I have two dropdown lists, one containing a list of countries and one for states/regions that is not populated until one of the countries is selected. Both of these dropdowns are wrapped in an updatepanel. When I select the USA, the state dropdown list is filled with the 50 states and I am able to move forward from there. We are using Selenium to run tests on this code, and the tests always break when it reaches the state dropdown. It either takes too long to generate the state list, or perhaps it just can't find the values since they are not in the initial html that is rendered. I've seen some things about a javascript "WaitForCondition" field, but can't find any details about how to use this in the selenium documentation. I'm not a javascript slouch, but am not the greatest with it either. Can anyone explain to me how you might go about solving my dilemma, and if it happens to require knowledge of how the WaitForCondition field, can you explain to me how I can get that to work? For the record, I have seen this post: [(click here for semi-useful stackoverflow post)](https://stackoverflow.com/questions/504849/using-waitforcondition-script-timeout-in-selenium-ide) but I do not understand how to relate it to my own situation. Thanks in advance for anything you can give me.
So it turns out I have found the solution to my own problem. I used the following line in my C# tests and it finds the value in my dropdown list instantly: ``` selenium.WaitForCondition("var ddl = selenium.browserbot.getCurrentWindow().document.getElementById('insert-id-of-dropdownlist-here'); ddl.options[ddl.selectedIndex].text == 'insert-text-value-to-search-for-in-dropdown-here';", "10000"); ``` In the IDE I used the following parameters: **Command**: waitForCondition **Target**: var ddl = selenium.browserbot.getCurrentWindow().document.getElementById('insert-id-of-dropdownlist-here'); ddl.options[ddl.selectedIndex].text == 'insert-the-text-value-to-search-for-in-dropdown-here'; **Value**: 10000 This is the page that ultimately helped me figure out the solution: <http://wiki.openqa.org/display/SEL/waitForCondition>
Are you using Selenium IDE? This makes it very easy to write your code and then export it to the language you're using with Selenium RC. In Selenium IDE, you'll find a method called "waitForText". This method takes an element locator as an the argument and a string as the value. Your locator would be the id of the state dropdown list (or a css selector if it has a dynamic id). For the value, use something that is present in the dropdown only after it is loaded (the last US state in the list is probably the best choice). Let me know if you need any clarification or additional detail. Regards, Mark
C# with Selenium Ajax DropdownList Question
[ "", "c#", "ajax", "drop-down-menu", "selenium", "updatepanel", "" ]
What is the best way to reuse switch logic. I have this switch statement that keeps appearing in my code. Rather then copy paste it I would like to make a function that calls other delegates and pass these delegates in as parameters. Or is there a better way? Function 1: ``` switch (test) { case "x": DoSomethingX(); break; case "y": DoSomethingY(); break; case "z": DoSomethingZ(); break; } ``` Function 2: ``` switch (test) { case "x": DoSomethingXxxx(); break; case "y": DoSomethingYyyy(); break; case "z": DoSomethingZyyy(); break; } ```
You could also have a Dictionary (or Func instead of Action) or something like that (considering your functions have a similar signature). Then you could instead of using a switch, you could have something like: ``` public class MyClass { Dictionary<string, Action> myDictionary; public MyClass() { BuildMyDictionary(); } private Dictionary<int, Action<int, int>> BuildMyDictionary() { myDictionary.Add("x", DoSomethingX); myDictionary.Add("y", DoSomethingY); myDictionary.Add("z", DoSomethingZ); myDictionary.Add("w", DoSomethingW); } public void DoStuff() { string whatever = "x"; //Get it from wherever //instead of switch myDictionary[t](); } } ``` I answered a similar question [here](https://stackoverflow.com/questions/1050638/would-you-use-regions-within-long-switch-enum-declarations/1050721#1050721) with a similar example. Also, try using enums instead of strings in your switch statement.
See if you can refactor this using an interface and different implementations of the interface. ``` public interface Test { void DoSomething(); } public class TestX : Test { void DoSomething() { } } public class TestY : Test { void DoSomething() { } } public class TestZ : Test { void DoSomething() { } } void func(Test test) { test.DoSomething(); } ```
reusing switch statement logic
[ "", "c#", "switch-statement", "" ]
I'm currently reading a file and wanted to be able to convert the array of bytes obtained from the file into a short array. How would I go about doing this?
One possibility is using [`Enumerable.Select`](http://msdn.microsoft.com/en-us/library/bb548891.aspx): ``` byte[] bytes; var shorts = bytes.Select(b => (short)b).ToArray(); ``` Another is to use [`Array.ConvertAll`](http://msdn.microsoft.com/en-us/library/exc45z53.aspx): ``` byte[] bytes; var shorts = Array.ConvertAll(bytes, b => (short)b); ```
Use [Buffer.BlockCopy](http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx). Create the short array at half the size of the byte array, and copy the byte data in: ``` short[] sdata = new short[(int)Math.Ceiling(data.Length / 2)]; Buffer.BlockCopy(data, 0, sdata, 0, data.Length); ``` It is the fastest method by far.
Convert byte array to short array in C#
[ "", "c#", "arrays", "" ]
I have large Boost/Spirit metaprogram that is blowing gcc's stack when I try to compile it. How can I increase gcc's stack size, so I can compile this program? Note: There's no infinite recursion going on, but there is enough incidental recursion to exhaust gcc's stack.
On Linux, you can expand the stack size in /etc/security/limits.conf. You can check your current stack size by using ``` $ ulimit -s 8192 ``` Then expand the stack to be double than that: ``` youruser soft stack 16384 ``` And then relog. This will increase stack size for all executable you're running, not just GCC's.
I use that in my compiler script: > CFLAGS += -Wl,--stack,10485760
How to increase the gcc executable stack size?
[ "", "c++", "gcc", "boost-spirit", "" ]
I am working on a security project at my university for open source software. I am trying to build freemarker from source, but I am running into some problems. Everything that I can find online says that simple running 'ant' in the root directory should build the project. The only requirement is that you have ant v1.7.0 installed, which I do. When I go into the root directory and type 'ant' I get the following output: ``` Buildfile: build.xml init: _autoget-deps: update-deps: [echo] Getting dependencies... [echo] ------------------------------------------------------- BUILD FAILED /media/osr/runs/java/freemarker/freemarker/trunk/freemarker/build.xml:64: The following error occurred while executing this line: /media/osr/runs/java/freemarker/freemarker/trunk/freemarker/build.xml:567: The following error occurred while executing this line: /media/osr/runs/java/freemarker/freemarker/trunk/freemarker/build.xml:575: Problem: failed to create task or type antlib:org.apache.ivy.ant:settings Cause: The name is undefined. Action: Check the spelling. Action: Check that any custom tasks/types have been declared. Action: Check that any <presetdef>/<macrodef> declarations have taken place. This appears to be an antlib declaration. Action: Check that the implementing library exists in one of: -/usr/share/ant/lib -/home/murrayj/.ant/lib -a directory added on the command line with the -lib argument Total time: 0 seconds ```
the build.xml does not have a default target. try this instead ``` ant compile ``` **edit:** changed target
You'll also need Apache Ivy. We've changed the build process for some time now; it now uses Ivy instead of manual dependency management.
Building Freemarker from source
[ "", "java", "security", "ant", "build-process", "freemarker", "" ]
My first question on SO, thanks. :) I'm developing a support issue logging system for my company and it must allow for files to be uploaded aswell as any problems submitted to our database. There could be from 0-6 different uploads to check, along with a support issue. I've managed to get an accurate variable of how many files there is through having a hidden input field (imgcount) that updates via js whenever an image is selected through a type="file" input, or removed from the form. My [input type="file"] names are image1, image2, etc. As i thought it'd be easier this way to loop through them. When the form is submitted the following code takes a look to see if there's any files and checks that they're of valid type (gif/jpeg/png), so they can be uploaded safely. I'm not too worried about viruses as the support system has a nice secure logon and we trust our clients. ``` $sscount = $_POST['imgcount']; echo $sscount; //to test the variable if($sscount>0){ for($i = 1; $i <= $sscount; $i++){ if (($_FILES["image$i"]["type"] == "image/gif") || ($_FILES["image$i"]["type"] == "image/jpeg") || ($_FILES["image$i"]["type"] == "image/png" ) && ($_FILES["image$i"]["size"] < 500000)) { } else { $errormsg .= "Error: Image $i must be either JPEG, GIF, or PNG and less than 500 kb.<br />"; } } } ``` But this doesn't seem to be looping through correctly, anyone got any ideas how i can get it to loop through and return correctly?
The && operator has a higher [precedence](https://www.php.net/manual/en/language.operators.precedence.php) than ||, so rather than `(A OR B OR C) AND D` as you intended, it is actually `A OR B OR (C AND D)` You can use parentheses to enforce the evaluation you intended. However, something like this might be cleaner and easier to maintain/read: ``` $allowed_types=array( 'image/gif', 'image/jpeg', 'image/png', ); $sscount = $_POST['imgcount']; if($sscount>0){ for($i = 1; $i <= $sscount; $i++){ if (in_array($_FILES["image$i"]["type"], $allowed_types) && ($_FILES["image$i"]["size"] < 500000)) { } } } ```
This isn't a direct answer to your question, but you can pass form values to PHP as an array which should be easier to loop through. [`in_array()`](http://php.net/in_array) is also useful for checking that a value is within an allowed list. HTML: ``` <input type="file" name="image[]"> <input type="file" name="image[]"> <input type="file" name="image[]"> <input type="file" name="image[]"> ``` PHP: ``` <?php if (isset($_FILES['image'])) { foreach ($_FILES['image'] as $file) { if (!in_array($file['type'], array("image/gif", "image/jpeg", "image/png")) || $file['size'] > 500000) { //error } else { //ok } } } ```
PHP - Looping through $_FILES to check filetype
[ "", "php", "file-upload", "loops", "" ]
we are a team of about 100 developers working in an iterative development style. We are looking for a solution that will allow us to aggregate all development artifacts in one collaborative environment. Rationals Team Concert is bringing a lot of what we are looking for issue tracking combined with project management and soure code management integration as well as reporting. While Team Concert is bringing a lot of features it is also quite expensive. Thats why I am looking for alternatives. I wasn't able to find a product which is providing the same functionality so I guess Rational is ahead of other companies in this market. Do you know of any competitive products? Can you suggest a combination of preferrably Open Source products that could serve us well? Thanks in advance for your help! cheers Mike
I guess a **[Redmine](http://www.redmine.org/)** setup plus a **DVCS** (like **[Git](http://git-scm.com/)**), combined with [**eclipse**](http://www.eclipse.org/) and [**Mylyn**](http://www.eclipse.org/mylyn/index.php) would be the closest open-source alternative to Rational Team Concert. You still would miss some nice features like instant messaging and stack debugging transfer (the ability to freeze a live execution and transfer it to a colleague), but that would be a good start.
Fair disclosure: I work for IBM. Fair answer: You get what you pay for. There are plenty of open source alternatives. None are as good as Team Concert and I firmly stand behind that. Have your IBM representative do a business value assessment and show you what your return on investment will be if you purchase Team Concert. They should be able to provide you these numbers. Either it makes business sense, or it doesn't. Having 100 developers who aren't working efficiently is quite costly.
Are there any alternatives to Rational Team Concert at the moment?
[ "", "java", "agile", "collaboration", "ibm-rational", "" ]
Hello I've currently got a program which retrieves WMI information and stores it to a database, after a certain period of time older records are then deleted. Currently I'm having my program delete records over 10 mintues old and it checks this every 2 mintues after populating the database with new information. In another timer which runs every 2 mintues the information stored in the database is displayed to the user, this appears in the same order that it appears in the database table. The issue I'm having occurs when the program is run from a fresh database after 10 mintues when records are deleted, instead of the new records being added to the end of the database table they appear at the top. It also occurs when the program is re-opened with existing data already populating the database once some of the old data has been deleted. Below I've added code showing how my data is added to the database and also how it is deleted (This occurs in 2 seperate classes). Below that I have indluded some sample output data so you can understand what I mean. Basically I need a way to resolve this as the data needs to be shown in the order it was collected based on the DateTime, so if you can spot anything it would be appreciated, if not would the best way to resolve this be sorting the data before it is displayed? ``` DateTime dateTime = DateTime.Now.Subtract(new TimeSpan(0, 0, 10, 0)); var result2 = (from b in hddInfo where b.DateTime < dateTime select b).DefaultIfEmpty(); foreach (TblHDDInfo record2 in result2) { if (record2 != null) { localDB.TblHDDInfo.DeleteOnSubmit(record2); } } localDB.SubmitChanges(); TblHDDInfo hddInfoAdd = new TblHDDInfo(); hddInfoAdd.DeviceID = deviceID; hddInfoAdd.IpAdd = ipAdd; hddInfoAdd.Size = size; hddInfoAdd.FreeSpace = freeSpace; hddInfoAdd.DateTime = dateTime; localDB.TblHDDInfo.InsertOnSubmit(hddInfoAdd); localDB.SubmitChanges(); ``` **1st time** HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:27:21 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:29:26 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:31:31 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:33:36 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:35:41 **2nd time** HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:37:46 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:29:26 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:31:31 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:33:36 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:35:41 **3rd time** HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:39:51 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:37:46 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:29:26 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:31:31 HDD Size: 186GB Remaining space:157GB DateTime:19/07/2009 17:33:36
Why not just add an orderby b.DateTime to your LINQ query? Just a clarification: Databases are by their very nature unordered and the location of inserts is indeterminant, in that, the location of a row in the actual table is a meaningless concept at the level of abstraction you work at with when interacting in your code against the DB. You have to sort the DB output by one or more of the fields to apply an ordering.
I'm not 100% sure what you're trying to accomplish since there is no "top" and "bottom" of a database table. But, this line of code ... ``` hddInfoAdd.DateTime = dateTime; ``` ... seems wrong to me. Shouldn't it be like ... ``` hddInfoAdd.DateTime = DateTime.Now; ```
Database records added to top of table instead of bottom using LINQ
[ "", "c#", "database", "linq", "sorting", "" ]
I understand the purpose of GWT, but I'm wondering if I can use it to compile a few functions from Java to JavaScript just to make sure that I don't have to maintain the same code in two different languages. Or would GWT bring along too much library/support overhead along to make this a reasonable choice? For future projects, I have the same question about Script# (the C# compiler). --- **Followup:** Script# [seems to produce very readable JavaScript](http://projects.nikhilk.net/Content/Projects/ScriptSharp/ScriptSharp.pdf) from C# (pages 35-51 have some examples of C# code and the generated JS code). I found out that there is a `-STYLE` flag to make the GWT output "pretty" or even "detailed." I still don't know if the emitted JS relies on large libraries or if there are other "gotchas" involved.
Yes, you can do just that. Here's the way to invoke it from Javascript ([Source](http://code.google.com/support/bin/answer.py?answer=75695&topic=10213)): > ## How can I call one of my GWT Java methods from my application host page? > > In order to accomplish this, you'll > first need to create a JSNI method > that creates a JavaScript method that > in turn makes the call to your Java > method. In your GWT application's > onModuleLoad(), you would call that > JSNI method so that the JavaScript > method is defined. From your > application host page you would then > call the created JavaScript method. > > Confused yet? It's actually quite > simple. > > The code snippet below shows an > example of this (courtesy of Robert > Hanson): ``` private native void initPlaylistJS (PlaylistTable pl) /*-{ $wnd.addClipToPlaylist = function (clipId, clipTitle) { pl.@com.foo.bar.client.PlaylistTable::addClip(Ljava/lang/String;Ljava/lang/String;)(clipId, clipTitle); }; }-*/; ``` > In this example, you would need to > make a call to initPlaylistJS(pl) in > your GWT module's onModuleLoad(). Once > your GWT application loads, the > JavaScript method is defined and is > callable from outside of the GWT > application. As for the 'baggage', GWT compiles a single monolithic file, so you don't need to include anything else. --- One extra thing to note is that in my experience GWT is not perfectly suited for sharing code between the server and the client, since the server part needs to become GWT-compilable, that is only include classes which are part of the [emulated JRE](http://code.google.com/webtoolkit/doc/1.6/RefJreEmulation.html) or for which you have the source available for compilation.
GWT is not a general-purpose Java-to-JavaScript converter, though it converts a useful part of the JRE for web applications (and of course the GWT widgets). It's not really worth using for a "few" functions just to avoid coding in JavaScript. Of course if you are building a complex UI which consequently involves complex JavaScript coding, then GWT really shines. If you write Java methods to help implement the logic of your GWT event handling, then these will get converted to JavaScript functions along with everything else. However the main benefit of GWT is how easy and natural it is to debug your UI in hosted mode - that's the main productivity gain (as well as the familiarity of the widget API for desktop application developers).
Can I use GWT (or Script#) to write individual functions in Java (or C#) and compile them to JavaScript?
[ "", "javascript", "gwt", "script#", "" ]
I am working on an enhancement to a Flex dashboard that will allow the users to save searches. I'm using BlazeDS and Java/Spring/SpringJdbc on the server side. My question is this: how would you model a search that has one or more criteria, such as: * Value Date between 2009-10-01 and 2009-10-31 * Currency = 'USD' * Bank Name starts with 'First' My first stab at this is to divide the criteria into 3 types: * Numeric criteria * Date criteria * String criteria Each of the criteria types has a different set of comparison operators: * Numeric operators: =, >, >=, <, <=, <> * Date operators: Before, After, Between * String operators: Starts with, Ends with, contains I have codes to identify each of these operators. My object model is a SearchCriteria interface and 3 classes that implement it: NumericCriteria, DateCriteria, and StringCriteria All of these classes map to the same table with the following columns: ``` - SAVED_SEARCH_ID: id of the saved search - SEQ_NUM: criteria order. We want to load the criteria in the same order each time - CRITERIA_TYPE: Operator code. I can use this later to determine what kind of criteria this is. - FIELD: currency, valueDate, bank, etc - FIRST_VALUE_NUMERIC - SECOND_VALUE_NUMERIC - FIRST_VALUE_DATE - SECOND_VALUE_DATE - FIRST_VALUE_STRING - SECOND_VALUE_STRING ``` Is there a cleaner way to do this? I'm not crazy about the data model, but I can't find any resources on this topic... All comments are appreciated, no matter how cruel :)
You could serialize your criteria classes to XML and persist the XML in lieu of implementing a bulky schema.
Maybe you can get some inspiration from the [Hibernate Criteria API](https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Criteria.html). It provides a full model for typesafe querying, which by itself could probably mapped into a database using JPA/Hibernate itself.
Storing search criteria in a database
[ "", "java", "database-design", "" ]
I have an application that is a not so simple Windows service (C#). I created an installer using Visual Studio 2008, which did the job of installing the service on the clients machine, but using the Visual Studio deployment project has 2 drawbacks: 1. I can't seem to get the installer to build using MSBuild (i've tried the DevEnv.exe method). The service is a small piece of a much larger project, and I'd like the build of the MSI file to happen at the same time as my build does. I have used WiX for the other installers, but this particular application requires a configuration step in the setup. 2. There seems to be a bug in VS 2008's deployment project when installing windows services. On repair and upgrade, the service is never stopped. (caused by an invalid sequence for RemoveExistingProducts - i have worked around this by changing the sequence to 1525) What is nice about VS2008's deployment project is that I created a custom action that shows a form that gets some info from the user, connects to a WCF service, which retrieves data and stores it in an encrypted data store on their local machine for use by the service. Now, I have looked high and low, and I don't see this being possible with WiX. Running an EXE after the program has installed isn't 'nice'. I'd like to be able to call a method in my Custom Action DLL that displays the form, and does the processing it needs to. Is there any way of doing this with WiX? -- or even, create a custom GUI in WiX that gets the values and passes these values to a method for processing So, questions: 1. Is this possible with WiX? 2. What are my alternatives if not? Many thanks
The answer to your question #1 is yes, but it's a little involved. You can define dialogs to collect info from the user with the [UI element](http://wix.sourceforge.net/manual-wix3/wix_xsd_ui.htm) and store it session properties. You can insert these dialogs into the flow with the [Publish element](http://wix.sourceforge.net/manual-wix3/wix_xsd_publish.htm). You can then create a vb script CustomAction and do just about anything with those session properties. Check out [this tutorial](http://www.tramontana.co.hu/wix/lesson8.php) for more.
You can definitely install and start services with WiX - I'm doing that all day, every day :-) Check out the [`ServiceInstall`](http://wix.sourceforge.net/manual-wix3/wix_xsd_serviceinstall.htm) and [`ServiceControl`](http://wix.sourceforge.net/manual-wix3/wix_xsd_servicecontrol.htm) elements (there are even more, if you need to specify even more). Basically, you need to first define your service file (YourService.exe) as a file in a component, and then you need to specify the ServiceInstall (and possibly ServiecControl) elements in addition to that. ``` <Component Id='YourServiceComponent' Guid='.....' DiskId='1'> <File Id='YourServiceEXEFile' Name='YourService.exe' src='(path to your EXE)/YourService.exe' KeyPath='yes'/> <ServiceInstall Id='YourServiceInstall' Name='YourServiceName' Description='.....' ErrorControl='normal' Start='auto' Type='ownProcess' Vital='yes' /> <ServiceControl Id='UninstallYourService' Name='YourServiceName' Remove='uninstall' Wait='yes' /> </Component> ``` Then you need to add this component to one of the features in your install that's being installed - and that's about it! Marc
WiX installer and custom actions
[ "", "c#", "windows-services", "wix", "" ]
I am trying to load big image files in Java and i am getting a memory error message if the file is too big ( i have already tried increasing the heap size by the command line flag). I am loading images with the following way : If the image is not a tiff image i am using this code: ``` BufferedImage img = ImageIO.read(fileToOpen); ``` And if the file is a tiff i am using this code : ``` BufferedImage img = JAI.create("fileload", fileToOpen.getAbsolutePath()).getAsBufferedImage(); ``` My question actually boils down to this: How do image manipulation programs (like Photoshop for instance) load files of hundreds of megabytes without getting memory errors? It is my understanding that the reason a 20MB jpeg is hard to load into memory is because when loading into a BufferedImage for example you are saving the image in an uncompressed fashion. So one possible solution would be to have a Java class that subclasses the Image abstract class but stores the data in a compressed form. But that would possibly have speed issues as the runtime machine would have to uncompress the data while drawing. Another option would be to cache the raw uncompressed data to disk and seamlessly read from there but the speed problem would still persist. So how do the big boys do it? How can Photoshop load a 200MB jpeg in memory and draw all resolutions of it without any apparent issues? (final note: in my application because of speed issues after i get my BufferedImage i draw its contents onto a VolatileImage with the same dimensions. This increases the drawing speed greatly)
The required memory for uncompressed RGBA image is width \* height \* 4 bytes. Try setting your memory according to this. There might be size cap limitations of the underlying JDK/DirectX/etc. system though. The big boys exploit the structure of the JPG image and they don't need to load it into memory. Perhaps they draw it from file directly, every time. BufferedImage has automatic acceleration capabilities similar to volatile image. Set the acceleration priority to 1 and the first paint will move it to VRAM on latest JDKs. **Edit** I presume you are running a 32bit system. If your uncompressed image is quite large, more than 1.4GB, you won't be able to handle it in memory due JVM restrictions. If the image is not a one-time image, then you could find tools to stream-uncompress it into a temp-raw image and use random file access to grab parts of it.
The trick is not dealing with the full size image. Divide it into manageable pieces like 50 by 50 pixels of the current resolution and generate the content from the original file when it is needed. If a given piece is not needed (e.g. for being off screen) it can be deleted (a weak reference would be perfect) or persisted to disk.
How to load big images in Java
[ "", "java", "image", "" ]
I'm having some troubles with using the std::sort algorithm here. I was reading that you can just overload the less than operator to sort classes, but I have been getting all sorts of errors. I have also tried using a functor as you can see in the example I made below. I was hoping somebody could see what I'm doing wrong here. ``` #include <iostream> #include <vector> #include <algorithm> #include <stdlib.h> #include <time.h> class Thing { public: Thing(int val) { this->_val = val; } bool operator<(Thing& rhs) { std::cout << "this works!"; return this->val() < rhs.val(); } int val() { return this->_val; } protected: int _val; }; struct Sort { bool operator()(Thing& start, Thing& end) { return start.val() < end.val(); } }; int main (int argc, char * const argv[]) { std::srand(std::time(NULL)); std::vector<Thing> things; for(int i = 0; i < 100; i++) { Thing myThing(std::rand()); things.push_back(myThing); } if(things[1] < things[2]) { //This works } //std::sort(things.begin(), things.end()); //This doesn't //std::sort(things.begin(), things.end(), Sort()); //Neither does this for(int i = 0; i < 100; i++) { std::cout << things.at(i).val() << std::endl; } return 0; } ```
I believe you need to change ``` bool operator()(Thing& start, Thing& end) { ``` into ``` bool operator()(const Thing& start, const Thing& end) { ``` and ``` int val() { ``` into ``` int val() const { ``` IOW, your code needs to be const-correct and not claim it may modify things it in fact doesn't (nor needs to).
Make your `val()` and `operator<()` `const` functions. The same for `Sort::operator()` — take `const Thing&` instead of `Thing&`.
Need help with STL sort algorithm
[ "", "c++", "algorithm", "stl", "sorting", "" ]
How to reset my program (close.. and Open again) in C# windows-mobile ?
Create a WinMo cmdline project in your solution and use Process.Start(appPath + @"\yourprogram.exe", String.Empty); (you can use Thread.sleep too before the Process.Start) in your main program use Application.Exit and after that use a Process.Start to the loader application. Maybe pass bye a parameter too then from the loader application cannot start your app only if you do it from your code and pass that "key" to the other app. I hope it helps
The only way it can be done is making an exit in program after placing a request in some task-scheduler to start it again
How to reset my program (close.. and Open again) - Windows mobile
[ "", "c#", "windows-mobile", "" ]
If I have a description like: > "We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply." And all I want is: > "We prefer questions that can be answered, not just discussed." I figure I would search for a regular expression, like "[.!\?]", determine the strpos and then do a substr from the main string, but I imagine it's a common thing to do, so hoping someone has a snippet lying around.
A slightly more costly expression, however will be more adaptable if you wish to select multiple types of punctuation as sentence terminators. ``` $sentence = preg_replace('/([^?!.]*.).*/', '\\1', $string); ``` Find termination characters followed by a space ``` $sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $string); ```
``` <?php $text = "We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply."; $array = explode('.',$text); $text = $array[0]; ?> ```
Does anyone have a PHP snippet of code for grabbing the first "sentence" in a string?
[ "", "php", "string", "code-snippets", "" ]
Is it possible to change the frame rate of an avi file using the Video for windows library? I tried the following steps but did not succeed. 1. AviFileInit 2. AviFileOpen(OF\_READWRITE) 3. pavi1 = AviFileGetStream 4. avi\_info = AviStreamInfo 5. avi\_info.dwrate = 15 6. EditStreamSetInfo(dwrate) returns -2147467262.
I'm pretty sure the AVIFile\* APIs don't support this. (Disclaimer: I was the one who defined those APIs, but it was over 15 years ago...) You can't just call EditStreamSetInfo on an plain AVIStream, only one returned from CreateEditableStream. You could use AVISave, then, but that would obviously re-copy the whole file. So, yes, you would probably want to do this by parsing the AVI file header enough to find the one DWORD you want to change. There are lots of documents on the RIFF and AVI file formats out there, such as <http://www.opennet.ru/docs/formats/avi.txt>.
I don't know anything about VfW, but you could always try hex-editing the file. The framerate is probably a field somewhere in the header of the AVI file. Otherwise, you can script some tool like mencoder[1] to copy the stream to a new file under a different framerate. ``` [1] http://www.mplayerhq.hu/ ```
Edit the frame rate of an avi file
[ "", "c++", "vfw", "" ]
I found a code of winform here: <http://www.wincustomize.com/articles.aspx?aid=136426&c=1> And it works fine as a winform. But I want to run the code in a web app. 1. I add the references of System.Windows.Forms and the Microsoft.mshtml.dll in the C:\Program Files\Microsoft.NET\Primary Interop Assemblies\ to my web app. 2. I copy the WebPageBitmap.cs into my web app. 3. I copy the Program.cs 's Main() to my web app as a Button\_Click(). 4. When I click the button in my web app. It occurs an error: ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment. How can I use System.Windows.Forms.WebBrowser in a web app to get a Web Site Thumbnail? ``` public partial class Capture01 : System.Web.UI.Page { public delegate void WebBrowserDocumentCompletedEventHandler(object sender, WebBrowserDocumentCompletedEventArgs e); [STAThread] protected void Button1_Click(object sender, EventArgs e) { int width = 1024; int height = 900; int thumbwidth = width; int thumbheight = height; string fileName = "image01.jpg"; string url = "http://www.iweixtest.cn/WE/Site/1647/index.aspx"; thumbwidth = 150; thumbheight = 100; //WebPageBitmap webBitmap = new WebPageBitmap(args[0], width, height, false, 10000); WebPageBitmap webBitmap = new WebPageBitmap(url, width, height, false, 10000); if (webBitmap.IsOk) { webBitmap.Fetch(); Bitmap thumbnail = webBitmap.GetBitmap(thumbwidth, thumbheight); //thumbnail.Save(args[1], ImageFormat.Jpeg); thumbnail.Save(fileName, ImageFormat.Jpeg); thumbnail.Dispose(); } else { MessageBox.Show(webBitmap.ErrorMessage); } } } ``` WebPageBitmap.cs ``` namespace GetSiteThumbnail { /// <summary> /// Thanks for the solution to the "sometimes not painting sites to Piers Lawson /// Who performed some extensive research regarding the origianl implementation. /// You can find his codeproject profile here: /// http://www.codeproject.com/script/Articles/MemberArticles.aspx?amid=39324 /// </summary> [InterfaceType(1)] [Guid("3050F669-98B5-11CF-BB82-00AA00BDCE0B")] public interface IHTMLElementRender2 { void DrawToDC(IntPtr hdc); void SetDocumentPrinter(string bstrPrinterName, ref _RemotableHandle hdc); } /// <summary> /// Code by Adam Najmanowicz /// http://www.codeproject.com/script/Membership/Profiles.aspx?mid=923432 /// http://blog.najmanowicz.com/ /// Some improvements suggested by Frank Herget /// http://www.artviper.net/ /// </summary> class WebPageBitmap { private WebBrowser webBrowser; private string url; private int width; private int height; private bool isOk; private string errorMessage; public string ErrorMessage { get { return errorMessage; } } public bool IsOk { get { return isOk; } set { isOk = value; } } public WebPageBitmap(string url, int width, int height, bool scrollBarsEnabled, int wait) { this.width = width; this.height = height; this.url = url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) ? url : this.url = "http://" + url; try // needed as the script throws an exeception if the host is not found { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(this.url); req.AllowAutoRedirect = true; //req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)"; //成功 req.UserAgent = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; //req.Referer = "http://www.cognifide.com"; req.ContentType = "text/html"; req.Accept = "*/*"; req.KeepAlive = false; using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) { string x = resp.StatusDescription; } } catch (Exception ex) { errorMessage = ex.Message; isOk = false; return; } isOk = true; // public, to check in program.cs if the domain is found, so the image can be saved webBrowser = new WebBrowser(); webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(documentCompletedEventHandler); webBrowser.Size = new Size(width, height); webBrowser.ScrollBarsEnabled = false; } /// <summary> /// Fetches the image /// </summary> /// <returns>true is the operation ended with a success</returns> public bool Fetch() { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.AllowAutoRedirect = true; //req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)"; req.UserAgent = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; //req.Referer = "http://www.cognifide.com"; req.ContentType = "text/html"; req.AllowWriteStreamBuffering = true; req.AutomaticDecompression = DecompressionMethods.GZip; req.Method = "GET"; req.Proxy = null; req.ReadWriteTimeout = 20; HttpStatusCode status; using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) { status = resp.StatusCode; } if (status == HttpStatusCode.OK || status == HttpStatusCode.Moved) { webBrowser.Navigate(url); while (webBrowser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } return true; } else { return false; } } private void documentCompletedEventHandler(object sender, WebBrowserDocumentCompletedEventArgs e) { ((WebBrowser)sender).Document.Window.Error += new HtmlElementErrorEventHandler(SuppressScriptErrorsHandler); } public void SuppressScriptErrorsHandler(object sender, HtmlElementErrorEventArgs e) { e.Handled = true; MessageBox.Show("Error!"); } internal Bitmap GetBitmap(int thumbwidth, int thumbheight) { IHTMLDocument2 rawDoc = (IHTMLDocument2)webBrowser.Document.DomDocument; IHTMLElement rawBody = rawDoc.body; IHTMLElementRender2 render = (IHTMLElementRender2)rawBody; Bitmap bitmap = new Bitmap(width, height); Rectangle bitmapRect = new Rectangle(0, 0, width, height); // Interesting thing that despite using the renderer later // this following line is still necessary or // the background may not be painted on some websites. webBrowser.DrawToBitmap(bitmap, bitmapRect); using (Graphics graphics = Graphics.FromImage(bitmap)) { IntPtr graphicshdc = graphics.GetHdc(); render.DrawToDC(graphicshdc); graphics.ReleaseHdc(graphicshdc); graphics.Dispose(); if (thumbheight == height && thumbwidth == width) { return bitmap; } else { Bitmap thumbnail = new Bitmap(thumbwidth, thumbheight); using (Graphics gfx = Graphics.FromImage(thumbnail)) { // high quality image sizing gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; gfx.InterpolationMode = InterpolationMode.HighQualityBicubic; // make it look pretty gfx.DrawImage(bitmap, new Rectangle(0, 0, thumbwidth, thumbheight), bitmapRect, GraphicsUnit.Pixel); } bitmap.Dispose(); return thumbnail; } } } } } ```
I have successfully used System.Windows.Forms.WebBrowser in a web app. Just follow the steps above and add AspCompat="true" in the webform page: Thank you for all the answers.
You could create your own worker thread and call [SetApartmentState](http://msdn.microsoft.com/en-us/library/system.threading.thread.setapartmentstate.aspx) to change it to an STA thread; this thread could do the work of rendering web pages. However, a lot of inter-thread communication would be required and, as R. Bemrose said, the `System.Windows` classes aren't really designed to be used inside a web app. Another approach would be to rewrite the sample application (as a .EXE) to take two parameters: (1) the URL to download, and (2) the output location for the screenshot image. Your web app could create a temp path (for the output file), launch this program (with [Process.Start](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx)), wait for it to finish, load the output file it created, then delete the temp file once it had been sent to the client or was otherwise no longer necessary. (It would, of course, need to have different error handling than displaying a message box if something went wrong.)
How to use System.Windows.Forms.WebBrowser in a web app?
[ "", "c#", ".net", "winforms", "webforms", "webbrowser-control", "" ]
I'm trying to override an overridden method (if that makes sense!) in C#. I have a scenario similar to the below, but when I have a breakpoint in the SampleMethod() in the "C" class it's not being hit, whilst the same breakpoint in the "B" method is being hit. ``` public class A { protected virtual void SampleMethod() {} } public class B : A { protected override void SampleMethod() { base.SampleMethod(); } } public class C : B { protected override void SampleMethod() { base.SampleMethod(); } } ``` Thanks in advance! --- **Edit:** Ok, the context would help: This is in the context of a composite control so class A inherits from CompositeControl and calls SampleMethod() after overriding the CreateChildControls() method.
Without seeing the code that calls SampleMethod, my guess would be that you have an object of type B and call SampleMethod on that.
Overriding can be performed in a chain as long as you like. The code you have shown is correct. The only possible explanation for the behaviour you are seeing is that the object to which you are referring is actually of type `B`. I suggest that you double check this, and if things still don't make sense, post the other appropiate code.
Override an overridden method (C#)
[ "", "c#", "inheritance", "" ]
I work with different servers and configurations. What is the best java code approach for getting the scheme://host:[port if it is not port 80]. Here is some code I have used, but don't know if this is the best approach. (this is pseudo code) HttpServletRequest == request ``` String serverName = request.getServerName().toLowerCase(); String scheme = request.getScheme(); int port = request.getServerPort(); String val = scheme + "://" + serverName + ":" port; ``` Such that val returns: ``` http(s)://server.com/ ``` or ``` http(s)://server.com:7770 ``` Basically, I need everything but the query string and 'context'. I was also consider using URL: ``` String absURL = request.getRequestURL(); URL url = new URL(absURL); url.get???? ```
try this: ``` URL serverURL = new URL(request.getScheme(), // http request.getServerName(), // host request.getServerPort(), // port ""); // file ``` **EDIT** hiding default port on **http** and **https**: ``` int port = request.getServerPort(); if (request.getScheme().equals("http") && port == 80) { port = -1; } else if (request.getScheme().equals("https") && port == 443) { port = -1; } URL serverURL = new URL(request.getScheme(), request.getServerName(), port, ""); ```
``` URI u=new URI("http://www.google.com/"); String s=u.getScheme()+"://"+u.getHost()+":"+u.getPort(); ``` As Cookie said, from java.net.URI ([docs](http://java.sun.com/j2se/1.5.0/docs/api/java/net/URI.html)).
Java: String representation of just the host, scheme, possibly port from servlet request
[ "", "java", "servlets", "request", "" ]
I typically code my PHP with one level of indentation after the initial `<?php`, but I'm having trouble finding a setting for this in Emacs with `php-mode`. To be clear, here's what Emacs is doing: ``` <?php echo "Hello."; if (something) do_something(); ``` And here's how I usually code: ``` <?php echo "Hello."; if (something) do_something(); ``` Emacs version 23 (straight from CVS), php-mode 1.5.0.
Found a solution, I think: ``` (c-set-offset 'topmost-intro 4) (c-set-offset 'cpp-macro -4) ``` Seems to be working. `topmost-intro` sets everything, and as far as I can tell `cpp-macro` only sets the `<?php` tags. Thanks to Cheeso for the hint which led me to the answer.
I don't have a php-mode, but in c-modes, M-x c-set-offset can help. - it'll allow you to customize the offset for a syntactic element, and it shows you what element was used for the current line.
Setting initial indent level for PHP in Emacs?
[ "", "php", "emacs", "indentation", "" ]
I'm searching a nice way to send a java object to my rest web service. It's possible or not ? For sample I wan't to send an "User" Object to my rest : ``` public Class User{ private String name; private String surname; public getName(){ return name; } public setName(String name){ [...] } ``` It's possible to generate AUTOMATICALY this kind of Rest ? www.foo.com/createUser/name="foo"&surname="foo"
Have a look at [Restlet](http://www.restlet.org/). The [tutorial](http://www.restlet.org/documentation/2.0/firstSteps) shows you how to get started. Restlet allows you to use a number of representation formats, including [XML](http://www.restlet.org/documentation/snapshot/ext/org/restlet/ext/xml/package-use.html) and [JSON](http://www.restlet.org/documentation/1.0/ext/org/restlet/ext/json/package-summary.html).
I would consider using a JSON representation for this kind of Java objects. I prefer the Jersey implementation of JAX-RS and it has built-in support for JSON serialization over JAXB. Hope this helps...
Send java object to a rest WebService
[ "", "java", "rest", "object", "auto-generate", "" ]
I would like to programmaticly get a stored major version number for a C# project in both Debug and Release builds. Where could I store this version number and how do i access it?
Go to Project Properties | Application | Assembly Information. You can access the version via `Assembly.GetExecutingAssembly().GetName().Version`
The version number is typically defined in the AssemblyInfo.cs file (located in the Properties folder). You can get the version number programmatically like this: ``` Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Version.ToString()); ``` Or, if you want to access the different parts: ``` Version version = Assembly.GetExecutingAssembly().GetName().Version; Console.WriteLine("Major={0}, Minor={1}", version.Major, version.Minor); ``` See the [`Version` class documentation](http://msdn.microsoft.com/en-us/library/system.version.aspx) for more details.
Whats the best way to store a version number in a Visual Studio 2008 project?
[ "", "c#", "visual-studio-2008", "build-process", "" ]
I have been working on a comparatively large system on my own, and it's my first time working on a large system(dealing with 200+ channels of information simultaneously). I know how to use Junit to test every method, and how to test boundary conditions. But still, for system test, I need to test all the interfacing and probably so some stress test as well (maybe there are other things to do, but I don't know what they are). I am totally new to the world of testing, and please give me some suggestions or point me to some info on how a good code tester would do system testing. PS: 2 specific questions I have are: how to test private functions? how to testing interfaces and avoid side effects?
Here are two web sites that might help: The first is a list of [open source Java tools](http://java-source.net/open-source/testing-tools). Many of the tools are addons to JUnit that allow either easier testing or testing at a higher integration level. Depending on your system, sometimes JUnit will work for system tests, but the structure of the test can be different. As for private methods, check [this question](https://stackoverflow.com/questions/105007/do-you-test-private-method) (and the question it references). You cannot test interfaces (as there is no behavior), but you can create an abstract base test classes for testing that implementations of an interface follow its contract. EDIT: Also, if you don't already have unit tests, check out [Working Effectivly with Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052); it is a must for testing code that is not set up well for testing.
[Mocking](http://en.wikipedia.org/wiki/Mock_object) is a good way to be able to simulate system tests in unit testing; by replacing (mocking) the resources upon which the other component depends, you can perform unit testing in a "system-like" environment without needing to have the entire system constructed to do it. As to your specific questions: generally, you shouldn't be using unit testing to test private functions; if they're private, they're **private** to the class. If you need to test something, test a public method which uses that private method to do something. Avoiding side effects that can be potentially problematic is best done using either a complete test environment (which can easily be wiped back to a "virgin" state) or using mocking, as described above. And testing interfaces is done by, well, testing the interface methods.
How to best test Java code?
[ "", "java", "testing", "interface", "junit", "" ]
I have an event on one of my classes that I want to attach a handler to. However, I don't need the handler to do anything, as I am just testing the behaviour of the class with handlers attached or not. The event signature is as follows: ``` public event EventHandler<EventArgs> Foo; ``` So I want to do something like: ``` myClass.Foo += (); ``` However this isn't a valid lambda expression. What is the most succinct way to express this?
``` myClass.Foo += (s,e) => {}; ``` or ``` myClass.Foo += delegate {}; ```
``` (x,y) => {} //oops forgot the params ``` OK? :) Or ``` delegate {} ```
No-op lambda
[ "", "c#", ".net", "lambda", "" ]
I'm trying to create a transparent button in C# (.NET 3.5 SP1) to use in my WinForms application. I've tried everything to get the button to be transparent (it should show the gradient background underneath the button) but it's just not working. Here is the code I'm using: ``` public class ImageButton : ButtonBase, IButtonControl { public ImageButton() { this.SetStyle( ControlStyles.SupportsTransparentBackColor | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); this.BackColor = Color.Transparent; } protected override void OnPaint(PaintEventArgs pevent) { Graphics g = pevent.Graphics; g.FillRectangle(Brushes.Transparent, this.ClientRectangle); g.DrawRectangle(Pens.Black, this.ClientRectangle); } // rest of class here... } ``` The problem is that the button seems to be grabbing random UI memory from somewhere and filling itself with some buffer from Visual Studio's UI (when in design mode). At runtime it's grabbing some zero'd buffer and is completely black. My ultimate goal is to paint an image on an invisible button instead of the rectangle. The concept should stay the same however. When the user hovers over the button then a button-type shape is drawn. Any ideas? **EDIT: Thanks everybody, the following worked for me:** ``` public class ImageButton : Control, IButtonControl { public ImageButton() { SetStyle(ControlStyles.SupportsTransparentBackColor, true); SetStyle(ControlStyles.Opaque, true); SetStyle(ControlStyles.ResizeRedraw, true); this.BackColor = Color.Transparent; } protected override void OnPaint(PaintEventArgs pevent) { Graphics g = pevent.Graphics; g.DrawRectangle(Pens.Black, this.ClientRectangle); } protected override void OnPaintBackground(PaintEventArgs pevent) { // don't call the base class //base.OnPaintBackground(pevent); } protected override CreateParams CreateParams { get { const int WS_EX_TRANSPARENT = 0x20; CreateParams cp = base.CreateParams; cp.ExStyle |= WS_EX_TRANSPARENT; return cp; } } // rest of class here... } ```
WinForms (and underlying User32) does not support transparency at all. WinForms however can simulate transparency by using control style you provide - SupportsTransparentBackColor, but in this case all that "transparent" control does, it to allow drawing parent its background. ButtonBase uses some windows styles that prevent working this mechanism. I see two solutions: one is to derive your control from Control (instead of ButtonBase), and second is to use Parent's DrawToBitmap to get background under your button, and then draw this image in OnPaint.
In winforms there are some tricks to allow a control having its background correctly painted when using transparency. You can add this code to the OnPaint or OnPaintBackground to get the controls you have in the background being painted: ``` if (this.Parent != null) { GraphicsContainer cstate = pevent.Graphics.BeginContainer(); pevent.Graphics.TranslateTransform(-this.Left, -this.Top); Rectangle clip = pevent.ClipRectangle; clip.Offset(this.Left, this.Top); PaintEventArgs pe = new PaintEventArgs(pevent.Graphics, clip); //paint the container's bg InvokePaintBackground(this.Parent, pe); //paints the container fg InvokePaint(this.Parent, pe); //restores graphics to its original state pevent.Graphics.EndContainer(cstate); } else base.OnPaintBackground(pevent); // or base.OnPaint(pevent);... ```
Drawing a transparent button
[ "", "c#", "winforms", "button", "gdi+", "" ]
For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple\_server and access a simple Hello World return in the same .py file. This is the extent of what I understand though, heh. How do I integrate the simple\_server and your basic XHTML/CSS files? I want to start the server and automagically call, for instance, index.py (does it need to be .py?). Obviously within the index file I would have my markup and stylesheet and I would operate it like a normal site at that point. My eventual goal is to get a basic message board going (post, edit, delete, user sessions). I realize I'll need access to a database, and I know my way around MySQL enough to not have to worry about those portions. Thanks for the help. EDIT: Allow me to clarify my goal, as I have been told Python does a LOT more than PHP. My goal is to begin building simple web applications into my pre-existing static XHTML pages. Obviously with PHP, you simply make sure its installed on your server and you start writing the code. I'd like to know how different Python is in that sense, and what I have to do to, say, write a basic message board in Python.
**"Obviously with PHP, you simply make sure its installed on your server and you start writing the code."** Not true with Python. Python is just a language, not an Apache plug-in like PHP. Generally, you can use something like [mod\_wsgi](http://code.google.com/p/modwsgi/) to create a Python plug-in for Apache. What you find is that web page processing involves a lot of steps, none of which are part of the Python *language*. You must use either extension libraries or a framework to process web requests in Python. [At this point, some PHP folks ask why Python is so popular. And the reason is because you have choices of which library or framework to use.] PHP parses the request and allows you to embed code in the resulting page. Python frameworks -- generally -- do not work this way. Most Python frameworks break the operation down into several steps. 1. Parsing the URL and locating an appropriate piece of code. 2. Running the code to get a result data objects. 3. Interpolating the resulting data objects into HTML templates. **"My goal is to begin building simple web applications into my pre-existing static XHTML pages."** Let's look at how you'd do this in [Django](http://www.djangoproject.com). 1. Create a Django project. 2. Create a Django app. 3. Transform your XTHML pages into Django templates. Pull out the dynamic content and put in `{{ somevariable }}` markers. Depending on what the dynamic content is, this can be simple or rather complex. 4. Define URL to View function mappings in your `urls.py` file. 5. Define view functions in your `views.py` file. These view functions create the dynamic content that goes in the template, and which template to render. At that point, you should be able to start the server, start a browser, pick a URL and see your template rendered. **"write a basic message board in Python."** Let's look at how you'd do this in [Django](http://www.djangoproject.com). 1. Create a Django project. 2. Create a Django app. 3. Define your data model in `models.py` 4. Write unit tests in `tests.py`. Test your model's methods to be sure they all work properly. 5. Play with the built-in admin pages. 6. Create Django templates. 7. Define URL to View function mappings in your `urls.py` file. 8. Define view functions in your `views.py` file. These view functions create the dynamic content that goes in the template, and which template to render.
I would recommend [Django](http://www.djangoproject.com/).
What to do after starting simple_server?
[ "", "python", "" ]
Is it possible to call a method on the type you pass into your generic method? Something like: ``` public class Blah<T> { public int SomeMethod(T t) { int blah = t.Age; return blah; } } ```
You can if there's some type to constrain T to: ``` public int SomeMethod(T t) where T : ISomeInterface { // ... } public interface ISomeInterface { int Age { get; } } ``` The type could be a base class instead - but there has to be *something* to let the compiler know that there'll definitely be an `Age` property. (In C# 4 you could use dynamic typing, but I wouldn't do that unless it were a particularly "special" situation which actually justified it.)
Expanding on Jon's answer. Yet another way is to take a functional approach to the problem ``` public int SomeMethod(T t, Func<T,int> getAge) { int blah = getAge(t); ... } ```
Is it possible to call a method on the type you pass into your generic method?
[ "", "c#", "generics", "" ]
When trying to render a Django template file in Google App Engine > from google.appengine.ext.webapp import template > > templatepath = os.path.join(os.path.dirname(**file**), 'template.html') > self.response.out.write (template.render( templatepath , template\_values)) I come across the following error: > <type > 'exceptions.UnicodeDecodeError'>: > 'ascii' codec can't decode byte 0xe2 > in position 17692: ordinal not in > range(128) > args = ('ascii', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 > Str...07/a-beautiful-method-to-find-peace-of-mind/ > --> > ', 17692, 17693, 'ordinal not in range(128)') > encoding = 'ascii' > end = 17693 > message = '' > object = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 > Str...07/a-beautiful-method-to-find-peace-of-mind/ > --> > reason = 'ordinal not in range(128)' > start = 17692 It seems that the underlying django template engine has assumed the "ascii" encoding, which should have been "utf-8". Anyone who knows what might have caused the trouble and how to solve it? Thanks.
Well, turns out the rendered results returned by the template needs to be decoded first: > self.response.out.write (template.render( templatepath , template\_values).decode('utf-8') ) A silly mistake, but thanks for everyone's answers anyway. :)
Are you using Django 0.96 or Django 1.0? You can check by looking at your main.py and seeing if it contains the following: ``` from google.appengine.dist import use_library use_library('django', '1.0') ``` If you're using Django 1.0, both FILE\_CHARSET and DEFAULT\_CHARSET should default to 'utf-8'. If your template is saved under a different encoding, just set FILE\_CHARSET to whatever that is. If you're using Django 0.96, you might want to try directly reading the template from the disk and then manually handling the encoding. e.g., replace `template.render( templatepath , template_values)` with `Template(unicode(template_fh.read(), 'utf-8')).render(template_values)`
Google App engine template unicode decoding problem
[ "", "python", "django", "google-app-engine", "unicode", "" ]
Is there a difference between `!==` and `!=` in PHP?
The `!=` operator compares value, while the `!==` operator compares type as well. That means this: ``` var_dump(5!="5"); // bool(false) var_dump(5!=="5"); // bool(true), because "5" and 5 are of different types ```
`!=` is the inverse of the `==` operator, which checks equality across types `!==` is the inverse of the `===` operator, which checks equality only for things of the same type.
Is there a difference between !== and != in PHP?
[ "", "php", "comparison", "operators", "" ]
What is the main purpose of using [CROSS APPLY](http://technet.microsoft.com/en-us/library/ms175156.aspx)? I have read (vaguely, through posts on the Internet) that `cross apply` can be more efficient when selecting over large data sets if you are partitioning. (Paging comes to mind) I also know that `CROSS APPLY` doesn't require a UDF as the right-table. In most `INNER JOIN` queries (one-to-many relationships), I could rewrite them to use `CROSS APPLY`, but they always give me equivalent execution plans. Can anyone give me a good example of when `CROSS APPLY` makes a difference in those cases where `INNER JOIN` will work as well? --- **Edit:** Here's a trivial example, where the execution plans are exactly the same. (Show me one where they differ and where `cross apply` is faster/more efficient) ``` create table Company ( companyId int identity(1,1) , companyName varchar(100) , zipcode varchar(10) , constraint PK_Company primary key (companyId) ) GO create table Person ( personId int identity(1,1) , personName varchar(100) , companyId int , constraint FK_Person_CompanyId foreign key (companyId) references dbo.Company(companyId) , constraint PK_Person primary key (personId) ) GO insert Company select 'ABC Company', '19808' union select 'XYZ Company', '08534' union select '123 Company', '10016' insert Person select 'Alan', 1 union select 'Bobby', 1 union select 'Chris', 1 union select 'Xavier', 2 union select 'Yoshi', 2 union select 'Zambrano', 2 union select 'Player 1', 3 union select 'Player 2', 3 union select 'Player 3', 3 /* using CROSS APPLY */ select * from Person p cross apply ( select * from Company c where p.companyid = c.companyId ) Czip /* the equivalent query using INNER JOIN */ select * from Person p inner join Company c on p.companyid = c.companyId ```
> Can anyone give me a good example of when CROSS APPLY makes a difference in those cases where INNER JOIN will work as well? See the article in my blog for detailed performance comparison: * [**`INNER JOIN` vs. `CROSS APPLY`**](http://explainextended.com/2009/07/16/inner-join-vs-cross-apply/) `CROSS APPLY` works better on things that have no simple `JOIN` condition. This one selects `3` last records from `t2` for each record from `t1`: ``` SELECT t1.*, t2o.* FROM t1 CROSS APPLY ( SELECT TOP 3 * FROM t2 WHERE t2.t1_id = t1.id ORDER BY t2.rank DESC ) t2o ``` It cannot be easily formulated with an `INNER JOIN` condition. You could probably do something like that using `CTE`'s and window function: ``` WITH t2o AS ( SELECT t2.*, ROW_NUMBER() OVER (PARTITION BY t1_id ORDER BY rank) AS rn FROM t2 ) SELECT t1.*, t2o.* FROM t1 INNER JOIN t2o ON t2o.t1_id = t1.id AND t2o.rn <= 3 ``` , but this is less readable and probably less efficient. **Update:** Just checked. `master` is a table of about `20,000,000` records with a `PRIMARY KEY` on `id`. This query: ``` WITH q AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM master ), t AS ( SELECT 1 AS id UNION ALL SELECT 2 ) SELECT * FROM t JOIN q ON q.rn <= t.id ``` runs for almost `30` seconds, while this one: ``` WITH t AS ( SELECT 1 AS id UNION ALL SELECT 2 ) SELECT * FROM t CROSS APPLY ( SELECT TOP (t.id) m.* FROM master m ORDER BY id ) q ``` is instant.
Consider you have two tables. **MASTER TABLE** ``` x------x--------------------x | Id | Name | x------x--------------------x | 1 | A | | 2 | B | | 3 | C | x------x--------------------x ``` **DETAILS TABLE** ``` x------x--------------------x-------x | Id | PERIOD | QTY | x------x--------------------x-------x | 1 | 2014-01-13 | 10 | | 1 | 2014-01-11 | 15 | | 1 | 2014-01-12 | 20 | | 2 | 2014-01-06 | 30 | | 2 | 2014-01-08 | 40 | x------x--------------------x-------x ``` There are many situations where we need to replace `INNER JOIN` with `CROSS APPLY`. **1. Join two tables based on `TOP n` results** Consider if we need to select `Id` and `Name` from `Master` and last two dates for each `Id` from `Details table`. ``` SELECT M.ID,M.NAME,D.PERIOD,D.QTY FROM MASTER M INNER JOIN ( SELECT TOP 2 ID, PERIOD,QTY FROM DETAILS D ORDER BY CAST(PERIOD AS DATE)DESC )D ON M.ID=D.ID ``` * **[SQL FIDDLE](http://sqlfiddle.com/#!3/a633c/1)** The above query generates the following result. ``` x------x---------x--------------x-------x | Id | Name | PERIOD | QTY | x------x---------x--------------x-------x | 1 | A | 2014-01-13 | 10 | | 1 | A | 2014-01-12 | 20 | x------x---------x--------------x-------x ``` See, it generated results for last two dates with last two date's `Id` and then joined these records only in the outer query on `Id`, which is wrong. This should be returning both `Ids` 1 and 2 but it returned only 1 because 1 has the last two dates. To accomplish this, we need to use `CROSS APPLY`. ``` SELECT M.ID,M.NAME,D.PERIOD,D.QTY FROM MASTER M CROSS APPLY ( SELECT TOP 2 ID, PERIOD,QTY FROM DETAILS D WHERE M.ID=D.ID ORDER BY CAST(PERIOD AS DATE)DESC )D ``` * **[SQL FIDDLE](http://sqlfiddle.com/#!3/a633c/2)** and forms the following result. ``` x------x---------x--------------x-------x | Id | Name | PERIOD | QTY | x------x---------x--------------x-------x | 1 | A | 2014-01-13 | 10 | | 1 | A | 2014-01-12 | 20 | | 2 | B | 2014-01-08 | 40 | | 2 | B | 2014-01-06 | 30 | x------x---------x--------------x-------x ``` Here's how it works. The query inside `CROSS APPLY` can reference the outer table, where `INNER JOIN` cannot do this (it throws compile error). When finding the last two dates, joining is done inside `CROSS APPLY` i.e., `WHERE M.ID=D.ID`. **2. When we need `INNER JOIN` functionality using functions.** `CROSS APPLY` can be used as a replacement with `INNER JOIN` when we need to get result from `Master` table and a `function`. ``` SELECT M.ID,M.NAME,C.PERIOD,C.QTY FROM MASTER M CROSS APPLY dbo.FnGetQty(M.ID) C ``` And here is the function ``` CREATE FUNCTION FnGetQty ( @Id INT ) RETURNS TABLE AS RETURN ( SELECT ID,PERIOD,QTY FROM DETAILS WHERE ID=@Id ) ``` * **[SQL FIDDLE](http://sqlfiddle.com/#!3/5e731/1)** which generated the following result ``` x------x---------x--------------x-------x | Id | Name | PERIOD | QTY | x------x---------x--------------x-------x | 1 | A | 2014-01-13 | 10 | | 1 | A | 2014-01-11 | 15 | | 1 | A | 2014-01-12 | 20 | | 2 | B | 2014-01-06 | 30 | | 2 | B | 2014-01-08 | 40 | x------x---------x--------------x-------x ``` **ADDITIONAL ADVANTAGE OF CROSS APPLY** `APPLY` can be used as a replacement for `UNPIVOT`. Either `CROSS APPLY` or `OUTER APPLY` can be used here, which are interchangeable. Consider you have the below table(named `MYTABLE`). ``` x------x-------------x--------------x | Id | FROMDATE | TODATE | x------x-------------x--------------x | 1 | 2014-01-11 | 2014-01-13 | | 1 | 2014-02-23 | 2014-02-27 | | 2 | 2014-05-06 | 2014-05-30 | | 3 | NULL | NULL | x------x-------------x--------------x ``` The query is below. ``` SELECT DISTINCT ID,DATES FROM MYTABLE CROSS APPLY(VALUES (FROMDATE),(TODATE)) COLUMNNAMES(DATES) ``` * **[SQL FIDDLE](http://sqlfiddle.com/#!3/57e22/1)** which brings you the result ``` x------x-------------x | Id | DATES | x------x-------------x | 1 | 2014-01-11 | | 1 | 2014-01-13 | | 1 | 2014-02-23 | | 1 | 2014-02-27 | | 2 | 2014-05-06 | | 2 | 2014-05-30 | | 3 | NULL | x------x-------------x ```
When should I use CROSS APPLY over INNER JOIN?
[ "", "sql", "sql-server", "performance", "t-sql", "cross-apply", "" ]
How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I'm not looking to achieve smooth scrolling.
If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript `window.scrollTo()` method -- passing in `0, 0` will scroll the page to the top left instantly. ``` window.scrollTo(xCoord, yCoord); ``` Parameters * xCoord is the pixel along the horizontal axis. * yCoord is the pixel along the vertical axis.
If you do want smooth scrolling, try something like this: ``` $("a[href='#top']").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; }); ``` That will take any `<a>` tag whose `href="#top"` and make it smooth scroll to the top.
Scroll to the top of the page using JavaScript?
[ "", "javascript", "scroll", "" ]
From the [`Pattern`](http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html) javadocs: ``` Greedy quantifiers: X? X, once or not at all X* X, zero or more times X+ X, one or more times X{n} X, exactly n times X{n,} X, at least n times X{n,m} X, at least n but not more than m times Reluctant quantifiers: X?? X, once or not at all X*? X, zero or more times X+? X, one or more times X{n}? X, exactly n times X{n,}? X, at least n times X{n,m}? X, at least n but not more than m times ``` The description of what they do is the same...so, what is the difference? I would really appreciate some examples. *I am coding in Java, but I hear this concept is the same for most modern regex implementations.*
A greedy operator always try to "grab" as much of the input as possible, while a reluctant quantifier will match as little of the input as possible and still create a match. Example: ``` "The red fox jumped over the red fence" /(.*)red/ => \1 = "The red fox jumped over the " /(.*?)red/ => \1 = "The " "aaa" /a?a*/ => \1 = "a", \2 = "aa" /a??a*/ => \1 = "", \2 = "aaa" "Mr. Doe, John" /^(?:Mrs?.)?.*\b(.*)$/ => \1 = "John" /^(?:Mrs?.)?.*?\b(.*)$/ => \1 = "Doe, John" ```
From [this link](http://java.sun.com/docs/books/tutorial/essential/regex/quant.html), where the tutorial author acknowledges the spirit of your question: > At first glance it may appear that > the quantifiers X?, X?? and X?+ do > exactly the same thing, since they all > promise to match "X, once or not at > all". There are subtle implementation > differences which will be explained > near the end of this section. They go on to put together examples and offer the explanation: > Greedy quantifiers are considered > "greedy" because they force the > matcher to read in, or eat, the entire > input string prior to attempting the > first match. If the first match > attempt (the entire input string) > fails, the matcher backs off the input > string by one character and tries > again, repeating the process until a > match is found or there are no more > characters left to back off from. > Depending on the quantifier used in > the expression, the last thing it will > try matching against is 1 or 0 > characters. > > The reluctant quantifiers, however, > take the opposite approach: They start > at the beginning of the input string, > then reluctantly eat one character at > a time looking for a match. The last > thing they try is the entire input > string. And for extra credit, the possessive explanation: > Finally, the possessive quantifiers > always eat the entire input string, > trying once (and only once) for a > match. Unlike the greedy quantifiers, > possessive quantifiers never back off, > even if doing so would allow the > overall match to succeed.
What is the difference between `Greedy` and `Reluctant` regular expression quantifiers?
[ "", "java", "regex", "" ]
I'm testing my company's established Swing application for accessibility issues. With high contrast mode enabled on my PC certain parts of this application are rendered properly (white-on-black) and some incorrectly (black-on-white). The bits that are correct are the native components (JButton, JLabel and whatnot) and third party components from the likes of JIDE. The incorrect bits are custom components and renderers developed in-house without consideration for high-contrast mode. Clearly it's possible to detect when high-contrast mode is enabled. How do I do this?
Turns out the win.highContrast.on property was added in Java 1.4.1 for this purpose. ``` public static void main(String[] args) { Toolkit toolkit = Toolkit.getDefaultToolkit(); Boolean highContrast = (Boolean)toolkit.getDesktopProperty( "win.highContrast.on" ); } ``` This only works on Windows (hence the `win.` prefix). On linux and Mac `highContrast` will be null. It'll be safest to do a platform check first, or a nullcheck on `highContrast`.
Extract from this link : <http://www.section508.gov/IRSCourse/mod02/printJava.html> "Windows software can check for the high contrast setting by calling the SystemParametersInfo function with the SPI\_GETHIGHCONTRAST value. Applications should query and support this value during initialization and when processing WM\_COLORCHANGE messages." This is to access via the Win32 API : <http://msdn.microsoft.com/en-us/library/ms724947(VS.85).aspx> (Not fully sure how, though, not really good in that field, hope someone can complete)
How do I detect if a display is in High Contrast mode?
[ "", "java", "swing", "accessibility", "high-contrast", "" ]
I'm bumping into some`null` fields in a SQL2005 db. Some report `Null` and others have values like `1.00` or `713.00`. I'd like a bullet proof way to convert the 'Null's to 0 and the '1.00' and '713.00' values into `Money` types.
``` CREATE TABLE dbo.Test_Text_Convert ( my_string TEXT NULL ) GO INSERT INTO dbo.Test_Text_Convert VALUES (NULL) INSERT INTO dbo.Test_Text_Convert VALUES ('7.10') INSERT INTO dbo.Test_Text_Convert VALUES ('xxx') INSERT INTO dbo.Test_Text_Convert VALUES ('$20.20') INSERT INTO dbo.Test_Text_Convert VALUES ('20.2020') GO SELECT CASE WHEN ISNUMERIC(CAST(my_string AS VARCHAR(MAX))) = 1 THEN CAST(ISNULL(CAST(my_string AS VARCHAR(MAX)), '0') AS MONEY) ELSE 0 END FROM dbo.Test_Text_Convert GO ``` I've set invalid strings to be 0, but you could easily change that behavior.
You can convert from `null` via the `coalesce` function: ``` coalesce(a, b) //returns b if a is null, a otherwise ```
SQL converting Text fields
[ "", "sql", "sql-server-2005", "t-sql", "casting", "" ]
I have a Youtube clip in a hidden DIV on my page. After the page has loaded I wanted the video to load quietly in the background so that when the user clicks the button to "un-hide" the DIV, the video will be ready to go. But the way I have it now, the video starts to load only after the user clicks the button. Is there a change I could make here to have the video loaded in the background and then just hide or show it based on the button click? ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#show_video").click(function(){ $("#hello").show(); }); }); </script> </head> <body> <button id="show_video">Show The Video</button> <div id="hello" style="display:none;"> <object width="630" height="380"><param value="http://www.youtube.com/v/UyyjU8fzEYU&amp;ap=%2526fmt%3D22" name="movie"><param value="window" name="wmode"><param value="true" name="allowFullScreen"><embed width="630" height="380" wmode="window" allowfullscreen="true" type="application/x-shockwave-flash" src="http://www.youtube.com/v/UyyjU8fzEYU&amp;ap=%2526fmt%3D22"></object> </div> </body> </html> ```
Yep. Use `visibility:hidden` instead of `display:none`. `display:none` means that the element isn't rendered as part of the DOM, so it's not loaded until the display property changes to something else. `visibility:hidden` loads the element, but does not show it. Try this: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#show_video").click(function(){ $("#hello").css('visibility','visible'); }); }); </script> </head> <body> <button id="show_video">Show The Video</button> <div id="hello" style="visibility:hidden;"> <object width="630" height="380"><param value="http://www.youtube.com/v/UyyjU8fzEYU&amp;ap=%2526fmt%3D22" name="movie"><param value="window" name="wmode"><param value="true" name="allowFullScreen"><embed width="630" height="380" wmode="window" allowfullscreen="true" type="application/x-shockwave-flash" src="http://www.youtube.com/v/UyyjU8fzEYU&amp;ap=%2526fmt%3D22"></object> </div> </body> </html> ```
I think you need to also show the video. Have you ever noticed on embedded videos in webpages that they don't even show the preview static image until they scroll into view? I think you will be fighting YouTube's algorithms on that one. its probably their goal NOT to load videos until a user clicks on them.
The Youtube video in my hidden DIV only starts to load after the DIV is shown
[ "", "javascript", "jquery", "youtube", "visibility", "" ]
If I write PHP (php5 if it matters) on Windows and Apache is the same as writing PHP on another OS and Apache? I do not mean things like file paths. Thank you.
Mostly, but you have a few things to watch out: * Under \*nix systems path names are case-sensitive, not under Windows. * Under \*nix systems, the path separator is `/`. Under Windows it is `\`, but PHP translates `/` automatically. Either use the `DIRECTORY_SEPARATOR` constant or always use `/`. * Under \*nix systems, the path traversal schema is different. There is no such thing as a drive letter. There are mount points instead. * Under \*nix systems, file permissions are more strict than on Windows by default. * Some functions are not available under Windows or behave differently. These are mostly for low-level functions (memory status, system status). Refer to the PHP documentation. * If you are using `exec()` or any other similar function, the commands won't be the same. Refer to your system documentation. About Apache: You might hit some snags at some point in one server uses PHP as a module and the other one uses it via `fcgi`. Two Apache configured the same way will behave the same way.
I'm going to mark this as community wiki, as I'm just copying and pasting my answer from another [very similar thread](https://stackoverflow.com/questions/809735/hosting-php): Almost, but not quite. There are a couple of things you have to watch out for. **1)** File names: Windows is a case-insensitive operating system. If you create a file Foo.php, you can include it using `include('Foo.php')` OR `include('foo.php')`. When you move your project to Linux/Unix, this will break if you don't have the right case. **2)** There are some language-specific platform differences, generally when it comes to something that relies on integrated OS functionality. These rarely come up, but you might run into them occasionally. For example, the [checkdnsrr()](http://www.php.net/manual/en/function.checkdnsrr.php) function didn't exist in Windows PHP until version 5.3.0. **3)** Installs. The PHP packages you get for Linux/Unix can very widely in what they include in a default install compared to Windows. You need to make sure to test your app on a development box of the opposite platform just to be sure you have all the required libraries compiled/added in, or you'll get some nice fatal errors from an otherwise normal looking app.
Is PHP for Windows the same as Linux, Mac, etc.?
[ "", "php", "" ]
How do I test for `Ctrl` down in [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms)/C#?
``` bool ctrl = ((Control.ModifierKeys & Keys.Control) == Keys.Control); ```
If you want to detect in a Key press handler, you would look at the modifier properties: ``` private void button1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if ((Control.ModifierKeys & Keys.Control) == Keys.Control) { MessageBox.Show("Pressed " + Keys.Control); } } ``` Actually, looking at that and seeing it doesn't use the `e` argument, it seems as long as your "this" is derived from a Form or Control then you can make this call at any time and not just in a keyboard event handler. However, if you wanted to ensure a combination, such as `Ctrl`-`A` was pressed, you would need some additional logic. ``` private void myKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if (((Control.ModifierKeys & Keys.Control) == Keys.Control) && e.KeyChar == 'A') { SelectAll(); } } ```
Test for 'Ctrl' keydown in C#
[ "", "c#", "winforms", "" ]
Ok this is my problem. I am trying something like this: ``` for i in big_list: del glist[:] for j in range(0:val) glist.append(blah[j]) ``` The idea is to reset the list and reuse it for the next set of data points. The problem is, for some reason, if the first list has 3 points, ``` glist[0] glist[1] glist[2] ``` The next list will continue from index 3 and store the last 3 elements in those indexes ``` glist[0] = 4th elem of new list glist[1] = 5th elem of new list glist[2] = 6th elem of new list glist[3] = 1st elem of new list glist[4] = 2nd elem of new list glist[5] = 3rd elem of new list ``` I'm sure it is an issue with allocated space. But how can I achieve this del g\_list[:] so the result is, ``` glist[0] = 1st elem of new list glist[1] = 2nd elem of new list glist[2] = 3rd elem of new list glist[3] = 4th elem of new list glist[4] = 5th elem of new list glist[5] = 6th elem of new list ``` Allocating variable from within loop is not an option. Any ideas?
Change `del glist[:]` to `glist = []`. You don't need to "reuse" or "reallocate" in Python, the garbagecollector will take care of that for you. Also, you use 'i' as the loop variable in both loops. That's going to confuse you sooner or later. :)
you can try ``` glist=[] ```
Reallocating list in python
[ "", "python", "list", "memory-management", "collections", "" ]
I am analyzing someone else's PHP code and I've noticed that the input HTML has many hidden input fields with names that end with '[]', for instance: ``` <input type="hidden" name="ORDER_VALUE[]" value="34" /> <input type="hidden" name="ORDER_VALUE[]" value="17" /> ``` The PHP page that processes this input acquires each value like this: ``` foreach ($_REQUEST["ORDER_VALUE"] as $order_value) { /... } ``` What is the '[]' used for? Specifying that there would be multiple input fields with the same name?
Yes. Basically PHP will know to stick all of those values with the same name into an array. This applies to all input fields, by the way, not just hidden ones.
It passes data as an array to PHP. When you have HTML forms with the same name it will append into comma lists like checkbox lists. Here PHP has processing to convert that to a PHP array based on the [] like so: To get your result sent as an array to your PHP script you name the , or elements like this: ``` <input name="MyArray[]" /> <input name="MyArray[]" /> <input name="MyArray[]" /> <input name="MyArray[]" /> ``` Notice the square brackets after the variable name, that's what makes it an array. You can group the elements into different arrays by assigning the same name to different elements: ``` <input name="MyArray[]" /> <input name="MyArray[]" /> <input name="MyOtherArray[]" /> <input name="MyOtherArray[]" /> ``` This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It's also possible to assign specific keys to your arrays: ``` <input name="AnotherArray[]" /> <input name="AnotherArray[]" /> <input name="AnotherArray[email]" /> <input name="AnotherArray[phone]" /> ``` <https://www.php.net/manual/en/faq.html.php>
Using square brackets in hidden HTML input fields
[ "", "php", "html", "" ]
I've written an abstract base class for unit tests that sets up just enough environment for our tests to run. The class exposes some of the runtime environment bits as properties whose types vary test by test (the property types are type arguments specified in the inheriting, concrete test class). This is all well and good, except a co-worker noticed that he can't view any of the class' properties in the debugger. Turns out the reason is that he had no fields defined in his inheriting class, and the CLR optimized something or other away, so the debugger couldn't display the properties. Is it possible to prevent this in the base class somehow, or do I have to resort to telling everyone they need to define at least one field which is used somewhere during the tests? Edit: Sounds like a likely culprit should be the optimization/debug settings. That said, I'm building the app from Visual Studio in Debug mode, I've double-checked that all projects are set for a debug build, and none of the projects in this solution have the Optimize flag set. Perhaps it would also be relevant to note that I'm using MSTest and the Visual Studio test runner. Edit 2: By "can't view properties" I'm referring to when I evaluate the property in Quickwatch and get a red exclamation mark and a text "Could not evaluate expression" error text. And lest you think I'm entirely off base with my suspicions, adding an instance field that gets initialized in the test initialize method makes the problem go away... Edit 3: Checked the build output. I notice that the compiler is invoked with these options: ``` /debug+ /debug:full /optimize- /define:DEBUG,TRACE ``` I should think that would be enough to stop this from happening, but there you go. :)
I've encountered this same problem before, and it's invariably due to the fact that Debug mode has been turned off in some way. Try checking each of the following: 1. The current build configuration for the solution and the appropiate project(s) is *Debug*. 2. In the *Build* tab of the property pages, the *Optimize code* checkbox is *unchecked*. If this is all correct, then I recommend you paste the text written to the *Output* window here so can we can potentially spot any more unusual cause of the issue.
![Dont Forget the obvious](https://i.stack.imgur.com/R6kM8.png) Make sure your arent trying to debug your release build. All of these compile settings set behind these configurations. The debug version is one for debugging ;-)
Can I prevent the CLR from optimizing away debugging information?
[ "", "c#", ".net", "optimization", "clr", "debugging", "" ]
I'm guessing it's fgets, but I can't find the specific syntax. I'm trying to read out (in a string I'm thinking is easier) the last line added to a log file.
The simplest naive solution is simply: ``` $file = "/path/to/file"; $data = file($file); $line = $data[count($data)-1]; ``` Though, this WILL load the whole file into memory. Possibly a problem (or not). A better solution is this: ``` $file = escapeshellarg($file); // for the security concious (should be everyone!) $line = `tail -n 1 $file`; ```
This looks like it is what you are looking for: [tekkie.flashbit.net: Tail functionality in PHP](http://tekkie.flashbit.net/php/tail-functionality-in-php) It implements a function that uses fseek() with a negative index to roll up the file from the end. You can define how many lines you want to be returned. The code also is available [as a Gist on GitHub](https://gist.github.com/ain/1894692): ``` // full path to text file define("TEXT_FILE", "/home/www/default-error.log"); // number of lines to read from the end of file define("LINES_COUNT", 10); function read_file($file, $lines) { //global $fsize; $handle = fopen($file, "r"); $linecounter = $lines; $pos = -2; $beginning = false; $text = array(); while ($linecounter > 0) { $t = " "; while ($t != "\n") { if(fseek($handle, $pos, SEEK_END) == -1) { $beginning = true; break; } $t = fgetc($handle); $pos --; } $linecounter --; if ($beginning) { rewind($handle); } $text[$lines-$linecounter-1] = fgets($handle); if ($beginning) break; } fclose ($handle); return array_reverse($text); } $fsize = round(filesize(TEXT_FILE)/1024/1024,2); echo "<strong>".TEXT_FILE."</strong>\n\n"; echo "File size is {$fsize} megabytes\n\n"; echo "Last ".LINES_COUNT." lines of the file:\n\n"; $lines = read_file(TEXT_FILE, LINES_COUNT); foreach ($lines as $line) { echo $line; } ```
PHP - Returning the last line in a file?
[ "", "php", "syntax", "fread", "fgets", "" ]